android向web提交参数的4种方式总结,附带网站案例源码

第一种:基于http协议通过get方式提交参数

1.对多个参数的封装

 1 public static String get_save(String name, String phone) {
 2         /**
 3          * 出现乱码原因有2个 提交参数没有对中文编码,解决方法:使用URLEncoder.encode(xx,xx)对要提交的汉字转码
 4          * tomatCAT服务器默认采用iso859-1编码,解决方法:把PHP页面保存为UTF-8格式
 5          */
 6         String path = "http://192.168.0.117/testxml/web.php";
 7         Map<String, String> params = new HashMap<String, String>();
 8         try {
 9             params.put("name", URLEncoder.encode(name, "UTF-8"));
10             params.put("phone", phone);
11             return sendgetrequest(path, params);
12         } catch (Exception e) {
13             // TODO Auto-generated catch block
14             e.printStackTrace();
15         }
16         return "提交失败";
17     }
get_save()

2.提交参数

 1 private static String sendgetrequest(String path, Map<String, String> params)
 2             throws Exception {
 3 
 4         // path="http://192.168.0.117/testxml/web.php?name=xx&phone=xx";
 5         StringBuilder url = new StringBuilder(path);
 6         url.append("?");
 7         for (Map.Entry<String, String> entry : params.entrySet()) {
 8             url.append(entry.getKey()).append("=");
 9             url.append(entry.getValue()).append("&");
10         }
11         url.deleteCharAt(url.length() - 1);
12         URL url1 = new URL(url.toString());
13         HttpURLConnection conn = (HttpURLConnection) url1.openConnection();
14         conn.setConnectTimeout(5000);
15         conn.setRequestMethod("GET");
16         if (conn.getResponseCode() == 200) {
17             InputStream instream = conn.getInputStream();
18             ByteArrayOutputStream outstream = new ByteArrayOutputStream();
19             byte[] buffer = new byte[1024];
20             while (instream.read(buffer) != -1) {
21                 outstream.write(buffer);
22             }
23             instream.close();
24             return outstream.toString().trim();
25 
26         }
27         return "连接失败";
28     }
sendgetrequest

 第二种:基于http协议通过post方式提交参数

1.对多个参数封装

 1 public static String post_save(String name, String phone) {
 2         /**
 3          * 出现乱码原因有2个 提交参数没有对中文编码,解决方法:使用URLEncoder.encode(xx,xx)对要提交的汉字转码
 4          * tomatCAT服务器默认采用iso859-1编码,解决方法:把PHP页面保存为UTF-8格式
 5          */
 6         String path = "http://192.168.0.117/testxml/web.php";
 7         Map<String, String> params = new HashMap<String, String>();
 8         try {
 9             params.put("name", URLEncoder.encode(name, "UTF-8"));
10             params.put("phone", phone);
11             return sendpostrequest(path, params);
12         } catch (Exception e) {
13             // TODO Auto-generated catch block
14             e.printStackTrace();
15         }
16         return "提交失败";
17     }
post_save

2.提交参数

 1 private static String sendpostrequest(String path,
 2             Map<String, String> params) throws Exception {
 3         // name=xx&phone=xx
 4         StringBuilder data = new StringBuilder();
 5         if (params != null && !params.isEmpty()) {
 6             for (Map.Entry<String, String> entry : params.entrySet()) {
 7                 data.append(entry.getKey()).append("=");
 8                 data.append(entry.getValue()).append("&");
 9             }
10             data.deleteCharAt(data.length() - 1);
11         }
12         byte[] entiy = data.toString().getBytes(); // 生成实体数据
13         URL url = new URL(path);
14         HttpURLConnection conn = (HttpURLConnection) url.openConnection();
15         conn.setReadTimeout(5000);
16         conn.setRequestMethod("POST");
17         conn.setDoOutput(true);// 允许对外输出数据
18         conn.setRequestProperty("Content-Type",
19                 "application/x-www-form-urlencoded");
20         conn.setRequestProperty("Content-Length", String.valueOf(entiy.length));
21         OutputStream outstream = conn.getOutputStream();
22         outstream.write(entiy);
23         if (conn.getResponseCode() == 200) {
24             InputStream instream = conn.getInputStream();
25             ByteArrayOutputStream byteoutstream = new ByteArrayOutputStream();
26             byte[] buffer = new byte[1024];
27             while (instream.read(buffer) != -1) {
28                 byteoutstream.write(buffer);
29             }
30             instream.close();
31             return byteoutstream.toString().trim();
32         }
33         return "提交失败";
34     }
sendpostrequest()

第三种:基于httpclient类通过post方式提交参数

1.对多个参数的封装

 1 public static String httpclient_postsave(String name, String phone) {
 2         /**
 3          * 出现乱码原因有2个 提交参数没有对中文编码,解决方法:使用URLEncoder.encode(xx,xx)对要提交的汉字转码
 4          * tomatCAT服务器默认采用iso859-1编码,解决方法:把PHP页面保存为UTF-8格式
 5          */
 6         String path = "http://192.168.0.117/testxml/web.php";
 7         Map<String, String> params = new HashMap<String, String>();
 8         try {
 9             params.put("name", name);
10             params.put("phone", phone);
11             return sendhttpclient_postrequest(path, params);
12         } catch (Exception e) {
13             // TODO Auto-generated catch block
14             e.printStackTrace();
15         }
16         return "提交失败";
17     }
httpclient_postsave

2.提交参数

 1 private static String sendhttpclient_postrequest(String path,Map<String, String> params) {
 2         List<NameValuePair> pairs = new ArrayList<NameValuePair>();
 3             for (Map.Entry<String, String> entry : params.entrySet()) {
 4                 pairs.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
 5             }
 6         try {
 7             UrlEncodedFormEntity entity=new  UrlEncodedFormEntity(pairs,"UTF-8");
 8             HttpPost httpost=new HttpPost(path);
 9             httpost.setEntity(entity);
10             HttpClient client=new DefaultHttpClient();
11             HttpResponse response= client.execute(httpost);
12         if(response.getStatusLine().getStatusCode()==200){
13             
14             return EntityUtils.toString(response.getEntity(), "utf-8");
15         }
16         } catch (Exception e) {
17             // TODO Auto-generated catch block
18             e.printStackTrace();
19         }
20 
21         return null;
22     }
sendhttpclient_postrequest()

第四种方式:基于httpclient通过get提交参数

1.多个参数的封装

 1 public static String httpclient_getsave(String name, String phone) {
 2         /**
 3          * 出现乱码原因有2个 提交参数没有对中文编码,解决方法:使用URLEncoder.encode(xx,xx)对要提交的汉字转码
 4          * tomatCAT服务器默认采用iso859-1编码,解决方法:把PHP页面保存为UTF-8格式
 5          */
 6         String path = "http://192.168.0.117/testxml/web.php";
 7         Map<String, String> params = new HashMap<String, String>();
 8         try {
 9             params.put("name", name);
10             params.put("phone", phone);
11             return sendhttpclient_getrequest(path, params);
12         } catch (Exception e) {
13             // TODO Auto-generated catch block
14             e.printStackTrace();
15         }
16         return "提交失败";
17     }
httpclient_getsave

2.提交参数

 1     private static String sendhttpclient_getrequest(String path,Map<String, String> map_params) {
 2         List<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
 3             for (Map.Entry<String, String> entry : map_params.entrySet()) {
 4                 params.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
 5             }
 6         String param=URLEncodedUtils.format(params, "UTF-8");
 7         HttpGet getmethod=new HttpGet(path+"?"+param);
 8         HttpClient httpclient=new DefaultHttpClient();
 9         try {
10             HttpResponse response=httpclient.execute(getmethod);
11             if(response.getStatusLine().getStatusCode()==200){
12                 return EntityUtils.toString(response.getEntity(), "utf-8");                
13             }            
14         } catch (ClientProtocolException e) {
15             // TODO Auto-generated catch block
16             e.printStackTrace();
17         } catch (IOException e) {
18             // TODO Auto-generated catch block
19             e.printStackTrace();
20         }        
21         return null;
22     }
sendhttpclient_getrequest()

 4种方式完整测试案例源码

 1 package caicai.web;
 2 
 3 import android.app.Activity;
 4 import android.os.Bundle;
 5 import android.view.View;
 6 import android.widget.EditText;
 7 import android.widget.TextView;
 8 
 9 public class Cai_webActivity extends Activity {
10   
11     TextView success;
12     String name;
13     String phone;    
14     EditText name_view;
15     EditText phone_view;
16     public void onCreate(Bundle savedInstanceState) {
17         super.onCreate(savedInstanceState);
18         setContentView(R.layout.main);      
19         name_view=(EditText) findViewById(R.id.name);       
20         phone_view=(EditText) findViewById(R.id.phone);       
21         success=(TextView) findViewById(R.id.success);
22     }   
23     public void get_save(View v){       
24         name=name_view.getText().toString();
25         phone=phone_view.getText().toString();
26         success.setText(service.get_save(name,phone));         
27     }
28     public void post_save(View v){
29         name=name_view.getText().toString();
30         phone=phone_view.getText().toString();
31         success.setText(service.post_save(name,phone)); 
32     }
33     public void httpclient_postsave(View v){
34         name=name_view.getText().toString();
35         phone=phone_view.getText().toString();
36         success.setText(service.httpclient_postsave(name,phone));       
37     }
38     public void httpclient_getsave(View v){
39         name=name_view.getText().toString();
40         phone=phone_view.getText().toString();
41         success.setText(service.httpclient_getsave(name,phone));       
42     }
43     
44     
45     
46 }
Cai_webActivity.java
  1 package caicai.web;
  2 
  3 import java.io.ByteArrayOutputStream;
  4 import java.io.IOException;
  5 import java.io.InputStream;
  6 import java.io.OutputStream;
  7 import java.net.HttpURLConnection;
  8 import java.net.URL;
  9 import java.net.URLEncoder;
 10 import java.util.ArrayList;
 11 import java.util.HashMap;
 12 import java.util.List;
 13 import java.util.Map;
 14 import org.apache.http.HttpResponse;
 15 import org.apache.http.NameValuePair;
 16 import org.apache.http.client.ClientProtocolException;
 17 import org.apache.http.client.HttpClient;
 18 import org.apache.http.client.entity.UrlEncodedFormEntity;
 19 import org.apache.http.client.methods.HttpGet;
 20 import org.apache.http.client.methods.HttpPost;
 21 import org.apache.http.client.utils.URLEncodedUtils;
 22 import org.apache.http.impl.client.DefaultHttpClient;
 23 import org.apache.http.message.BasicNameValuePair;
 24 import org.apache.http.util.EntityUtils;
 25 
 26 public class service {
 27 
 28     public static String get_save(String name, String phone) {
 29         /**
 30          * 出现乱码原因有2个 提交参数没有对中文编码,解决方法:使用URLEncoder.encode(xx,xx)对要提交的汉字转码
 31          * tomatCAT服务器默认采用iso859-1编码,解决方法:把PHP页面保存为UTF-8格式
 32          */
 33         String path = "http://192.168.0.117/testxml/web.php";
 34         Map<String, String> params = new HashMap<String, String>();
 35         try {
 36             params.put("name", URLEncoder.encode(name, "UTF-8"));
 37             params.put("phone", phone);
 38             return sendgetrequest(path, params);
 39         } catch (Exception e) {
 40             // TODO Auto-generated catch block
 41             e.printStackTrace();
 42         }
 43         return "提交失败";
 44     }
 45 
 46     private static String sendgetrequest(String path, Map<String, String> params)
 47             throws Exception {
 48 
 49         // path="http://192.168.0.117/testxml/web.php?name=xx&phone=xx";
 50         StringBuilder url = new StringBuilder(path);
 51         url.append("?");
 52         for (Map.Entry<String, String> entry : params.entrySet()) {
 53             url.append(entry.getKey()).append("=");
 54             url.append(entry.getValue()).append("&");
 55         }
 56         url.deleteCharAt(url.length() - 1);
 57         URL url1 = new URL(url.toString());
 58         HttpURLConnection conn = (HttpURLConnection) url1.openConnection();
 59         conn.setConnectTimeout(5000);
 60         conn.setRequestMethod("GET");
 61         if (conn.getResponseCode() == 200) {
 62             InputStream instream = conn.getInputStream();
 63             ByteArrayOutputStream outstream = new ByteArrayOutputStream();
 64             byte[] buffer = new byte[1024];
 65             while (instream.read(buffer) != -1) {
 66                 outstream.write(buffer);
 67             }
 68             instream.close();
 69             return outstream.toString().trim();
 70 
 71         }
 72         return "连接失败";
 73     }
 74 
 75     public static String post_save(String name, String phone) {
 76         /**
 77          * 出现乱码原因有2个 提交参数没有对中文编码,解决方法:使用URLEncoder.encode(xx,xx)对要提交的汉字转码
 78          * tomatCAT服务器默认采用iso859-1编码,解决方法:把PHP页面保存为UTF-8格式
 79          */
 80         String path = "http://192.168.0.117/testxml/web.php";
 81         Map<String, String> params = new HashMap<String, String>();
 82         try {
 83             params.put("name", URLEncoder.encode(name, "UTF-8"));
 84             params.put("phone", phone);
 85             return sendpostrequest(path, params);
 86         } catch (Exception e) {
 87             // TODO Auto-generated catch block
 88             e.printStackTrace();
 89         }
 90         return "提交失败";
 91     }
 92 
 93     private static String sendpostrequest(String path,
 94             Map<String, String> params) throws Exception {
 95         // name=xx&phone=xx
 96         StringBuilder data = new StringBuilder();
 97         if (params != null && !params.isEmpty()) {
 98             for (Map.Entry<String, String> entry : params.entrySet()) {
 99                 data.append(entry.getKey()).append("=");
100                 data.append(entry.getValue()).append("&");
101             }
102             data.deleteCharAt(data.length() - 1);
103         }
104         byte[] entiy = data.toString().getBytes(); // 生成实体数据
105         URL url = new URL(path);
106         HttpURLConnection conn = (HttpURLConnection) url.openConnection();
107         conn.setReadTimeout(5000);
108         conn.setRequestMethod("POST");
109         conn.setDoOutput(true);// 允许对外输出数据
110         conn.setRequestProperty("Content-Type",
111                 "application/x-www-form-urlencoded");
112         conn.setRequestProperty("Content-Length", String.valueOf(entiy.length));
113         OutputStream outstream = conn.getOutputStream();
114         outstream.write(entiy);
115         if (conn.getResponseCode() == 200) {
116             InputStream instream = conn.getInputStream();
117             ByteArrayOutputStream byteoutstream = new ByteArrayOutputStream();
118             byte[] buffer = new byte[1024];
119             while (instream.read(buffer) != -1) {
120                 byteoutstream.write(buffer);
121             }
122             instream.close();
123             return byteoutstream.toString().trim();
124         }
125         return "提交失败";
126     }
127 
128     public static String httpclient_postsave(String name, String phone) {
129         /**
130          * 出现乱码原因有2个 提交参数没有对中文编码,解决方法:使用URLEncoder.encode(xx,xx)对要提交的汉字转码
131          * tomatCAT服务器默认采用iso859-1编码,解决方法:把PHP页面保存为UTF-8格式
132          */
133         String path = "http://192.168.0.117/testxml/web.php";
134         Map<String, String> params = new HashMap<String, String>();
135         try {
136             params.put("name", name);
137             params.put("phone", phone);
138             return sendhttpclient_postrequest(path, params);
139         } catch (Exception e) {
140             // TODO Auto-generated catch block
141             e.printStackTrace();
142         }
143         return "提交失败";
144     }
145 
146     private static String sendhttpclient_postrequest(String path,Map<String, String> params) {
147         List<NameValuePair> pairs = new ArrayList<NameValuePair>();
148             for (Map.Entry<String, String> entry : params.entrySet()) {
149                 pairs.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
150             }
151         try {
152             UrlEncodedFormEntity entity=new  UrlEncodedFormEntity(pairs,"UTF-8");
153             HttpPost httpost=new HttpPost(path);
154             httpost.setEntity(entity);
155             HttpClient client=new DefaultHttpClient();
156             HttpResponse response= client.execute(httpost);
157         if(response.getStatusLine().getStatusCode()==200){
158             
159             return EntityUtils.toString(response.getEntity(), "utf-8");
160         }
161         } catch (Exception e) {
162             // TODO Auto-generated catch block
163             e.printStackTrace();
164         }
165 
166         return null;
167     }
168 
169 
170     public static String httpclient_getsave(String name, String phone) {
171         /**
172          * 出现乱码原因有2个 提交参数没有对中文编码,解决方法:使用URLEncoder.encode(xx,xx)对要提交的汉字转码
173          * tomatCAT服务器默认采用iso859-1编码,解决方法:把PHP页面保存为UTF-8格式
174          */
175         String path = "http://192.168.0.117/testxml/web.php";
176         Map<String, String> params = new HashMap<String, String>();
177         try {
178             params.put("name", name);
179             params.put("phone", phone);
180             return sendhttpclient_getrequest(path, params);
181         } catch (Exception e) {
182             // TODO Auto-generated catch block
183             e.printStackTrace();
184         }
185         return "提交失败";
186     }
187 
188     private static String sendhttpclient_getrequest(String path,Map<String, String> map_params) {
189         List<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
190             for (Map.Entry<String, String> entry : map_params.entrySet()) {
191                 params.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
192             }
193         String param=URLEncodedUtils.format(params, "UTF-8");
194         HttpGet getmethod=new HttpGet(path+"?"+param);
195         HttpClient httpclient=new DefaultHttpClient();
196         try {
197             HttpResponse response=httpclient.execute(getmethod);
198             if(response.getStatusLine().getStatusCode()==200){
199                 return EntityUtils.toString(response.getEntity(), "utf-8");                
200             }            
201         } catch (ClientProtocolException e) {
202             // TODO Auto-generated catch block
203             e.printStackTrace();
204         } catch (IOException e) {
205             // TODO Auto-generated catch block
206             e.printStackTrace();
207         }        
208         return null;
209     }
210 
211 }
service.java
 1 <?xml version="1.0" encoding="utf-8"?>
 2 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 3     android:layout_width="fill_parent"
 4     android:layout_height="fill_parent"
 5     android:orientation="vertical" >
 6 
 7     <TextView
 8         android:layout_width="fill_parent"
 9         android:layout_height="wrap_content"
10         android:text="姓名:" />
11 
12     <EditText
13         android:id="@+id/name"
14         android:layout_width="match_parent"
15         android:layout_height="wrap_content" />
16 
17     <TextView
18         android:layout_width="wrap_content"
19         android:layout_height="wrap_content"
20         android:text="电话:" />
21 
22     <EditText
23         android:id="@+id/phone"
24         android:layout_width="match_parent"
25         android:layout_height="wrap_content" />
26  
27     <Button
28         android:layout_width="wrap_content"
29         android:layout_height="wrap_content"
30         android:text="get提交" 
31         android:onClick="get_save"
32         android:layout_marginRight="30px"/>
33     <Button
34         android:layout_width="wrap_content"
35         android:layout_height="wrap_content"
36         android:text="post提交" 
37         android:onClick="post_save"
38         android:layout_marginRight="30px"/>
39 
40     <Button
41         android:layout_width="wrap_content"
42         android:layout_height="wrap_content"
43         android:text="Httpclient_post提交" 
44         android:onClick="httpclient_postsave"
45         android:layout_marginRight="30px"/>
46     <Button 
47         android:layout_width="wrap_content"
48         android:layout_height="wrap_content"
49         android:text="Httpclient_get提交" 
50         android:onClick="httpclient_getsave"/>
51     <TextView
52         android:id="@+id/success"
53         android:layout_width="wrap_content"
54         android:layout_height="wrap_content"
55       />
56 
57 </LinearLayout>
main.xml
 1 <?xml version="1.0" encoding="utf-8"?>
 2 <manifest xmlns:android="http://schemas.android.com/apk/res/android"
 3     package="caicai.web"
 4     android:versionCode="1"
 5     android:versionName="1.0" >
 6 
 7     <uses-sdk android:minSdkVersion="8" />
 8     <uses-permission android:name="android.permission.INTERNET"/>
 9 
10     <application
11         android:icon="@drawable/ic_launcher"
12         android:label="@string/app_name" >
13         <activity
14             android:label="@string/app_name"
15             android:name=".Cai_webActivity" >
16             <intent-filter >
17                 <action android:name="android.intent.action.MAIN" />
18 
19                 <category android:name="android.intent.category.LAUNCHER" />
20             </intent-filter>
21         </activity>
22     </application>
23 
24 </manifest>
AndroidManifest.xml

 

 

posted on 2013-06-23 16:43  clarenceV1  阅读(1058)  评论(0编辑  收藏  举报

导航