HttpClient獲取第三方接口數據以及解析獲取json


初到公司實習,需要通過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;
}

 


免責聲明!

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



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