1. 程式人生 > >Post請求url接口傳json數據

Post請求url接口傳json數據

col content sendpost request logs amp 長度 todo 發送請求

 1 /**
 2      * 向指定 URL 發送POST方法的請求
 3      * 
 4      * @param url
 5      *            發送請求的 URL
 6      * @param param
 7      *            請求參數,請求參數應該是 name1=value1&name2=value2 的形式。
 8      * @return 所代表遠程資源的響應結果
 9      */
10     public static String sendPostByJson(String url, String jsString) {
11 String result = ""; 12 try { 13 // 創建url資源 14 URL RelUrl = new URL(url); 15 // 建立http連接 16 HttpURLConnection conn = (HttpURLConnection) RelUrl.openConnection(); 17 // 設置允許輸出 18 conn.setDoOutput(true); 19 20 conn.setDoInput(true
); 21 22 // 設置不用緩存 23 conn.setUseCaches(false); 24 // 設置傳遞方式 25 conn.setRequestMethod("POST"); 26 // 設置維持長連接 27 conn.setRequestProperty("Connection", "Keep-Alive"); 28 // 設置文件字符集: 29 conn.setRequestProperty("Charset", "UTF-8");
30 //轉換為字節數組 31 byte[] data = (jsString).getBytes(); 32 // 設置文件長度 33 conn.setRequestProperty("Content-Length", String.valueOf(data.length)); 34 35 // 設置文件類型: 36 conn.setRequestProperty("contentType", "application/json"); 37 38 39 // 開始連接請求 40 conn.connect(); 41 OutputStream out = conn.getOutputStream(); 42 // 寫入請求的字符串 43 out.write((jsString).getBytes()); 44 out.flush(); 45 out.close(); 46 47 System.out.println(conn.getResponseCode()); 48 49 // 請求返回的狀態 50 if (conn.getResponseCode() == 200) { 51 System.out.println("連接成功"); 52 // 請求返回的數據 53 InputStream in = conn.getInputStream(); 54 try { 55 byte[] data1 = new byte[in.available()]; 56 in.read(data1); 57 // 轉成字符串 58 result = new String(data1); 59 System.out.println(result); 60 } catch (Exception e1) { 61 // TODO Auto-generated catch block 62 e1.printStackTrace(); 63 } 64 } else { 65 System.out.println("no++"); 66 } 67 68 } catch (Exception e) { 69 70 } 71 return result; 72 }

Post請求url接口傳json數據