以往我们提交Http Get请求和Post请求时,一般会根据请求方式分别编写方法进行调用,以下方法则将两种请求的调用方式进行了整合,这样以后调用请求的时候就不需要考虑请求方式是Get还是Post,通通只要调用此方法就行了。代码如下:
public static ServiceResult sendRequest(String url, String obj, Map<String, String> headers, RequestMethod requestMethod, ContentType contentType) throws IOException {
//返回对象,包含businessObject(返回数据)、success(是否成功返回)、
//message(返回信息,一般是错误信息)、responseCode(返回码)等属性
ServiceResult result = new ServiceResult();
//Get提交时直接在url中拼接参数,obj是已经拼接好的参数字符串
if (requestMethod.toString().equals("GET") && obj.length() > 0) {
url = url + "?" + obj;
}
URL requestUrl = new URL(url);
HttpURLConnection connection=null;
StringBuffer sbBuffer = null;
try {
//打开连接,设置连接参数
connection = (HttpURLConnection) requestUrl.openConnection();
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setRequestMethod(requestMethod.toString());
//设置内容类型,默认为json
if (contentType == null) {
connection.setRequestProperty("Content-Type", "application/json");
} else {
connection.setRequestProperty("Content-Type",contentType);
}
connection.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; SV1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)");
connection.setRequestProperty("Accept", "*/*");
//设置请求头,请求头信息存在map中,因此需要循环遍历出来进行设置
if (headers != null) {
for (Iterator iter = headers.keySet().iterator(); iter.hasNext();){
String name = (String) iter.next();
String value = String.valueOf(headers.get(name));
connection.setRequestProperty(name, value);
}
}
connection.setReadTimeout(2000000);
connection.setConnectTimeout(2000000);
connection.connect();
//如果是post请求,则需要将参数写入到输出流中
OutputStream outputStream = connection.getOutputStream();
outputStream.write(obj.toString().getBytes());
outputStream.flush();
outputStream.close();
//获取返回结果码
int code = connection.getResponseCode();
if (code == 200) {//返回成功的结果码
//从输入流中读取返回信息
InputStreamReader inputStreamReader = new InputStreamReader(connection.getInputStream());
BufferedReader reader = new BufferedReader(inputStreamReader);
sbBuffer = new StringBuffer("");
String lines;
while ((lines = reader.readLine()) != null) {
lines = new String(lines.getBytes(), "utf-8");
sbBuffer.append(lines);
}
reader.close();
inputStreamReader.close();
//将返回信息设置到返回对象中
result.setResponseCode(200);
result.setIsSuccess(true);
result.setBusinessObject(sbBuffer.toString());
} else {//返回失败
//将返回失败信息设置到返回对象中
result.setBusinessObject(connection.getResponseMessage());
result.setMessage(connection.getResponseMessage());
result.setResponseCode(connection.getResponseCode());
result.setIsSuccess(false);
}
//断开连接
connection.disconnect();
} catch (IOException e) {
e.printStackTrace();
//将异常信息设置到返回对象中
result.setIsSuccess(false);
result.setMessage(e.getMessage());
result.setResponseCode(0);
}
return result;
}