調用第三方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();
        }
    }
}
 

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM