调用第三方API的方法HttpClient

https://www.cnblogs.com/enjoyjava/p/8886949.html

Java调用API很简单,主要分为三步:

    ①找到要调用的API接口

   ②向指定URL添加参数发送请求

   ③对返回的字符串进行处理

java调用API的方式:

https://blog.csdn.net/qq_33655674/article/details/79592305

 

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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
我用的API接口是在易源数据上找到的,上面有很多可以免费使用的接口
 
https://www.showapi.com/
 
 
 
当找好了要使用的API那么就是发送请求了,这里我选择的是图灵机器人,我们来看一下它的接口要求:
 
 
 
上面说明了它的接口地址、返回格式以及请求方式
 
那么它的请求参数有两个,其中info是必须的,也就是我们发送向图灵机器人要说的的话。
 
 
 
返回是一个JSON字符串,这里我们只需要text的内容即可
 
  
 
  
 
下面我们具体来调用一下,首先新建一个Java工程,并加入以下jar包,
 
 
 
其中前6个是处理JSON字符串必须的,最后一个servlet-api是用于发送http求用的。
 
然后新建一个名为Talk的Java类,具体代码如下
 
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
  
  
import net.sf.json.JSONObject;
  
public class Talk {
     
    public static String result(String info) {
        //接口地址
        String requestUrl = "http://route.showapi.com/60-27"
        //params用于存储要请求的参数
        Map params = new HashMap();
      //showapi_appid的值,把###替换成你的appid
        params.put("showapi_appid","###");
      //我们请求的字符串
        params.put("info",info);
      //数字签名,###填你的数字签名,可以在你的个人中心看到
        params.put("showapi_sign","###");
      //调用httpRequest方法,这个方法主要用于请求地址,并加上请求参数
        String string = httpRequest(requestUrl,params);
        //处理返回的JSON数据并返回
        JSONObject pageBean = JSONObject.fromObject(string).getJSONObject("showapi_res_body");
        return pageBean.getString("text");
    }
     
    private static String httpRequest(String requestUrl,Map params) { 
        //buffer用于接受返回的字符
        StringBuffer buffer = new StringBuffer();
        try
            //建立URL,把请求地址给补全,其中urlencode()方法用于把params里的参数给取出来
            URL url = new URL(requestUrl+"?"+urlencode(params)); 
            //打开http连接
            HttpURLConnection httpUrlConn = (HttpURLConnection) url.openConnection(); 
            httpUrlConn.setDoInput(true); 
            httpUrlConn.setRequestMethod("GET"); 
            httpUrlConn.connect(); 
             
            //获得输入
            InputStream inputStream = httpUrlConn.getInputStream(); 
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8"); 
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader); 
   
            //将bufferReader的值给放到buffer里
            String str = null
            while ((str = bufferedReader.readLine()) != null) { 
                buffer.append(str); 
            
            //关闭bufferReader和输入流
            bufferedReader.close(); 
            inputStreamReader.close(); 
            inputStream.close(); 
            inputStream = null
            //断开连接
            httpUrlConn.disconnect();
             
        } catch (Exception e) { 
            e.printStackTrace(); 
        
            //返回字符串
        return buffer.toString(); 
    
     
    public static String urlencode(Map<String,Object>data) {
        //将map里的参数变成像 showapi_appid=###&showapi_sign=###&的样子
        StringBuilder sb = new StringBuilder();
        for (Map.Entry i : data.entrySet()) {
            try {
                sb.append(i.getKey()).append("=").append(URLEncoder.encode(i.getValue()+"","UTF-8")).append("&");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }
        return sb.toString();
    }
    //测试是否有效
    public static void main(String[] args) {
     
        System.out.println(result("你好啊"));
    }
  
}
运行结果如下:
 
 
 
至此就完成了API的调用

  

HttpClient 是Apache Jakarta Common 下的子项目,可以用来提供高效的、最新的、功能丰富的支持 HTTP 协议的客户端编程工具包,并且它支持 HTTP 协议最新的版本和建议。

 

在开发中经常遇到和第三方公司接口对接,需要拿到对方提供的数据或者是给对方提供

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
package test;
  
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
  
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
  
import com.alibaba.fastjson.JSONObject;
  
public class InterfaceRequest {
  
    public static void main(String[] args) {
        String url = "https://www.jianliyisheng.com/api/site/getprovincedata";
        HttpClient client = HttpClients.createDefault();
        //默认post请求
        HttpPost post = new HttpPost(url);
        //拼接多参数
        JSONObject json = new JSONObject();
        json.put("uid", "79");
        json.put("key", "d86e33fb43036df9f9c29ff8085ac653");
        json.put("timestamp", "1562296283");
        json.put("typekey", "wshh");
  
        try {
            post.addHeader("Content-type", "application/json; charset=utf-8");
            post.setHeader("Accept", "application/json");
            post.setEntity(new StringEntity(json.toString(), Charset.forName("utf-8")));
            HttpResponse httpResponse = client.execute(post);
  
            HttpEntity entity = httpResponse.getEntity();
            System.err.println("状态:" + httpResponse.getStatusLine());
            System.err.println("参数:" + EntityUtils.toString(entity));
        } catch (UnsupportedEncodingException e1) {
            e1.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
  

  

posted @   小虾米的java梦  阅读(3659)  评论(0编辑  收藏  举报
编辑推荐:
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
阅读排行:
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 地球OL攻略 —— 某应届生求职总结
· 提示词工程——AI应用必不可少的技术
· Open-Sora 2.0 重磅开源!
· 周边上新:园子的第一款马克杯温暖上架
点击右上角即可分享
微信分享提示