搜索
您的当前位置:首页正文

Android向Web提交参数的4种方式总结

来源:爱够旅游网
Android向Web提交参数的4种方式总结

2013年06月27日 10:13供稿中心: 互联网运营部

摘要:Android向Web提交参数的4种方式总结,第一种:基于http协议通过get方式提交参数...

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

1 2 3 4 5 6 7 8 9

publicstaticString get_save(String name, String phone) { /**

* 出现乱码原因有2个 提交参数没有对中文编码,解决方法:使用URLEncoder.encode(xx,xx)对要提交的汉字转码

* tomatCAT服务器默认采用iso859-1编码,解决方法:把PHP页面保存为UTF-8格式 */

String path =\"http://192.168.0.117/testxml/web.php\"; Map params =newHashMap(); try{

params.put(\"name\10

params.put(\"phone\11

returnsendgetrequest(path, params); 12

}catch(Exception e) { 13

// TODO Auto-generated catch block 14

e.printStackTrace(); 15

} 16

return\"提交失败\"; 17 } 18

get_save()

1.对多个参数的封装

1 privatestaticString sendgetrequest(String path, Map params) 2

throwsException { 3

4

//

5 path=\"http://192.168.0.117/testxml/web.php?name=xx&phone=xx\"; 6 StringBuilder url =newStringBuilder(path); 7 url.append(\"?\");

8 for(Map.Entry entry : params.entrySet()) { 9 url.append(entry.getKey()).append(\"=\"); 10 url.append(entry.getValue()).append(\"&\"); 11 }

12 url.deleteCharAt(url.length() -1); 13 URL url1 =newURL(url.toString());

14 HttpURLConnection conn = (HttpURLConnection) url1.openConnection(); 15

conn.setConnectTimeout(5000); 16

conn.setRequestMethod(\"GET\"); 17

if(conn.getResponseCode() ==200) { 18

InputStream instream = conn.getInputStream(); 19

ByteArrayOutputStream outstream 20 =newByteArrayOutputStream(); 21 byte[] buffer =newbyte[1024];

22 while(instream.read(buffer) != -1) { 23 outstream.write(buffer); 24 }

25 instream.close();

26 returnoutstream.toString().trim(); 27 28 }

29 return\"连接失败\"; }

sendgetrequest

2.提交参数

第二种:基于http协议通过post方式提交参数 1.对多个参数封装

1 publicstaticString post_save(String name, String phone) { 2 /**

3 * 出现乱码原因有2个 提交参数没有对中文编码,解决方法:使用URLEncoder.encode(xx,xx)对要提交的汉字转码 4

* tomatCAT服务器默认采用iso859-1编码,解决方法:把PHP页5 面保存为UTF-8格式 6 */

7 String path =\"http://192.168.0.117/testxml/web.php\"; 8 Map params =newHashMap(); 9 try{

10 params.put(\"name\

11 params.put(\"phone\

12 returnsendpostrequest(path, params); 13 }catch(Exception e) {

14 // TODO Auto-generated catch block 15 e.printStackTrace(); 16 }

17 return\"提交失败\"; 18 } post_save

2.提交参数

1 2 3 4 5 6 7 8 9

privatestaticString sendpostrequest(String path,

Map params)throwsException { // name=xx&phone=xx

StringBuilder data =newStringBuilder(); if(params !=null&& !params.isEmpty()) {

for(Map.Entry entry : params.entrySet()) {

data.append(entry.getKey()).append(\"=\"); data.append(entry.getValue()).append(\"&\"); }

10

data.deleteCharAt(data.length() -1); 11

}

12

byte[] entiy = data.toString().getBytes();// 生成实体数据 13

URL url =newURL(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\21 String.valueOf(entiy.length)); 22 OutputStream outstream = conn.getOutputStream(); 23 outstream.write(entiy);

24 if(conn.getResponseCode() ==200) {

25 InputStream instream = conn.getInputStream(); 26 ByteArrayOutputStream =newByteArrayOutputStream(); 27

byte[] buffer =newbyte[1024]; 28

while(instream.read(buffer) != -1) { 29

byteoutstream.write(buffer); 30

} 31

instream.close(); 32

returnbyteoutstream.toString().trim(); 33

} 34

return\"提交失败\"; 35

} sendpostrequest()

byteoutstream

第三种:基于httpclient类通过post方式提交参数 1.对多个参数的封装

publicstaticString httpclient_postsave(String name, String phone) { 1

/** 2

* 出现乱码原因有2个 提交参数没有对中文编码,解决方法:使用3 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 params =newHashMap(); 8

try{ 9

params.put(\"name\10

params.put(\"phone\11

returnsendhttpclient_postrequest(path, params); 12

}catch(Exception e) { 13

// TODO Auto-generated catch block 14

e.printStackTrace(); 15

} 16

return\"提交失败\"; 17

} 18

httpclient_postsave

2.提交参数

1

privatestaticString sendhttpclient_postrequest(String

2 path,Map params) {

3 List pairs =newArrayList(); 4 for(Map.Entry entry : params.entrySet()) { 5

pairs.add(newBasicNameValuePair(entry.getKey(), 6 entry.getValue())); 7 } 8 try{

9 UrlEncodedFormEntity entity=new UrlEncodedFormEntity(pairs,\"UTF-8\"); 10

HttpPost httpost=newHttpPost(path); 11

httpost.setEntity(entity); 12

HttpClient client=newDefaultHttpClient(); 13

HttpResponse response= client.execute(httpost); 14

if(response.getStatusLine().getStatusCode()==200){ 15

16

17 returnEntityUtils.toString(response.getEntity(),\"utf-8\"); 18 }

19 }catch(Exception e) {

20 // TODO Auto-generated catch block 21 e.printStackTrace(); 22 } 23

returnnull;

}

sendhttpclient_postrequest()

第四种方式:基于httpclient通过get提交参数 1.多个参数的封装

publicstaticString httpclient_getsave(String name, String phone) { 1

/** 2

* 出现乱码原因有2个 提交参数没有对中文编码,解决方法:使用3 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 params =newHashMap(); 8

try{ 9

params.put(\"name\10

params.put(\"phone\11

returnsendhttpclient_getrequest(path, params); 12

}catch(Exception e) { 13

// TODO Auto-generated catch block 14

e.printStackTrace(); 15

} 16

return\"提交失败\"; 17

} 18

httpclient_getsave

2.提交参数

sendhttpclient_getrequest(String path,MapString> map_params) { 2

List params 3 =newArrayList();

4 for(Map.Entry entry : map_params.entrySet()) { 5

params.add(newBasicNameValuePair(entry.getKey(), 6 entry.getValue())); 7 }

8 String param=URLEncodedUtils.format(params,\"UTF-8\"); 9 HttpGet getmethod=newHttpGet(path+\"?\"+param); 10 HttpClient httpclient=newDefaultHttpClient(); 11 try{

12 HttpResponse response=httpclient.execute(getmethod); 13 if(response.getStatusLine().getStatusCode()==200){ 14

returnEntityUtils.toString(response.getEntity(),\"utf-8\"); 15

} 16

}catch(ClientProtocolException e) { 17

// TODO Auto-generated catch block 18

e.printStackTrace(); 19

}catch(IOException e) { 20

// TODO Auto-generated catch block 21

e.printStackTrace(); 22

} 23

returnnull; }

sendhttpclient_getrequest()

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

1 packagecaicai.web; 2

3 importandroid.app.Activity; 4 importandroid.os.Bundle; 5 importandroid.view.View; 6 importandroid.widget.EditText; 7 importandroid.widget.TextView; 8

9 publicclassCai_webActivityextendsActivity { 10

11 TextView success; 12 String name; 13 String phone; 14 EditText name_view; 15 EditText phone_view;

16 publicvoidonCreate(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 publicvoidget_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 publicvoidpost_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 publicvoidhttpclient_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 publicvoidhttpclient_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 }

47 Cai_webActivity.java

1 packagecaicai.web; 2

3 importjava.io.ByteArrayOutputStream; 4 importjava.io.IOException; 5 importjava.io.InputStream; 6 importjava.io.OutputStream; 7 importjava.net.HttpURLConnection; 8 importjava.net.URL; 9 importjava.net.URLEncoder; 10 importjava.util.ArrayList; 11 importjava.util.HashMap; 12 importjava.util.List; 13 importjava.util.Map;

14 importorg.apache.http.HttpResponse; 15 importorg.apache.http.NameValuePair;

16 importorg.apache.http.client.ClientProtocolException; 17 importorg.apache.http.client.HttpClient;

18 importorg.apache.http.client.entity.UrlEncodedFormEntity;

19 importorg.apache.http.client.methods.HttpGet; 20 importorg.apache.http.client.methods.HttpPost; 21 importorg.apache.http.client.utils.URLEncodedUtils; 22 importorg.apache.http.impl.client.DefaultHttpClient; 23 importorg.apache.http.message.BasicNameValuePair; 24 importorg.apache.http.util.EntityUtils; 25

26 publicclassservice { 27

28 publicstaticString get_save(String name, String phone) { 29 /**

30 * 出现乱码原因有2个 提交参数没有对中文编码,解决方法:使用URLEncoder.encode(xx,xx)对要提交的汉字转码 31

* tomatCAT服务器默认采用iso859-1编码,解决方法:把PHP页32 面保存为UTF-8格式 33 */

34 String path =\"http://192.168.0.117/testxml/web.php\"; 35 Map params =newHashMap(); 36 try{

37 params.put(\"name\38 params.put(\"phone\

39 returnsendgetrequest(path, params); 40 }catch(Exception e) {

41 // TODO Auto-generated catch block

42 e.printStackTrace(); 43 }

44 return\"提交失败\"; 45 } 46

47 privatestaticString sendgetrequest(String path, Map params) 48

throwsException { 49 50

//

51 path=\"http://192.168.0.117/testxml/web.php?name=xx&phone=xx\"; 52 StringBuilder url =newStringBuilder(path); 53 url.append(\"?\");

54 for(Map.Entry entry : params.entrySet()) { 55 url.append(entry.getKey()).append(\"=\"); 56 url.append(entry.getValue()).append(\"&\"); 57 }

58 url.deleteCharAt(url.length() -1); 59 URL url1 =newURL(url.toString()); 60 HttpURLConnection conn = url1.openConnection(); 61

conn.setConnectTimeout(5000); 62

conn.setRequestMethod(\"GET\"); 63

if(conn.getResponseCode() ==200) { 64

(HttpURLConnection)

65 InputStream instream = conn.getInputStream();

66 ByteArrayOutputStream outstream =newByteArrayOutputStream(); 67

byte[] buffer =newbyte[1024]; 68

while(instream.read(buffer) != -1) { 69

outstream.write(buffer); 70

} 71

instream.close(); 72

returnoutstream.toString().trim(); 73 74

} 75

return\"连接失败\"; 76

} 77 78

publicstaticString post_save(String name, String phone) { 79

/** 80

* 出现乱码原因有2个 提交参数没有对中文编码,解决方法:使用81 URLEncoder.encode(xx,xx)对要提交的汉字转码

82 * tomatCAT服务器默认采用iso859-1编码,解决方法:把PHP页面保存为UTF-8格式 83

*/ 84

String path =\"http://192.168.0.117/testxml/web.php\"; 85

Map params =newHashMap(); 86

try{ 87

88 params.put(\"name\89 params.put(\"phone\

90 returnsendpostrequest(path, params); 91 }catch(Exception e) {

92 // TODO Auto-generated catch block 93 e.printStackTrace(); 94 }

95 return\"提交失败\"; 96 } 97

98 privatestaticString sendpostrequest(String path, 99 Map params)throwsException { 10 // name=xx&phone=xx 0

StringBuilder data =newStringBuilder(); 10

1 if(params !=null&& !params.isEmpty()) {

String> entry : params.entrySet()) 10 for(Map.Entry2 {

10 data.append(entry.getKey()).append(\"=\"); 3

data.append(entry.getValue()).append(\"&\"); 10

4 }

10 data.deleteCharAt(data.length() -1); 5

}

10

6 byte[] entiy = data.toString().getBytes();// 生成实体数据 10 URL url =newURL(path);

7 HttpURLConnection conn url.openConnection(); 10

8 conn.setReadTimeout(5000);

= (HttpURLConnection)

10 conn.setRequestMethod(\"POST\"); 9

conn.setDoOutput(true);// 允许对外输出数据 11

0 conn.setRequestProperty(\"Content-Type\

11 \"application/x-www-form-urlencoded\"); 1

conn.setRequestProperty(\"Content-Length\11String.valueOf(entiy.length)); 2

OutputStream outstream = conn.getOutputStream(); 11

3 outstream.write(entiy);

11 if(conn.getResponseCode() ==200) { 4

InputStream instream = conn.getInputStream(); 11

5 ByteArrayOutputStream =newByteArrayOutputStream();

11

6 byte[] buffer =newbyte[1024]; 11 while(instream.read(buffer) != -1) { 7

byteoutstream.write(buffer); 11

} 8 119

instream.close();

returnbyteoutstream.toString().trim();

byteoutstream

12

} 0

return\"提交失败\"; 12

1 } 12

2

12 publicstaticString httpclient_postsave(String name, String 3 phone) {

12 /** 4

* 出现乱码原因有2个 提交参数没有对中文编码,解决方法:使用12URLEncoder.encode(xx,xx)对要提交的汉字转码 5

* tomatCAT服务器默认采用iso859-1编码,解决方法:把PHP页12面保存为UTF-8格式 6

*/ 12

7 String path =\"http://192.168.0.117/testxml/web.php\"; 12 Map params =newHashMap(); 8

try{ 12

9 params.put(\"name\

13 params.put(\"phone\0

returnsendhttpclient_postrequest(path, params); 13

1 }catch(Exception e) {

13 // TODO Auto-generated catch block 2

e.printStackTrace(); 13

} 3 134

return\"提交失败\"; }

13

5

privatestaticString sendhttpclient_postrequest(String 13

path,Map params) { 6 13

List pairs =newArrayList();

7 for(Map.Entry entry : params.entrySet()) { 13

8 pairs.add(newBasicNameValuePair(entry.getKey(), entry.getValue())); 13

9 }

14 try{ 0

UrlEncodedFormEntity 14UrlEncodedFormEntity(pairs,\"UTF-8\"); 1

HttpPost httpost=newHttpPost(path); 14

2 httpost.setEntity(entity);

entity=new

14 HttpClient client=newDefaultHttpClient(); 3

HttpResponse response= client.execute(httpost); 14

4 if(response.getStatusLine().getStatusCode()==200){ 14 5

14returnEntityUtils.toString(response.getEntity(),\"utf-8\"); 6

}

14

7 }catch(Exception e) {

14 // TODO Auto-generated catch block 8

e.printStackTrace(); 14

} 9 150

returnnull;

15

} 1 15

2

15 publicstaticString httpclient_getsave(String name, String phone) 3 {

15 /** 4

* 出现乱码原因有2个 提交参数没有对中文编码,解决方法:使用15URLEncoder.encode(xx,xx)对要提交的汉字转码 5

* tomatCAT服务器默认采用iso859-1编码,解决方法:把PHP页15面保存为UTF-8格式 6

*/ 15

7 String path =\"http://192.168.0.117/testxml/web.php\"; 15 Map params =newHashMap(); 8

try{ 15

9 params.put(\"name\

16 params.put(\"phone\0

returnsendhttpclient_getrequest(path, params); 16

1 }catch(Exception e) {

16 // TODO Auto-generated catch block 2

e.printStackTrace(); 16

} 3 164

return\"提交失败\"; }

16

5

privatestaticString sendhttpclient_getrequest(String 16

path,Map map_params) { 6 16

List

params

7 =newArrayList(); 16 for(Map.EntryString>

entry

:

16 params.add(newBasicNameValuePair(entry.getKey(), 9 entry.getValue()));

17 } 0

String param=URLEncodedUtils.format(params,\"UTF-8\"); 17

1 HttpGet getmethod=newHttpGet(path+\"?\"+param);

17 HttpClient httpclient=newDefaultHttpClient(); 2

try{ 17

3 HttpResponse response=httpclient.execute(getmethod); 17 if(response.getStatusLine().getStatusCode()==200){ 4

17returnEntityUtils.toString(response.getEntity(),\"utf-8\"); 5

}

17

6 }catch(ClientProtocolException e) { 17 // TODO Auto-generated catch block 7

e.printStackTrace(); 17

}catch(IOException e) { 8 179

// TODO Auto-generated catch block e.printStackTrace();

18

} 0

returnnull; 18

1 } 18

2

18 } 3

service.java 184 185 186 187 188 189 190 191 192 193 194 195 196 19

7 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212

1 2 3 4 5 6 7 8 9

xmlns:android=\"http://schemas.android.com/apk/res/android\" android:layout_width=\"fill_parent\" android:layout_height=\"fill_parent\" android:orientation=\"vertical\">

android:layout_width=\"fill_parent\"

android:layout_height=\"wrap_content\" 10

android:text=\"姓名:\"/> 11 12

android:id=\"@+id/name\" 14

android:layout_width=\"match_parent\" 15

android:layout_height=\"wrap_content\"/> 16 17

android:layout_width=\"wrap_content\" 19

android:layout_height=\"wrap_content\" 20

android:text=\"电话:\"/> 21 22

24 android:id=\"@+id/phone\"

25 android:layout_width=\"match_parent\" 26 android:layout_height=\"wrap_content\"/> 27

28 29 android:layout_width=\"wrap_content\" 30 android:layout_height=\"wrap_content\" 31 android:text=\"get提交\" 32 android:onClick=\"get_save\"

33 android:layout_marginRight=\"30px\"/> 34 35 android:layout_width=\"wrap_content\" 36 android:layout_height=\"wrap_content\" 37 android:text=\"post提交\" 38 android:onClick=\"post_save\" 39 android:layout_marginRight=\"30px\"/> 40

41 42 android:layout_width=\"wrap_content\" 43 android:layout_height=\"wrap_content\" 44 android:text=\"Httpclient_post提交\" 45 android:onClick=\"httpclient_postsave\" 46 android:layout_marginRight=\"30px\"/>

47 48 android:layout_width=\"wrap_content\" 49 android:layout_height=\"wrap_content\" 50 android:text=\"Httpclient_get提交\" 51 android:onClick=\"httpclient_getsave\"/> 52 53 android:id=\"@+id/success\"

54 android:layout_width=\"wrap_content\" 55 android:layout_height=\"wrap_content\" 56 /> 57

58 main.xml

1 2 3 4 5 6 7 8 9

android:icon=\"@drawable/ic_launcher\" 11

android:label=\"@string/app_name\"> 12

android:label=\"@string/app_name\" 14

android:name=\".Cai_webActivity\"> 15

16

17 18

android:name=\"android.intent.category.LAUNCHER\"/> 20

21

22

23

24 25 AndroidManifest.xml

因篇幅问题不能全部显示,请点此查看更多更全内容

Top