HTTPClient to use http/https protocol to send request

使用了spring boot, gradle, commons-httpcomponent3.

目前httpclient 已经有了版本4.

https://github.com/lvfe/httpClient

https://github.com/lvfe/httpclient3

HttpClient相比传统JDK自带的URLConnection,增加了易用性和灵活性

使用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. 释放连接。无论执行方法是否成功,都必须释放连接

        PostMethod postMethod = new PostMethod(postUrl);
       HttpClient client = new HttpClient();
            client.getHttpConnectionManager().getParams()
                    .setConnectionTimeout(50000);// 设置连接时间
        client.getHttpConnectionManager().getParams()
                    .setHeader('Content-Type', 'application/json');// 设置连接时间
int status = client.executeMethod(postMethod); 
if (status == HttpStatus.SC_OK) {
InputStream inputStream = postMethod.setResponseBody(String aaa); BufferedReader br = new BufferedReader(new InputStreamReader( inputStream)); StringBuffer stringBuffer = new StringBuffer();
       }
        //finally
inputStream.close()
br.close();
             postMethod.releaseConnection();
一些要考虑的
1.要set header content-type
2.在post方法中,Httpclient3,传递值为json对象时, 需要把json转成string, getRequestBody(String aa) 已经deprecate了,这时候可以设成getRequestEntity(requestEntity);
requestEntity可以用ByteRequestEntity。文档中有写出替代方法。deprecate的方法最好不要用,防止以后有production issue
3.工程化中,我们希望有清晰的异常处理,返回给用户;不要单单返回500;超时信息放在类上私有变量。
4.gradle build可以设置build task jar.部署用java -jar xxx.jar
5. java可以一个模块一个模块写完

猜你喜欢

转载自www.cnblogs.com/connie313/p/10680379.html