本人在使用httpclient做練習的時候,偶然發現京東萬象上有一個免費的頻道新聞調用api,故嘗試之,因爲官網文檔只給出的java代碼都是封裝後的,所以我自己寫了一遍,又寫了一些註釋。分享代碼,供大家參考。
下面是具體的調用代碼:
public void testDemo() throws JSONException, UnsupportedOperationException, IOException {
String url = "https://way.jd.com/jisuapi/get";//設置接口地址
//設置參數
JSONObject jsonObject = new JSONObject();
jsonObject.put("channel", channel[1]);
jsonObject.put("num", "5");
jsonObject.put("start", "0");
jsonObject.put("appkey", APPKEY);
String uri = changeJsonToArguments(jsonObject);//獲取uri
CloseableHttpClient httpClient = HttpClients.createDefault();//創建並實例化客戶端
HttpGet get = new HttpGet(url+uri);//創建並實例化get接口
HttpResponse response = httpClient.execute(get);//獲取響應
output(parseResponse(response).replaceAll(",", LINE));//輸出相應實體
httpClient.close();//關閉客戶端
}
下面是解析響應實體的封裝方法:
public String parseResponse(HttpResponse response) throws UnsupportedOperationException, IOException {
InputStream inputStream = response.getEntity().getContent();//創建並實例化字節輸入流,使用響應實體作爲輸入流
InputStreamReader reader = new InputStreamReader(inputStream, "utf-8");//創建並實例化字符輸入流,並設置編碼格式
StringBuffer buffer = new StringBuffer(" ");//創建並實例化stringbuffer,存放響應信息
char[] buff = new char[512];//創建並實例化字符數組
int length = 0;//聲明變量length,表示讀取長度
while ((length = reader.read(buff)) != -1) {//循環讀取字符輸入流
String x = new String(buff, 0, length);//獲取讀取到的有效內容
buffer.append(x);//將讀取到的內容添加到stringbuffer中
}
return buffer.toString();
}
下面是獲取到的信息: