这两天都在用HttpURLConnection这玩意儿,被其中的一个坑纠结了好久。下面是代码。其中几个细节需要注意,当服务端响应的状态码是大于200时(如401,404,。。。等)需要用getErrorStream()错误流来处理response响应的消息,否则无法获取。我就是被这个坑纠结了一天。
package com.*.common;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
public class HttpClientConnection {
public static final String HTTP_POST = "POST";// post请求
public static final String HTTP_GET = "GET";// get请求
public static final String HTTP_PUT = "PUT"; // put请求
public static final String CHARSET_UTF_8 = "UTF-8";// utf-8字符编码
public static final String CONTENT_TYPE = "application/json";// HTTP内容类型。如果未指定ContentType,默认为TEXT/HTML
public static final String CONTENT_TYPE_FORM_URL = "application/x-www-form-urlencoded";// HTTP内容类型。相当于form表单的形式
public static final int SEND_REQUEST_TIME_OUT = 5000;// 请求超时时间
public static final int READ_TIME_OUT = 5000;// 将读超时时间
/**
* @param requestType 请求类型 (POST||GET||PUT...)
* @param requestUrl 请求地址
* @param requestParams 请求参数 (放在请求体body内的,适用于POST请求,不需要的话传参null)
* @return 返回服务端响应的数据
*
*/
public static String httpConnection(String requestType, String requestUrl, String requestParams){
boolean isDoInput = false;
if (requestParams != null && requestParams.length() > 0) isDoInput = true;
OutputStream outputStream = null;
InputStream inputStream = null;
InputStreamReader inputStreamReader = null;
BufferedReader reader = null;
String tempLine = null;
StringBuffer resultBuffer = new StringBuffer();
try {
HttpURLConnection httpURLConnection = (HttpURLConnection) new URL(requestUrl).openConnection();//http的连接类
// 设置是否向httpUrlConnection输出,因为这个是post请求,参数要放在http正文内,因此需要设为true, 默认情况下是false;
if (isDoInput) {
httpURLConnection.setDoOutput(true);
httpURLConnection.setRequestProperty("Content-Length", String.valueOf(requestParams.length()));
}
httpURLConnection.setDoInput(true);//设置是否从httpUrlConnection读入
httpURLConnection.setRequestMethod(requestType);//设定请求的方法
httpURLConnection.setRequestProperty("Charset", CHARSET_UTF_8);//设置字符编码
httpURLConnection.setRequestProperty("Content-Type", CONTENT_TYPE);//设置内容类型
httpURLConnection.setConnectTimeout(SEND_REQUEST_TIME_OUT); //设置一个指定的超时值(以毫秒为单位)
httpURLConnection.setReadTimeout(READ_TIME_OUT);//将读超时设置为指定的超时,以毫秒为单位。
httpURLConnection.setUseCaches(false);//Post请求不能使用缓存
httpURLConnection.connect();//连接
//post请求的时候参数需要放在请求体内
if (isDoInput) {
outputStream = httpURLConnection.getOutputStream();
outputStream.write(requestParams.getBytes(CHARSET_UTF_8));
outputStream.flush();
}
int responseCode = httpURLConnection.getResponseCode();
//当responseCode 在200以上的时候必须用getErrorStream()错误流来处理response响应的消息,否则无法获取
if (responseCode >= 300) {
reader = new BufferedReader(new InputStreamReader(httpURLConnection.getErrorStream(),CHARSET_UTF_8));
while ((tempLine = reader.readLine()) != null) {
resultBuffer.append(tempLine);
}
throw new Exception( "HTTP Request is not success, Response code is " + responseCode + ", And Response message is " + resultBuffer.toString());
}
//responseCode 等于200的时候用getInputStream()正常流就ok
if (responseCode == HttpURLConnection.HTTP_OK) {
reader = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream(),CHARSET_UTF_8));
while ((tempLine = reader.readLine()) != null) {
resultBuffer.append(tempLine);
}
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}catch (Exception e) {
e.printStackTrace();
} finally {
closeAll(outputStream,reader,inputStreamReader,inputStream);
}
//最后返回服务端响应的内容
return resultBuffer.toString();
}
/**
* 关闭所有流
* @param outputStream
* @param reader
* @param inputStreamReader
* @param inputStream
*/
private static void closeAll(OutputStream outputStream, BufferedReader reader,InputStreamReader inputStreamReader, InputStream inputStream) {
try {
if (outputStream != null) {
outputStream.close();
}
} catch (Exception e) {
e.printStackTrace();
}
try {
if (reader != null) {
reader.close();
}
} catch (Exception e) {
e.printStackTrace();
}
try {
if (inputStreamReader != null) {
inputStreamReader.close();
}
} catch (Exception e) {
e.printStackTrace();
}
try {
if (inputStream != null) {
inputStream.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}