java中如何使用HttpClient调用接口

java使用HttpClient调用接口

HttpClient 提供的主要的功能

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

(2)支持自动转向

(3)支持 HTTPS 协议

(4)支持代理服务器等

直接言归正传了!!!!上代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
public static String sendPutForm(String url,  Map map, String encoding) throws ParseException, IOException {
       String body = "";
       // 打印了一下我推送的json数据
       log.info("我推送的json数据:" + map);
       log.info("我推送的url:" + url);
       CloseableHttpResponse response = null;
       ///获得Http客户端
       CloseableHttpClient client = HttpClients.createDefault();
       List parameters = new ArrayList();
       for (Map.Entry entry : map.entrySet()) {
           System.out.println("key = " + entry.getKey() + ", value = " + entry.getValue());
           parameters.add(new BasicNameValuePair(entry.getKey(),entry.getValue()));
       }
       UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(parameters);
       // 配置信息
       // 设置连接超时时间(单位毫秒)
       // 设置请求超时时间(单位毫秒)
       // socket读写超时时间(单位毫秒)
       RequestConfig requestConfig = RequestConfig.custom()
               .setConnectTimeout(50000).setConnectionRequestTimeout(50000)
               .setSocketTimeout(50000).build();
       // 向指定资源位置上传内容// 创建Post请求
       HttpPost httpPost = new HttpPost(url);
       httpPost.setConfig(requestConfig);
       httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
       httpPost.setEntity(formEntity);
       try {
           response = client.execute(httpPost);
           // 通过response中的getEntity()方法获取返回值
           HttpEntity entity = response.getEntity();
           if (entity != null) {
               body = EntityUtils.toString(entity, encoding);
           }
       } catch (Exception e) {
           // TODO: handle exception
           e.printStackTrace();
       } finally {
           httpPost.abort();
           if (response != null) {
               EntityUtils.consumeQuietly(response.getEntity());
           }
       }
       log.info("body:" + body);
       return body;
   }

代码其实就是这么多,还有好多形式。大家可以参考写一下。

java的HttpClient调用远程接口

httpClient比jdk自带的URLConection更加易用和方便,这里介绍一下使用httpClient来调用远程接口。

首先导入相关的依赖包:

1
2
3
4
5
         
            org.apache.httpcomponents
            httpclient
            4.5.3
         

使用方法

1,创建HttpClient对象;

2,指定请求URL,并创建请求对象,如果是get请求则创建HttpGet对象,post则创建HttpPost对象;

3,如果请求带有参数,对于get请求可直接在URL中加上参数请求,或者使用setParam(HetpParams params)方法设置参数,对于HttpPost请求,可使用setParam(HetpParams params)方法或者调用setEntity(HttpEntity entity)方法设置参数;

4,调用httpClient的execute(HttpUriRequest request)执行请求,返回结果是一个response对象;

5,通过response的getHeaders(String name)或getAllHeaders()可获得请求头部信息,getEntity()方法获取HttpEntity对象,该对象包装了服务器的响应内容。

实例

我使用了property文件来保存不同API对应的链接,也可以除去properties文件的读取代码,直接将变量 API换成所需URL

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URL;
import java.util.Map;
import java.util.Properties;
  
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
  
public class APIUtil {
  
    /**
     * 返回API调用结果
     * @param APIName 接口在api.properties中的名称
     * @param params 访问api所需的参数及参数值
     * @return 此处返回的是JSON格式的数据
     */
    public static String API(String APIName, Map params) {
         String content = "";
         //请求结果 
                CloseableHttpResponse response = null
        //实例化httpclient 
                CloseableHttpClient httpclient = HttpClients.createDefault(); 
        
            try {
             //读取配置文件的URL
                Properties properties = new Properties();
                URL fileURL = APIUtil.class.getClassLoader().getResource("api.properties");
        properties.load(new FileInputStream(new File(fileURL.getFile())));
        String API = properties.getProperty(APIName);
            //构造url请求
            StringBuilder url = new StringBuilder(API);
            if(params!=null && params.size()>0) {
                url.append("?");
                for(Map.Entry entry : params.entrySet()) {
                    url.append(entry.getKey()+"="+entry.getValue()+"&");
                }
                url.substring(0, url.length()-1);
            }
            //实例化get方法 
            HttpGet httpget = new HttpGet(url.toString());
            //执行get请求
        response = httpclient.execute(httpget);
        if(response.getStatusLine().getStatusCode()==200) {
            content = EntityUtils.toString(response.getEntity(),"utf-8");
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
        return content;
    }  
}

执行完毕后返回API提供的数据。

以上为个人经验,希望能给大家一个参考,也希望大家多多支持IT俱乐部。

本文收集自网络,不代表IT俱乐部立场,转载请注明出处。https://www.2it.club/code/java/6935.html
上一篇
下一篇
联系我们

联系我们

在线咨询: QQ交谈

邮箱: 1120393934@qq.com

工作时间:周一至周五,9:00-17:30,节假日休息

关注微信
微信扫一扫关注我们

微信扫一扫关注我们

返回顶部