HTTP访问的两种方式(HttpClient和HttpURLConnection)
程序员文章站
2022-03-04 09:25:26
...
直接上代码
使用HttpClient
NameValuePair nameValuePair1 = new BasicNameValuePair("name", "yang"); NameValuePair nameValuePair2 = new BasicNameValuePair("pwd","123123"); List nameValuePairs = new ArrayList(); nameValuePairs.add(nameValuePair1); nameValuePairs.add(nameValuePair2); String validateURL = "http://10.0.2.2:8080/testhttp1/TestServlet"; try { HttpParams httpParams = new BasicHttpParams(); HttpConnectionParams.setConnectionTimeout(httpParams,5000); //设置连接超时为5秒 HttpClient client = new DefaultHttpClient(httpParams); // 生成一个http客户端发送请求对象 HttpPost httpPost = new HttpPost(urlString); //设定请求方式 if (nameValuePairs!=null && nameValuePairs.size()!=0) { //把键值对进行编码操作并放入HttpEntity对象中 httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs,HTTP.UTF_8)); } HttpResponse httpResponse = client.execute(httpPost); // 发送请求并等待响应 // 判断网络连接是否成功 if (httpResponse.getStatusLine().getStatusCode() != 200) { System.out.println("网络错误异常!!!!"); return false; } HttpEntity entity = httpResponse.getEntity(); // 获取响应里面的内容 inputStream = entity.getContent(); // 得到服务气端发回的响应的内容(都在一个流里面) // 得到服务气端发回的响应的内容(都在一个字符串里面) // String strResult = EntityUtils.toString(entity); } catch (Exception e) { System.out.println("这是异常!"); }
使用HttpURLConnection
String validateURL="http://10.0.2.2:8080/testhttp1/TestServlet?name=yang&pwd=123123"; try { URL url = new URL(validateUrl); //创建URL对象 //返回一个URLConnection对象,它表示到URL所引用的远程对象的连接 HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setConnectTimeout(5000); //设置连接超时为5秒 conn.setRequestMethod("GET"); //设定请求方式 conn.connect(); //建立到远程对象的实际连接 //返回打开连接读取的输入流 DataInputStream dis = new DataInputStream(conn.getInputStream()); //判断是否正常响应数据 if (conn.getResponseCode() != HttpURLConnection.HTTP_OK) { System.out.println("网络错误异常!!!!"); return false; } } catch (Exception e) { e.printStackTrace(); System.out.println("这是异常!"); } finally { if (conn != null) { conn.disconnect(); //中断连接 } }