HttpClient發送Json數據到指定接口
阿新 • • 發佈:2018-01-06
fault post發送 utf err httppost efault ret http 數據
項目中遇到將Json數據發送到指定接口,於是結合網上利用HttpClient進行發送.
/** * post發送json數據 * @param url * @param param * @return */ private String doPost(String url, JSONObject param) { HttpPost httpPost = null; String result = null; try { HttpClient client = newDefaultHttpClient(); httpPost = new HttpPost(url); if (param != null) { StringEntity se = new StringEntity(param.toString(), "utf-8"); httpPost.setEntity(se); // post方法中,加入json數據 httpPost.setHeader("Content-Type", "application/json"); } HttpResponse response= client.execute(httpPost); if (response != null) { HttpEntity resEntity = response.getEntity(); if (resEntity != null) { result = EntityUtils.toString(resEntity, "utf-8"); } } } catch (Exception ex) { logger.error("發送到接口出錯", ex); } return result; }
HttpClient發送Json數據到指定接口