1. 程式人生 > >Java 中使用HttpURLConnection發起POST 請求

Java 中使用HttpURLConnection發起POST 請求

private void httpUrlConnection() { 
try { 
String pathUrl = "http://172.20.0.206:8082/TestServelt/login.do"; 
// 建立連線 
URL url = new URL(pathUrl); 
HttpURLConnection httpConn = (HttpURLConnection) url.openConnection(); 

 
// //設定連線屬性 
httpConn.setDoOutput(true);// 使用 URL 連線進行輸出 
httpConn.setDoInput(true);// 使用 URL 連線進行輸入 
httpConn.setUseCaches(false);// 忽略快取 
httpConn.setRequestMethod("POST");// 設定URL請求方法 
String requestString = "客服端要以以流方式傳送到服務端的資料..."; 

 
// 設定請求屬性 
// 獲得資料位元組資料,請求資料流的編碼,必須和下面伺服器端處理請求流的編碼一致 
byte[] requestStringBytes = requestString.getBytes(ENCODING_UTF_8); 
httpConn.setRequestProperty("Content-length", "" + requestStringBytes.length); 
httpConn.setRequestProperty("Content-Type", "application/octet-stream"); 
httpConn.setRequestProperty("Connection", "Keep-Alive");// 維持長連線 
httpConn.setRequestProperty("Charset", "UTF-8"); 
// 
String name = URLEncoder.encode("黃武藝", "utf-8"); 
httpConn.setRequestProperty("NAME", name); 

 
// 建立輸出流,並寫入資料 
OutputStream outputStream = httpConn.getOutputStream(); 
outputStream.write(requestStringBytes); 
outputStream.close(); 
// 獲得響應狀態 
int responseCode = httpConn.getResponseCode(); 

 
if (HttpURLConnection.HTTP_OK == responseCode) {// 連線成功 
// 當正確響應時處理資料 
StringBuffer sb = new StringBuffer(); 
String readLine; 
BufferedReader responseReader; 
// 處理響應流,必須與伺服器響應流輸出的編碼一致 
 responseReader = new BufferedReader(new InputStreamReader(httpConn.getInputStream(), ENCODING_UTF_8)); 
while ((readLine = responseReader.readLine()) != null) { 
sb.append(readLine).append("\n"); 
} 
responseReader.close(); 
tv.setText(sb.toString()); 
} 
} catch (Exception ex) { 
ex.printStackTrace(); 
} 

 
}