Android 开发工具类 29_sendPOSTRequest

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      * @return
24      */
25     private static boolean sendPOSTRequest(String path, Map<String, String> params, String encoding) throws Exception{
26         //  title=liming&length=30
27         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 }

 

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。