標籤:
sendPOSTRequest 業務類
1 package com.wangjialin.internet.userInformation.service; 2 3 import java.io.OutputStream; 4 import java.net.HttpURLConnection; 5 import java.net.URL; 6 import java.net.URLEncoder; 7 import java.util.HashMap; 8 import java.util.Map; 9 10 public class UploadUserInformationByPostService {11 public static boolean save(String title, String length) throws Exception{12 String path = "http://192.168.1.103:8080/ServerForPOSTMethod/ServletForPOSTMethod";13 Map<String, String> params = new HashMap<String, String>();14 params.put("name", title);15 params.put("age", length);16 return sendPOSTRequest(path, params, "UTF-8");17 }18 19 /**20 * 發送POST請求21 * @param path 請求路徑22 * @param params 請求參數23 * @return24 */25 private static boolean sendPOSTRequest(String path, Map<String, String> params, String encoding) throws Exception{26 // title=liming&length=3027 StringBuilder sb = new StringBuilder();28 if(params!=null && !params.isEmpty()){29 for(Map.Entry<String, String> entry : params.entrySet()){30 sb.append(entry.getKey()).append("=");31 sb.append(URLEncoder.encode(entry.getValue(), encoding));32 sb.append("&");33 }34 sb.deleteCharAt(sb.length() - 1);35 }36 byte[] data = sb.toString().getBytes();37 38 HttpURLConnection conn = (HttpURLConnection) new URL(path).openConnection();39 conn.setConnectTimeout(5000);40 conn.setRequestMethod("POST");41 conn.setDoOutput(true);//允許對外傳輸資料42 conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");43 conn.setRequestProperty("Content-Length", data.length+"");44 45 OutputStream outStream = conn.getOutputStream();46 outStream.write(data);47 outStream.flush();48 49 if(conn.getResponseCode() == 200){50 return true;51 }52 return false;53 }54 }
Android 開發工具類 29_sendPOSTRequest