標籤:tty ping 解決 entity from lin cep servlet gen
初到公司實習,需要通過http post擷取第三方介面返回的json資料並解析json數組擷取value
@RequestMapping("/getProductName")
@ResponseBody
public ArrayList getProductName(HttpServletRequest request) throws Exception {
HttpPost httpPost = new HttpPost("");
CloseableHttpClient client = HttpClients.createDefault();
String respContent = null;
JSONObject jsonParam = new JSONObject();
StringEntity entity = new StringEntity(jsonParam.toString(),"utf-8");//解決中文亂碼問題
entity.setContentEncoding("UTF-8");
entity.setContentType("application/json");
httpPost.setEntity(entity);
System.out.println();
ArrayList productList = new ArrayList();
try{
HttpResponse resp = client.execute(httpPost);
if(resp.getStatusLine().getStatusCode() == 200) {
HttpEntity he = resp.getEntity();
respContent = EntityUtils.toString(he,"UTF-8");
System.out.println("本處輸出第三方接資料---------------->"+respContent);
JSONObject jsonObject= JSON.parseObject(respContent);
String jsonStr =jsonObject.getString("需要擷取的json中的屬性"); //取出json數組中的某一個屬性
System.out.println("這裡輸出返回產品名稱"+jsonStr);
JSONArray jsonArray = jsonObject.getJSONArray("需要擷取的json中的屬性");
for (int i = 0;i<jsonArray.size();i++){
// Object list = jsonArray.get(i);
//System.out.println(list);
}
JSONObject jo = JSONObject.parseObject(respContent);
System.out.println("=============="+jo);
net.sf.json.JSONObject jsonobj = net.sf.json.JSONObject.fromObject(jo);
net.sf.json.JSONArray jsonArray1 = jsonobj.getJSONArray("需要擷取的json中的屬性");
for(int i=0;i<jsonArray1.size();i++)
{
String productName = (String)jsonArray1.getJSONObject(i).get("json數組中某一個屬性");
System.out.println(productName);
productList.add(productName);
}
}}catch (Exception e){
System.out.println("對接第三方介面出現異常");
}
return productList;
}
HttpClient擷取第三方介面資料以及解析擷取json