HttpURLConnection post请求 传参数
public static JSONObject post(String urlString, ParamInfo paramInfo) throws Exception {
URL url = new URL(urlString);
JSONObject jsonObject = new JSONObject();
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoInput(true); // 设置该连接可输入
conn.setDoOutput(true); // 设置该连接可输出
conn.setRequestMethod("POST"); // 设置请求方式
conn.setRequestProperty("accept","application/json");
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("Cache-Control", "no-cache");
conn.setRequestProperty("User-Agent", "Mozilla/5.0");
String paramJsonStr = JSON.toJSONString(paramInfo);
// 注释掉的方法没成功
// conn.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
// System.out.println(paramJsonStr);
// DataOutputStream dos = new DataOutputStream(conn.getOutputStream());
// dos.write(paramJsonStr.getBytes("UTF-8"));
// dos.flush();
// dos.close();
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
JSONObject paramJSONObj = JSON.parseObject(paramJsonStr);
Map<String,String> encodedParamMap = new HashMap<>();
for (Map.Entry entry :paramJSONObj.entrySet() ) {
encodedParamMap.put((String)entry.getKey(),java.net.URLEncoder.encode(entry.getValue().toString(), "UTF-8"));
}
String paramStr = encodedParamMap.entrySet().stream().map(a->a.getKey()+"="+a.getValue()).reduce((a,b)->a+"&"+b).get();
System.out.println(paramStr);
PrintWriter pw = new PrintWriter(new BufferedOutputStream(conn.getOutputStream()));
pw.write(paramStr);
pw.flush();
pw.close();
if (HttpURLConnection.HTTP_OK == conn.getResponseCode()) {
//开始处理返回数据
InputStream inputStream = conn.getInputStream();
String jsonString = IOUtils.toString(inputStream, "UTF-8");
inputStream.close();
jsonObject = JSON.parseObject(jsonString, ServerResponse.class).getData();
} else {
throw new Exception(String.format("http request failed,status_code:%d", conn.getResponseCode()));
}
conn.disconnect();
System.out.println(jsonObject);
return jsonObject;
}
版权声明:本文为junior_programmer原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。