做项目的过程中遇到,需要从其它web系统(提供了对外接口)获取某些数据的情况,初步学习了下HttpClient的使用。在这记录一下。
apache官网下载commons-logging、commons-httpclient、commons-codec这几个包。
httpClient其实就是模拟浏览器向服务器端发送请求,然后接收服务器端返回的内容。
package cn.httpClient;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.GetMethod;
public class HttpClientTest {
public static void main(String[] args) {
String url="http://www.baidu.com/index.php?tn="+URLEncoder.encode("sitehao123");//这里可以加参数
String filePath="e:/baidu.html";//将获取到的内容保存到该文件中
downLoadHtmlPage(url,filePath);
}
private static boolean downLoadHtmlPage(String url,String filePath){
try {
HttpClient client = new HttpClient();//定义client对象
client.getHttpConnectionManager().getParams().setConnectionTimeout(2000);//设置连接超时时间为2秒(连接初始化时间)
GetMethod method = new GetMethod(url);//get方式访问下百度的首页
int statusCode = client.executeMethod(method);//获取执行结果的状态,200表示成功(更多的状态值意义,可以自行百度搜索)
if (statusCode != HttpStatus.SC_OK) {
System.out.println("远程访问失败。");
return false;
}
// System.out.println(method.getResponseBodyAsString());//打印获得的内容.如果知道服务器返回的是字符串,或json、xml等有意义的字符串
InputStream in=method.getResponseBodyAsStream();//返回一个html页面,可能包含有图片等二进制数据
//使用字节流
OutputStream out=new FileOutputStream(new File(filePath));//路径存在性的检查就不写了
byte[] tempByte=new byte[1024];
int j=0;
while((j=in.read(tempByte))>0){
out.write(tempByte,0,j);
}
in.close();
out.close();
client.getHttpConnectionManager().closeIdleConnections(1);
}catch(Exception e){
e.printStackTrace();
}finally{
}
return false;
}
}
用记事本打开e:/baidu.html
用IE打开
用get方式访问,会受到url长度的限制,所以httpClient也提供了post访问方式。将上面例子的部分源码修改即可,修改部分如下
HttpClient client = new HttpClient();//定义client对象
client.getHttpConnectionManager().getParams().setConnectionTimeout(2000);//设置连接超时时间为2秒(连接初始化时间)
// GetMethod method = new GetMethod(url);//get方式访问下百度的首页
// int statusCode = client.executeMethod(method);//获取执行结果的状态,200表示成功(更多的状态值意义,可以自行百度搜索)
//改为post访问
PostMethod method=new PostMethod(url);
NameValuePair[] nameValues=new NameValuePair[2];//用数组来传递参数
nameValues[0]=new NameValuePair("longinName","123456");
nameValues[1]=new NameValuePair("passWord","123456");
method.addParameters(nameValues);
int statusCode = client.executeMethod(method);
if (statusCode != HttpStatus.SC_OK) {
System.out.println("远程访问失败。");
return false;
}
还可以发送文件
private static String send( File file) {
String sendTargetUrl=TARGET_URL;//目标服务器的url
String msg=null;
HttpClient client = new HttpClient();
PostMethod method = new PostMethod(sendTargetUrl);
method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false));
method.getParams().setContentCharset("UTF-8");
// 若上传的文件比较大 , 可在此设置最大的连接超时时间
client.getHttpConnectionManager(). getParams().setConnectionTimeout(8000 );
try {
FilePart fp = new FilePart(file.getName(), file);
MultipartRequestEntity mrp = new MultipartRequestEntity(
new Part[] { fp }, method.getParams());
method.setRequestEntity(mrp);
int httpStat = client.executeMethod(method);
System.out.println("httpStat----" + httpStat);
if (httpStat != HttpStatus.SC_OK) {
System.out.println("tbgx dmp:"+"connected fail:" + httpStat);
}
byte[] responseBody = method.getResponseBody();
//System.out.println("responseBody after send :" + new String(responseBody));
msg = new String(responseBody);
} catch (HttpException e) {
System.err.println("Fatal protocol violation: " + e.getMessage());
e.printStackTrace();
} catch (IOException e) {
System.err.println("Fatal transport error: " + e.getMessage());
e.printStackTrace();
} finally {
method.releaseConnection();
}
return msg;
}