java 利用httpclient 3.1 和 httpclient4.1.2发送post请求
来源:互联网 发布:c语言 extern static 编辑:程序博客网 时间:2024/04/28 20:42
ttpclient3和httpclient4都有连接池的概念,但两个版本的接口相差较大。
使用HttpClient发送请求、接收响应很简单,一般需要如下几步即可。
1. 创建HttpClient对象。
2. 创建请求方法的实例,并指定请求URL。如果需要发送GET请求,创建HttpGet对象;如果需要发送POST请求,创建HttpPost对象。
3. 如果需要发送请求参数,可调用HttpGet、HttpPost共同的setParams(HetpParams params)方法来添加请求参数;对于HttpPost对象而言,也可调用setEntity(HttpEntity entity)方法来设置请求参数。
4. 调用HttpClient对象的execute(HttpUriRequest request)发送请求,该方法返回一个HttpResponse。
5. 调用HttpResponse的getAllHeaders()、getHeaders(String name)等方法可获取服务器的响应头;调用HttpResponse的getEntity()方法可获取HttpEntity对象,该对象包装了服务器的响应内容。程序可通过该对象获取服务器的响应内容。
6. 释放连接。无论执行方法是否成功,都必须释放连接
httpclient3
MultiThreadedHttpConnectionManager 是HTTP Client中用来复用连接的连接管理类,可以通过以下方法创建一个client实例
- MultiThreadedHttpConnectionManager n = new MultiThreadedHttpConnectionManager();
- HttpClient client = new HttpClient(n);
以下是httpclient整体类
- public class HttpClientUtils {
-
-
-
- private static final Log logger = LogFactory.getLog(HttpClientUtils.class);
-
-
- private final static int SOCKET_TIMEOUT = 30000;
-
- private final static int CONNECTION_TIMEOUT = 30000;
-
- private final static int MAX_CONN_PRE_HOST = 2;
-
- private final static int MAX_CONN = 2;
-
- private final static HttpConnectionManager httpConnectionManager;
-
- HttpClient httpClient;
-
- static {
- httpConnectionManager = new MultiThreadedHttpConnectionManager();
- HttpConnectionManagerParams params = httpConnectionManager.getParams();
- params.setConnectionTimeout(CONNECTION_TIMEOUT);
- params.setSoTimeout(SOCKET_TIMEOUT);
- params.setDefaultMaxConnectionsPerHost(MAX_CONN_PRE_HOST);
- params.setMaxTotalConnections(MAX_CONN);
- httpClient = new HttpClient(httpConnectionManager);
-
- }
-
-
-
-
-
-
-
-
- public static String doHttpPostRequest(PostMethod post) {
- String resultString = "";
- try {
- httpClient.executeMethod(post);
- if (post.getStatusCode() == HttpStatus.SC_OK) {
- resultString = post.getResponseBodyAsString();
- }
- } catch (HttpException e) {
- logger.error("http请求超时", e);
- } catch (IOException e) {
- logger.error("IO超时", e);
- } finally {
- post.releaseConnection();
- }
- return resultString;
- }
-
-
-
-
-
-
-
- public static String returnError(String reason) {
- StringBuffer buffer = new StringBuffer();
- buffer.append("<?xml version=\"1.0\" encoding=\"GBK\"?>");
- buffer.append("<Response>");
- buffer.append("<Success>false</Success>");
- buffer.append("<reason>");
- buffer.append(reason);
- buffer.append("</reason>");
- buffer.append("</Response>");
- return buffer.toString();
- }
-
- public final static String REQUEST_HEADER = "x-forwarded-for";
-
-
-
-
-
-
-
-
- public static void resetRequestHeader(HttpClient client, String ip) {
- List<Header> headers = new ArrayList<Header>();
- headers.add(new Header(REQUEST_HEADER, ip));
- client.getHostConfiguration().getParams().setParameter("http.default-headers", headers);
- }
- }
以下是测试程序
- public class HttpClientTest {
-
-
-
-
-
-
- private NameValuePair[] buildNameValuePairs(Map<String, String> params) {
- Object[] keys = params.keySet().toArray();
- NameValuePair[] pairs = new NameValuePair[keys.length];
-
- for (int i = 0; i < keys.length; i++) {
- String key = (String) keys[i];
- pairs[i] = new NameValuePair(key, params.get(key));
- }
-
- return pairs;
- }
-
-
-
-
-
-
-
-
-
-
- public String doPost(String url, Map<String, String> params){
- String response = "";
- if (null == url || "".equals(url.trim())) {
- return HttpClientUtil.returnError("推送地址错误[url=" + url + "]");
- }
- if (null == code || "".equals(code.trim())) {
- return HttpClientUtil.returnError("编码错误[code=" + code + "]");
- }
-
- if (null == params || params.size() == 0) {
- return HttpClientUtil.returnError("无传递参数[params.size = 0]");
- }
- PostMethod postMethod = new PostMethod(url);
- postMethod.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "utf-8");
-
- postMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(5, true));
-
- postMethod.setRequestBody(buildNameValuePairs(params));
- response = HttpClientUtils.doHttpPostRequest(postMethod);
- return response;
- }
-
- public static void main(String[] args) {
- String url = "http://localhost/serlvet";
- String xml = "xxxxxxxxxxxxxxxxxxxxxxx";
- HashMap<String, String> params = new HashMap<String, String>();
- params.put("aaaa", xml);
- params.put("bbbb", "bbbxxxx");
- String r = new HttpClientTest().doPost(url,params);
- System.out.println(r);
-
- }
-
- }
httpclient4.1.2
- public class HttpClientUtils2 implements Runnable{
- private static final Log logger = LogFactory.getLog(HttpClientUtils2.class);
- private static ThreadSafeClientConnManager cm = null;
- static {
- int maxTotal = 20;
- int defaultMaxConnection = 50;
- SchemeRegistry schemeRegistry = new SchemeRegistry();
- schemeRegistry.register(new Scheme("http", 80, PlainSocketFactory.getSocketFactory()));
- cm = new ThreadSafeClientConnManager(schemeRegistry);
- try {
- cm.setMaxTotal(maxTotal);
-
- cm.setDefaultMaxPerRoute(defaultMaxConnection);
- } catch (NumberFormatException e) {
- e.printStackTrace();
- }
- }
-
- public static HttpClient getHttpClient() {
- HttpParams params = new BasicHttpParams();
- params.setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
- params.setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 30000);
- params.setParameter(CoreConnectionPNames.SO_TIMEOUT, 30000);
- return new DefaultHttpClient(cm, params);
- }
-
- public static void release() {
- if (cm != null) {
- cm.shutdown();
- }
- }
-
- public static void doHttpPostRequest(String url) {
- InputStream in = null;
- HttpResponse response;
-
- HttpClient client = getHttpClient();
- try {
- response = client.execute(post);
- if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
- HttpEntity entity = response.getEntity();
- long l = entity.getContentLength();
-
- in = entity.getContent();
- int count = 0;
- while (count == 0) {
- count = Integer.parseInt(""+entity.getContentLength());
- }
- byte[] bytes = new byte[count];
- int readCount = 0;
- while (readCount <= count) {
- if(readCount == count)break;
- readCount += in.read(bytes, readCount, count - readCount);
- }
-
-
- }
- if (in != null) {
-
- in.close();
- }
- } catch (ClientProtocolException e) {
- e.printStackTrace();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- }
测试程序
- public class HttpClient2Test {
-
-
-
-
-
-
-
-
-
-
- public String doPost(String url, Map<String, String> params){
- String response = "";
- HttpPost post = new HttpPost(url);
-
- post.getParams().setParameter("http.protocol.content-charset", HTTP.UTF_8);
- post.getParams().setParameter(HTTP.CONTENT_ENCODING, HTTP.UTF_8);
- post.getParams().setParameter(HTTP.CHARSET_PARAM, HTTP.UTF_8);
- post.getParams().setParameter(HTTP.DEFAULT_PROTOCOL_CHARSET, HTTP.UTF_8);
- try {
- post.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
- } catch (UnsupportedEncodingException e1) {
-
- e1.printStackTrace();
- }
- response = HttpClientUtils2.doHttpPostRequest(postMethod);
- return response;
- }
-
- public static void main(String[] args) {
- String url = "http://localhost/serlvet";
- String xml = "xxxxxxxxxxxxxxxxxxxxxxx";
-
- List<NameValuePair> params = new ArrayList<NameValuePair>();
- params.add(new BasicNameValuePair("abc", "xml"));
- String r = new HttpClientTest().doPost(url,params);
- System.out.println(r);
-
- }
-
- }
0 0