解決一次模擬post請求的時候,出現中文???的錯誤
阿新 • • 發佈:2019-01-09
public static String sendPostV2(String postUrl,String params,String headers){ CloseableHttpClient closeableHttpClient = HttpClients.createDefault(); //建立一個連線 try { HttpPost httpPost = new HttpPost(postUrl); //這個防止中文???,很重要,很重要,很重要 httpPost.setEntity(new StringEntity(params, Charset.forName("UTF-8"))); //設定頭資訊 JSONObject jsonObject = JSONObject.parseObject(headers); Set<String> keys = jsonObject.keySet(); for (String key:keys){ httpPost.setHeader(key,jsonObject.getString(key)); } //傳送 HttpResponse httpResponse = closeableHttpClient.execute(httpPost); int returnCode = httpResponse.getStatusLine().getStatusCode(); if (returnCode== HttpStatus.SC_OK){ InputStream inputStream = httpResponse.getEntity().getContent(); BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream)); StringBuffer stringBuffer = new StringBuffer(); String line = ""; while ((line = bufferedReader.readLine())!=null){ stringBuffer.append(line); } return stringBuffer.toString(); } }catch (IOException e){ e.printStackTrace(); JSONObject jsonObject = new JSONObject(); jsonObject.put("code","404"); jsonObject.put("result","no result"); return jsonObject.toJSONString(); } JSONObject jsonObject = new JSONObject(); jsonObject.put("code","404"); jsonObject.put("result","no result"); return jsonObject.toJSONString(); }