簡單的使用httpclient調介面傳送和接收JSon
阿新 • • 發佈:2019-01-07
由於專案需要,需要用httpclient調其他部門的介面獲取資訊,學習了httpclient的使用方法,demo大概程式碼如下:
寫完後,發現可以使用HttpUtil 工具類調取。這裡就不列出了public static List<Object> doPost(String url, JSONObject json, String infoname, Class cl){ CloseableHttpClient httpclient = HttpClientBuilder.create().build(); HttpPost post = new HttpPost(url); JSONObject response = null; List<Object> list=new ArrayList(); try { StringEntity s = new StringEntity(json.toString()); s.setContentEncoding("UTF-8"); s.setContentType("application/json");//傳送json資料需要設定contentType post.setEntity(s); HttpResponse res = httpclient.execute(post); if(res.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { String result = EntityUtils.toString(res.getEntity());// 返回json格式: System.out.println(result); response = JSONObject.parseObject(result); List<JSONObject> info = (List) response.get(infoname); for (JSONObject s1 : info) { Object netDownData = (Object) JSONObject.toJavaObject(s1, cl); list.add(netDownData); } }else{ logger.error("拉取失敗,錯誤編碼為:"+res.getStatusLine().getStatusCode()); } } catch (Exception e) { throw new RuntimeException(e); } return list; }