HTTPClient

原文http://hc.apache.org/httpcomponents-client-4.5.x/tutorial/html/fundamentals.html

1.简介

HttpClient最重要的作用是执行http方法。处理一个http方法会涉及一个或者多个http request/http response之间的交换,这些都是在内部由httpclient执行。当用户向服务器发送一个request对象,本质是由httpclient传输给目标服务器,返回一个对应的response对象,如果不成功时返回一个异常。

request的处理过程:

CloseableHttpClient httpclient = HttpClients.createDefault();
HttpGet httpget = new HttpGet("http://localhost/");
CloseableHttpResponse response = httpclient.execute(httpget);
try {
    <...>
} finally {
    response.close();
}

2.主要功能

  • 实现了所有 HTTP 的方法(GET,POST,PUT,HEAD 等)

  • 支持自动转向

  • 支持 HTTPS 协议

  • 支持代理服务器等

3.使用HttpClient的基本流程(读取网页内容)

首先创建一个HttpClient(Http客户端)实例,之后确定提交的方法(get/post),最后在实例上执行提交的方法。

/**
*  读取网页内容
*/
HttpCilent httpclient = new HttpClient();
HttpMethod httpMethod = new GetMethod("Http://java.sun.com");
//post方法
//HttpMethod httpMethod = new PostMethod("Http://java.sun.com");

//get方法
httpClient.executeMethod(httpMethod);

//打印服务器返回的状态
System.out.println(method.getStatusLine());
//打印返回的信息
System.out.println(method.getResponseBodyAsString());
//释放连接

method.releaseConnection();

4.访问接口

一般步骤:

        创建一个HttpClient对象;

        构造http请求对象;

        执行HttpClient对象的execute方法,将Http请求对象作为该方法的参数

        读取execute方法返回的HttpResponse结果并解析

        释放连接

public void urlPostJson(String url,String desc,String json) {
        log.info("-----------------------------"+desc+"  Request: " + json);
        
        HttpClient client = new HttpClient(); //创建HTTPClient对象

        client.getHostConfiguration().setProxy("127.0.0.1", 5689);
        client.getHttpConnectionManager().getParams().setConnectionTimeout(3000);//                        
        client.setConnectionTimeout(3000);
        client.getParams().setSoTimeout(3000);//        client.setTimeout(1000);
        client.getParams().setConnectionManagerTimeout(1000);

        PostMethod method = new PostMethod(url);//确定http请求方法

        try {
//            method.setRequestHeader("Content-Type", " application/json; charset=UTF-8");
            method.setRequestBody(new ByteArrayInputStream(json.getBytes("UTF-8")));
//            method.setRequestBody(json);

            int status = client.executeMethod(method);//执行方法

            String res=method.getResponseBodyAsString();//获取返回对象

            log.info("                               status:"+status+"  Resonse: "+res);
        } catch (IOException e) {
            log.error("HttpClient.executeMethod(postMethod) IOException!",e);
        }finally{
            if (method != null) {
                method.releaseConnection();
            }
        }
    }

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值