一、URLConnection:抽象类 URLConnection
是超类,它代表应用程序和 URL 之间的通信链接。此类的实例可用于读取和写入此 URL 引用的资源。
- 通过在 URL 上调用
openConnection
方法创建连接对象。 - 处理设置参数和一般请求属性。
- 使用
connect
方法建立到远程对象的实际连接。 - 远程对象变为可用。远程对象的头字段和内容变为可访问。
二、HttpURLConnection 是 URLConnection的子类。它只是个简单对象,对底层http ,socket做了封装。但仍需配置较多。
每个 HttpURLConnection 实例都可用于生成单个请求,但是其他实例可以透明地共享连接到 HTTP 服务器的基础网络。请求后在 HttpURLConnection 的 InputStream 或 OutputStream 上调用 close() 方法可以释放与此实例关联的网络资源,但对共享的持久连接没有任何影响。如果在调用 disconnect() 时持久连接空闲,则可能关闭基础套接字。
try { // 建立连接 URL url = new URL(baseUrl); HttpURLConnection httpConn = (HttpURLConnection) url.openConnection(); // //设置连接属性 httpConn.setDoOutput(true);// 使用 URL 连接进行输出 httpConn.setDoInput(true);// 使用 URL 连接进行输入 httpConn.setUseCaches(false);// 忽略缓存 httpConn.setRequestMethod("POST");// 设置URL请求方法 httpConn.setConnectTimeout(10000); // 设置连接超时10秒 httpConn.setReadTimeout(10000); // 设置读取超时10秒 // 设置请求属性 // 获得数据字节数据,请求数据流的编码,必须和下面服务器端处理请求流的编码一致 byte[] requestStringBytes = requestString.getBytes("UTF-8"); httpConn.setRequestProperty("Content-length", ""+ requestStringBytes.length); LogUtil.showLogI(TAG,"length====================="+ requestStringBytes.length); httpConn.setRequestProperty("Content-Type","text/xml; charset=utf-8" ); httpConn.setRequestProperty("Connection", "Keep-Alive");// 维持长连接 // 建立输出流,并写入数据 OutputStream outputStream = httpConn.getOutputStream(); outputStream.write(requestStringBytes); outputStream.flush(); outputStream.close(); // 获得响应状态 int responseCode = httpConn.getResponseCode(); LogUtil.showLogI(TAG,"responseCode===========" + responseCode ); if (HttpURLConnection.HTTP_OK == responseCode) {// 连接成功 // 当正确响应时处理数据 StringBuffer sb = new StringBuffer(); String readLine; BufferedReader responseReader; // 处理响应流,必须与服务器响应流输出的编码一致 responseReader = new BufferedReader(new InputStreamReader(httpConn.getInputStream(), "utf-8")); while ((readLine = responseReader.readLine()) != null) { sb.append(readLine).append("\n"); } responseReader.close(); ResponseResult = sb.toString(); //System.out.println("response ============" + ResponseResult); LogUtil.showLogI(TAG,"response ============" + ResponseResult ); return getResponseResult(toKen, ResponseResult); } } catch (Exception ex) { ex.printStackTrace(); }三、HttpClient 是一个集成都更高的http客户端。 HttpClient相比传统JDK自带的URLConnection,增加了易用性和灵活性,它不仅使客户端发送HTTP请求变得容易。不需要设置更多的参数等。
/**
* 发送 post请求访问本地应用并根据传递参数不同返回不同结果
*/
public static String postMethod(String url, List<NameValuePair> param) {
// 创建默认的httpClient实例.
CloseableHttpClient httpclient = HttpClients.createDefault();
// 创建httppost
HttpPost httppost = new HttpPost(url);
UrlEncodedFormEntity uefEntity;
String result = null;
try {
uefEntity = new UrlEncodedFormEntity(param, "UTF-8");
httppost.setEntity(uefEntity);
CloseableHttpResponse response = httpclient.execute(httppost);
try {
HttpEntity entity = response.getEntity();
// 打印响应状态
log.error("statusLine", response.getStatusLine());
if (entity != null) {
log.error("Response content length: " + entity.getContentLength());
result = EntityUtils.toString(entity, "UTF-8");
log.error("请求结果======"+result);
}
} finally {
response.close();
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e1) {
e1.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
// 关闭连接,释放资源
try {
httpclient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return result;
}
/**
* 发送 get请求
*/
public String getMethod(String url, List<NameValuePair> param) {
CloseableHttpClient httpclient = HttpClients.createDefault();
try {
// 创建httpget.
HttpGet httpget = new HttpGet(url);
// 执行get请求.
CloseableHttpResponse response = httpclient.execute(httpget);
try {
// 获取响应实体
HttpEntity entity = response.getEntity();
// 打印响应状态
log.error("statusLine", response.getStatusLine());
if (entity != null) {
// 打印响应内容长度
log.error("Response content length: " + entity.getContentLength());
// 打印响应内容
log.error("Response content: " + EntityUtils.toString(entity));
}
} finally {
response.close();
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
// 关闭连接,释放资源
try {
httpclient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}