java模拟post请求,HttpURLConnection--代码积累
public JSONObject postRequest(Map<String,String> paramMap,String URL) throws Exception {
?
JSONObject paramJson = new JSONObject(paramMap);
System.out.println(paramJson.toString());
// 創(chuàng)建url資源
? ? ? ? URL url = new URL(URL);
? ? ? ? // 建立http連接
? ? ? ? HttpURLConnection conn = (HttpURLConnection) url.openConnection();
? ? ? ? // 設(shè)置允許輸出
? ? ? ? conn.setDoOutput(true);
? ? ? ? conn.setDoInput(true);
? ? ? ? // 設(shè)置不用緩存
? ? ? ? conn.setUseCaches(false);
? ? ? ? // 設(shè)置傳遞方式
? ? ? ? conn.setRequestMethod("POST");
? ? ? ? // 設(shè)置維持長連接
? ? ? ? conn.setRequestProperty("Connection", "Keep-Alive");
? ? ? ? // 設(shè)置文件字符集:
? ? ? ? conn.setRequestProperty("Charset", "UTF-8");
? ? ? ? //轉(zhuǎn)換為字節(jié)數(shù)組
? ? ? ? byte[] data = (paramJson.toString()).getBytes();
? ? ? ? // 設(shè)置文件長度
? ? ? ? conn.setRequestProperty("Content-Length", String.valueOf(data.length));
? ? ? ? // 設(shè)置文件類型:
? ? ? ? conn.setRequestProperty("contentType", "application/json");
?
? ? ? ? // 開始連接請求
? ? ? ? conn.connect();
? ? ? ? OutputStream? out = conn.getOutputStream();? ? ?
? ? ? ? // 寫入請求的字符串
? ? ? ? out.write((paramJson.toString()).getBytes());
? ? ? ? out.flush();
? ? ? ? out.close();
?
? ? ? ? String str = null;
? ? ? ? // 請求返回的狀態(tài)
? ? ? ? if (conn.getResponseCode() == 200) {
? ? ? ? ? ? // 請求返回的數(shù)據(jù)
? ? ? ? ? ? InputStream in = conn.getInputStream();? ? ? ? ? ?
? ? ? ? ? ? try {
? ? ? ? ? ? ? ? byte[] data1 = new byte[in.available()];
? ? ? ? ? ? ? ? in.read(data1);
? ? ? ? ? ? ? ? // 轉(zhuǎn)成字符串
? ? ? ? ? ? ? ? str = new String(data1);
? ? ? ? ? ? ? ? System.out.println(str);
? ? ? ? ? ? } catch (Exception e1) {
? ? ? ? ? ? ? ? // TODO Auto-generated catch block
? ? ? ? ? ? ? ? e1.printStackTrace();
? ? ? ? ? ? }
? ? ? ? } else {
? ? ? ? ? ? System.out.println("連接失敗");
? ? ? ? }
return new JSONObject(str);
}
轉(zhuǎn)載于:https://www.cnblogs.com/zmdd/p/8377646.html
總結(jié)
以上是生活随笔為你收集整理的java模拟post请求,HttpURLConnection--代码积累的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: C语言实验报告
- 下一篇: NatalieWood-Breathin