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 }

 

转载于:https://www.cnblogs.com/renzimu/p/4540850.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值