使用HttpGet 傳送 json格式的引數
阿新 • • 發佈:2019-01-08
由於工作需要使用java實現http客戶端傳送get請求,且引數值為json格式,幾經周折得以實現,現在記錄分享如下:
hashMap 引數例項:
Map<String, Object> indata = new HashMap(); indata.put("berthstatus", 1); indata.put("berthcode", "22333"); indata.put("parkcode", "6688"); Map<String, Object> param = new HashMap(); param.put("indata",indata);
具體實現函式:
protected void requestService(Map<String,Object> reqmap) throws Exception { JSONObject obj = new JSONObject(reqmap); String r = URLEncoder.encode(obj.toString(), "UTF-8"); String reqUrl = "http://192.168.17.35:8888/getParkInfo?jsonString=" + r; System.out.println("請求引數:" + reqUrl); CloseableHttpResponse response = null; CloseableHttpClient client = null; String res = null; HttpGet httpGet = new HttpGet(reqUrl); System.out.println("executing request" + httpGet.getRequestLine()); try { client = HttpClients.createDefault(); response = client.execute(httpGet); if (response.getStatusLine().getStatusCode() == 200) { String result = EntityUtils.toString(response.getEntity()); System.out.println("executing result---連線正常" + result); } else { System.out.println("executing result---伺服器連線異常"); } } catch (Exception e) { System.out.println("Exception================" + e.toString()); } finally { if (response != null) { response.close(); } if (client != null) { client.close(); } } }