Android 開發工具類 29_sendPOSTRequest

來源:互聯網
上載者:User

標籤:

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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.