一个完整的用java客户端使用httpClient请求网页并返回的方法


import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import net.sf.json.JSONObject;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;

import net.hitina.adam.action.Action;
import net.hitina.adam.action.RequestEnv;
import net.hitina.adam.action.ResponseEnv;


public class Action extends Action { // action根目录在"webroot/WEB-INF/applicationContext.xml"中有配置


/**
*
*/
public void sfsbgs(RequestEnv request, ResponseEnv response) {


String baseUrl = "http://000.000.000.000:8080";
String url = "/webroot/xxx.jsp";


//http客户端连接国税接口
HttpClient httpClient = HttpClients.createDefault();
//网址链接
HttpPost post = new HttpPost(baseUrl+url);
//参数队列
List<NameValuePair> params = new ArrayList<NameValuePair>();
//传参,参数名,参数值
params.add(new BasicNameValuePair("CSM","CSZ"));//税收档案编号


RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(60000).setConnectTimeout(60000).build();
post.setConfig(requestConfig);
Map resultMap = null;
try {
post.setEntity(new UrlEncodedFormEntity(params,"utf-8"));
HttpResponse re = httpClient.execute(post);
String rtn = new String(readInputStream(re.getEntity().getContent()),"utf-8");
JSONObject jsonObject = JSONObject.fromObject(rtn);
resultMap = (Map) jsonObject;
} catch (IOException e) {
System.out.println("method begin "+ "|" + "当前时间=" + new Date().getTime() + "调用XX方法开始");
}finally {
post.releaseConnection();
}

response.setMessage(resultMap.toString());

}

private static byte[] readInputStream(InputStream inStream) throws IOException {
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
//创建一个Buffer字符串
byte[] buffer = new byte[1024];
//每次读取的字符串长度,如果为-1,代表全部读取完毕
int len ;
//使用一个输入流从buffer里把数据读取出来
while( (len=inStream.read(buffer)) != -1 ){
//用输出流往buffer里写入数据,中间参数代表从哪个位置开始读,len代表读取的长度
outStream.write(buffer, 0, len);
}
//关闭输入流
inStream.close();
//把outStream里的数据写入内存
byte[] b = outStream.toByteArray();
outStream.close();
return b;
}

}

原文地址:https://www.cnblogs.com/ZenoLiang/p/8018009.html