HttpURLConnection,是在java.net下一种多用途、轻量极的HTTP客户端,使用它来进行HTTP操作可以适用于大多数的应用程序,缺点是自带的API较少。
HttpClient,是apache开发的一个基于HTTP协议的工具类,同时支持http和https请求,里面集成了一些常用的API,方便我们使用。但是httpclient 3.X 以及之前的版本已经不再维护了。取而代之的是现在的HttpComponents,也就是httpclient4.X开始的版本,它把之前的HttpClient主要分成了三个模块。两种版本在使用上也有差异。所以今天在这里,我就介绍一下,自己在开发中使用到的HttpClient 3.1。
一般情况下,我们都会把请求的代码封装成一个工具类,这样在使用的时候就可以很方便的进行调用。
HttpURLConnection请求url工具类
package com.csdn.common.util;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
/**
* http请求处理工具
* */
public class HttpUtil {
/**
* http请求url获取返回信息
* @param reqUrl 拼接了参数的请求连接
* @return String
*/
public static String getRspMsg(String reqUrl) {
String rspMsg = "";
if(!"".equals(reqUrl) && reqUrl != null){
try {
//定义链接
URL url = new URL(reqUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection(); //打开连接
connection.setRequestProperty("Charset", "UTF-8"); //设置参数
connection.setRequestMethod("GET"); //设置请求方式
BufferedReader reader = new BufferedReader(new InputStreamReader(
connection.getInputStream()));//获取远程服务返回的实体数据
String lines;
while ((lines = reader.readLine()) != null) { //数据拼接
System.out.println(lines);
rspMsg += lines;
}
reader.close();
// 断开连接
connection.disconnect();
} catch (Exception e) {
rspMsg = e.getLocalizedMessage();
// e.printStackTrace();
}
}
return rspMsg;
}
/**
* http POST请求url获取返回信息
* @param reqUrl 请求链接
* @param post 请求参数
* @return String
*/
public static String postRspMsg(String reqUrl,String post){
if(!"".equals(reqUrl) && reqUrl != null){
try {
String rspMsg = "";
URL url = new URL(reqUrl);
HttpURLConnection httpConnect = (HttpURLConnection) url.openConnection();
httpConnect.setRequestProperty("Charset", "UTF-8"); //参数编码格式
httpConnect.setRequestMethod("POST"); //请求方式
httpConnect.setDoOutput(true); //是否输出 the application intends to write data to the URL connection
//httpConnect.setDoInput(true); //是否输入
PrintWriter pw = new PrintWriter(httpConnect.getOutputStream()); // 获取URLConnection对象对应的输出流
if(!"".equals(post) && post != null){
pw.write(post); post的请求参数 xx=xx&yy=yy格式的字符串
pw.flush(); //刷新缓存
pw.close();
}
System.out.println(httpConnect.getResponseCode());
BufferedReader bf = new BufferedReader(new InputStreamReader(httpConnect.getInputStream())); //获取返回的信息
String lines;
while((lines = bf.readLine())!=null){
rspMsg += lines; //拼接信息
}
bf.close();
System.out.println(rspMsg); //打印信息
return rspMsg;
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return null;
}
}
HttpClient请求工具类
/**
* 获取get请求响应
* @param url 拼接了请求参数的url
* @return result
*/
public static String httpClientGet(String url){
if(!"".equals(url) && url != null){
HttpClient httpClient = new HttpClient(new HttpClientParams(),new SimpleHttpConnectionManager(true)); //创建实例对象,等同于我们打开浏览器
GetMethod method = new GetMethod(url); //这里指定请求的方式,get、post、delete、head、trace,找到对应的请求方法,等同于我们在浏览器中输入一个链接
httpClient.getParams().setContentCharset("UTF-8"); //设置内容编码格式
String result = "";
try {
httpClient.executeMethod(method); //执行url请求,获取远程服务资源,等同于我们在浏览器上敲了一下回车
System.out.println("statusCode : "+method.getStatusCode());
result = method.getResponseBodyAsString(); //获得返回的实体内容字符串
System.out.println(result);
return result;
} catch (HttpException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
method.releaseConnection();
}
}
return null;
}
/**
* 获取post请求响应
* @param url
* @param params 请求参数 xx=xx&yy=yy格式的字符串
* @return result
*/
public static String httpClientPost(String url,String params) {
if(!"".equals(url) && url != null){
HttpClient httpClient = new HttpClient(new HttpClientParams(),new SimpleHttpConnectionManager(true));
PostMethod method = new PostMethod(url);
httpClient.getParams().setContentCharset("UTF-8"); //设置内容编码格式
try {
if(params != null && !"".equals(params)) {
RequestEntity requestEntity = new StringRequestEntity(params,"application/x-www-form-urlencoded","UTF-8"); //设置请求实体编码格式
method.setRequestEntity(requestEntity);
}
httpClient.executeMethod(method); //请求连接
System.out.println("statusCode: "+method.getStatusCode());
String responses= method.getResponseBodyAsString(); 获得返回的实体内容字符串
System.out.println(responses);
return responses;
} catch (HttpException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
method.releaseConnection(); //关闭请求连接
}
}
return null;
}
在上面的两个功工具类中,请求的路径和参数都拼接到url这个地址中,请求的方法都可以在标注的地方进行修改。
HttpClient可将GetMethod修改为以下几种:
HttpURLConnection的setRequestMethod修改为以下几种:
今天先写到这里,需要3.1jar包的同学,可以跟下面这个链接前往下载:
http://download.csdn.net/detail/tianxiezuomaikong/9765902
官网在线帮助文档(API):
http://hc.apache.org/httpclient-3.x/apidocs/
另外补充一篇,介绍POST 4请求方式的好文:
http://www.cnblogs.com/aaronjs/p/4165049.html
java还有更多有趣的东西等待着我这个好奇人员去发掘呢,生命不止,学无终止。