博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
HttpComponents之httpclient基本使用方法
阅读量:7128 次
发布时间:2019-06-28

本文共 5169 字,大约阅读时间需要 17 分钟。

hot3.png

httpclient的版本是4.3

第一种方式

package http;import org.apache.http.HttpEntity;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.DefaultHttpClient;import org.apache.http.message.BasicNameValuePair;import org.apache.http.util.EntityUtils;import java.io.IOException;import java.util.ArrayList;import java.util.List;public class HttpClient2 {    public static void main(String args[]) throws IOException {        List
 formparams = new ArrayList
();        formparams.add(new BasicNameValuePair("account", ""));        formparams.add(new BasicNameValuePair("password", ""));        HttpEntity reqEntity = new UrlEncodedFormEntity(formparams, "utf-8");        RequestConfig requestConfig = RequestConfig.custom()                .setSocketTimeout(5000)                .setConnectTimeout(5000)                .setConnectionRequestTimeout(5000)                .build();        HttpClient client = new DefaultHttpClient();        HttpPost post = new HttpPost("http://cnivi.com.cn/login");        post.setEntity(reqEntity);        post.setConfig(requestConfig);        HttpResponse response = client.execute(post);        if (response.getStatusLine().getStatusCode() == 200) {            HttpEntity resEntity = response.getEntity();            String message = EntityUtils.toString(resEntity, "utf-8");            System.out.println(message);        } else {            System.out.println("请求失败");        }    }}

第二种方式

这种方式是用了一个http的连接池,同时使用httpbuilder构造合适的http方法。

package http;import org.apache.http.HttpEntity;import org.apache.http.HttpHost;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.methods.HttpUriRequest;import org.apache.http.client.methods.RequestBuilder;import org.apache.http.conn.routing.HttpRoute;import org.apache.http.impl.client.CloseableHttpClient;import org.apache.http.impl.client.HttpClientBuilder;import org.apache.http.impl.client.HttpClients;import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;import org.apache.http.message.BasicNameValuePair;import org.apache.http.util.EntityUtils;import java.io.IOException;import java.util.*;public class HttpClientUtils {    private static PoolingHttpClientConnectionManager connectionManager = null;    private static HttpClientBuilder httpBulder = null;    private static RequestConfig requestConfig = null;    private static int MAXCONNECTION = 10;    private static int DEFAULTMAXCONNECTION = 5;    private static String IP = "cnivi.com.cn";    private static int PORT = 80;    static {        //设置http的状态参数        requestConfig = RequestConfig.custom()                .setSocketTimeout(5000)                .setConnectTimeout(5000)                .setConnectionRequestTimeout(5000)                .build();        HttpHost target = new HttpHost(IP, PORT);        connectionManager = new PoolingHttpClientConnectionManager();        connectionManager.setMaxTotal(MAXCONNECTION);        connectionManager.setDefaultMaxPerRoute(DEFAULTMAXCONNECTION);        connectionManager.setMaxPerRoute(new HttpRoute(target), 20);        httpBulder = HttpClients.custom();        httpBulder.setConnectionManager(connectionManager);    }    public static CloseableHttpClient getConnection() {        CloseableHttpClient httpClient = httpBulder.build();        httpClient = httpBulder.build();        return httpClient;    }    public static HttpUriRequest getRequestMethod(Map
 map, String url, String method) {        List
 params = new ArrayList
();        Set
> entrySet = map.entrySet();        for (Map.Entry
 e : entrySet) {            String name = e.getKey();            String value = e.getValue();            NameValuePair pair = new BasicNameValuePair(name, value);            params.add(pair);        }        HttpUriRequest reqMethod = null;        if ("post".equals(method)) {            reqMethod = RequestBuilder.post().setUri(url)                    .addParameters(params.toArray(new BasicNameValuePair[params.size()]))                    .setConfig(requestConfig).build();        } else if ("get".equals(method)) {            reqMethod = RequestBuilder.get().setUri(url)                    .addParameters(params.toArray(new BasicNameValuePair[params.size()]))                    .setConfig(requestConfig).build();        }        return reqMethod;    }    public static void main(String args[]) throws IOException {        Map
 map = new HashMap
();        map.put("account", "");        map.put("password", "");        HttpClient client = getConnection();        HttpUriRequest post = getRequestMethod(map, "http://cnivi.com.cn/login", "post");        HttpResponse response = client.execute(post);        if (response.getStatusLine().getStatusCode() == 200) {            HttpEntity entity = response.getEntity();            String message = EntityUtils.toString(entity, "utf-8");            System.out.println(message);        } else {            System.out.println("请求失败");        }    }}

=============END=============

转载于:https://my.oschina.net/xinxingegeya/blog/282683

你可能感兴趣的文章
免费高清视频素材下载网站
查看>>
RGW Usage类解析
查看>>
mouseover、mouseout防止多次触发
查看>>
Linux命令行:rpm 命令参数使用详解
查看>>
expdp数据泵自动备份脚本
查看>>
菲波那切数列
查看>>
java 调用存储过程示例版
查看>>
linux之lvm管理及扩容
查看>>
eclipse 查找接口实现类快捷键
查看>>
awk(二)流程控制,数组
查看>>
归并排序
查看>>
Netmask v. Address Prefix Length
查看>>
我的友情链接
查看>>
Unity3D教程:iTween插件的介绍和用法
查看>>
zabbix监控磁盘IO
查看>>
Linux inode分析
查看>>
ospf 区域类型详细
查看>>
Linux下Bash编程之條件判斷详解(二)
查看>>
模板引擎缓存
查看>>
php 5.6.11添加模块
查看>>