初到公司实习,需要通过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;
}
原文地址:https://www.cnblogs.com/hjy4ever/p/9579872.html