转自:https://www.cnblogs.com/ITtangtang/p/3968093.html
HttpClient简介
HTTP 协议可能是现在 Internet 上使用得最多、最重要的协议了,越来越多的 Java 应用程序需要直接通过 HTTP 协议来访问网络资源。虽然在 JDK 的 java.net 包中已经提供了访问 HTTP 协议的基本功能,但是对于大部分应用程序来说,JDK 库本身提供的功能还不够丰富和灵活。HttpClient 是 Apache Jakarta Common 下的子项目,用来提供高效的、最新的、功能丰富的支持 HTTP 协议的客户端编程工具包,并且它支持 HTTP 协议最新的版本和建议。HttpClient 已经应用在很多的项目中,比如 Apache Jakarta 上很著名的另外两个开源项目 Cactus 和 HTMLUnit 都使用了 HttpClient。更多信息请关注http://hc.apache.org/
HttpClient 功能介绍
以下列出的是 HttpClient 提供的主要的功能,要知道更多详细的功能可以参见 HttpClient 的主页。
-
实现了所有 HTTP 的方法(GET,POST,PUT,HEAD 等)
-
支持自动转向
-
支持 HTTPS 协议
-
支持代理服务器等
使用POST方式提交数据(httpClient)
httpclient使用了单独的一个HttpMethod子类来处理文件的上传,这个类就是MultipartPostMethod,该类已经封装了文件上传的细节,我们要做的仅仅是告诉它我们要上传文件的全路径即可,下面这里将给出关于两种模拟上传方式的代码
第一种:模拟上传url文件(该方式也适合做普通post请求):
/**
* 上传url文件到指定URL
* @param fileUrl 上传图片url
* @param postUrl 上传路径及参数,注意有些中文参数需要使用预先编码 eg : URLEncoder.encode(appName, "UTF-8")
* @return
* @throws IOException
*/
public static String doUploadFile(String postUrl) throws IOException {
if(StringUtils.isEmpty(postUrl))
return null;
String response = "";
PostMethod postMethod = new PostMethod(postUrl);
try {
HttpClient client = new HttpClient();
client.getHttpConnectionManager().getParams()
.setConnectionTimeout(50000);// 设置连接时间
int status = client.executeMethod(postMethod); //发送请求//发送请求//发送请求
if (status == HttpStatus.SC_OK) {
InputStream inputStream = postMethod.getResponseBodyAsStream();
BufferedReader br = new BufferedReader(new InputStreamReader(
inputStream));
StringBuffer stringBuffer = new StringBuffer();
String str = "";
while ((str = br.readLine()) != null) {
stringBuffer.append(str);
}
response = stringBuffer.toString();
} else {
response = "fail";
}
} catch (Exception e) {
e.printStackTrace();
} finally {
// 释放连接
postMethod.releaseConnection();
}
return response;
}
使用GET方式提交数据(httpClient)
public synchronized String httpGet(String url) {
HttpGet httpGet = new HttpGet(url);
try {
httpGet.setHeader("User-Agent", HttpHeader.User_Agent_Firefox);
HttpResponse httpResponse = this.httpClient.execute(httpGet);
int requestStatus = httpResponse.getStatusLine().getStatusCode();
if (requestStatus == HttpStatus.SC_OK) {
byte[] temp = getResponseBody(httpResponse);
String html = new String(temp, HttpHeader.ENCODING_UTF8);
return html;
} else {
byte[] temp = getResponseBody(httpResponse);
String html = new String(temp, HttpHeader.ENCODING_UTF8);
logger.info(requestStatus + "\t" + url);
logger.error(html);
return html;
}
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
logger.error("error", e);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
logger.error("error", e);
} finally {
try {
httpGet.clone();
} catch (CloneNotSupportedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return null;
}
使用PUT方式提交数据(httpClient)
public synchronized String httpPut(String url, String query) {
HttpPut httpPut = new HttpPut(url);
try {
if (query != null) {
StringEntity input = new StringEntity(query, HttpHeader.ENCODING_UTF8);
input.setContentType("application/json");
httpPut.setEntity(input);
}
HttpResponse httpResponse = this.httpClient.execute(httpPut);
int requestStatus = httpResponse.getStatusLine().getStatusCode();
if (requestStatus == HttpStatus.SC_OK) {
byte[] temp = getResponseBody(httpResponse);
String html = new String(temp, HttpHeader.ENCODING_UTF8);
return html;
} else {
byte[] temp = getResponseBody(httpResponse);
String html = new String(temp, HttpHeader.ENCODING_UTF8);
logger.info(requestStatus + "\t" + url);
logger.error(html);
return html;
}
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
logger.error("error", e);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
logger.error("error", e);
} finally {
try {
httpPut.clone();
} catch (CloneNotSupportedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return null;
}