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.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 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 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 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 StringBuilder data =newStringBuilder(); if(params !=null&& !params.isEmpty()) { for(Map.Entry 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 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 3 List 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 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,Map List 4 for(Map.Entry 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 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 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 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 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 StringBuilder data =newStringBuilder(); 10 1 if(params !=null&& !params.isEmpty()) { String> entry : params.entrySet()) 10 for(Map.Entry 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 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 List 7 for(Map.Entry 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 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 List params 7 =newArrayList 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 android:layout_height=\"wrap_content\" 10 android:text=\"姓名:\"/> 11 12 android:layout_width=\"match_parent\" 15 android:layout_height=\"wrap_content\"/> 16 17 android:layout_height=\"wrap_content\" 20 android:text=\"电话:\"/> 21 22 25 android:layout_width=\"match_parent\" 26 android:layout_height=\"wrap_content\"/> 27 28 1 2 3 4 5 6 7 8 9 android:label=\"@string/app_name\"> 12 android:name=\".Cai_webActivity\"> 15 24 因篇幅问题不能全部显示,请点此查看更多更全内容