String url = "";
String res = "";
HttpClient httpClient = new HttpClient();
PostMethod postMethod = new PostMethod(url);
JSONObject jsonObject = new JSONObject();
Gson gson = new Gson();
Map resmap = new HashMap();
try {
postMethod.addRequestHeader("accept", "*/*");
postMethod.addRequestHeader("connection", "Keep-Alive");
//设置json格式传送
postMethod.addRequestHeader("Content-Type", "application/json;charset=utf-8");
//postMethod.addRequestHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.81 Safari/537.36");
//添加请求参数
jsonObject.put("A",A );
jsonObject.put("B", B);
String toJson = jsonObject.toString();
LOGGER.info("调用接口地址:"+url);
LOGGER.info("发送数据"+toJson);
RequestEntity se = new StringRequestEntity(toJson, "application/json", "UTF-8");
postMethod.setRequestEntity(se);
int code = httpClient.executeMethod(postMethod);
LOGGER.info(code);
if (code == 200) {
InputStream in = postMethod.getResponseBodyAsStream();
//这里的编码规则要与上面的相对应
BufferedReader br = new BufferedReader(new InputStreamReader(in,"UTF-8"));
String tempbf;
StringBuffer html = new StringBuffer(100);
while ((tempbf = br.readLine()) != null) {
html.append(tempbf +"\n");
}
// 返回值中文乱码 res = postMethod.getResponseBodyAsString();
LOGGER.info("接口返回结果:"+html.toString());
resmap = gson.fromJson(html.toString(), resmap.getClass());
String resCode = (String) resmap.get("code");
}
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
HttpClient POST请求及返回值中文乱码
最新推荐文章于 2025-03-14 13:55:54 发布