调用第三方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

我用的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 协议最新的版本和建议。

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

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();
        }
    }
}
 

  

原文地址:https://www.cnblogs.com/fengli9998/p/12204459.html