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

1.对多个参数的封装

 public static String 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<String, String> params = new HashMap<String, String>();
try {
params.put("name", URLEncoder.encode(name, "UTF-8"));
params.put("phone", phone);
return sendgetrequest(path, params);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return "提交失败";
}

get_save()

2.提交参数

 private static String sendgetrequest(String path, Map<String, String> params)
throws Exception { // path="http://192.168.0.117/testxml/web.php?name=xx&phone=xx";
StringBuilder url = new StringBuilder(path);
url.append("?");
for (Map.Entry<String, String> entry : params.entrySet()) {
url.append(entry.getKey()).append("=");
url.append(entry.getValue()).append("&");
}
url.deleteCharAt(url.length() - 1);
URL url1 = new URL(url.toString());
HttpURLConnection conn = (HttpURLConnection) url1.openConnection();
conn.setConnectTimeout(5000);
conn.setRequestMethod("GET");
if (conn.getResponseCode() == 200) {
InputStream instream = conn.getInputStream();
ByteArrayOutputStream outstream = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
while (instream.read(buffer) != -1) {
outstream.write(buffer);
}
instream.close();
return outstream.toString().trim(); }
return "连接失败";
}

sendgetrequest

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

1.对多个参数封装

 public static String post_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<String, String> params = new HashMap<String, String>();
try {
params.put("name", URLEncoder.encode(name, "UTF-8"));
params.put("phone", phone);
return sendpostrequest(path, params);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return "提交失败";
}

post_save

2.提交参数

 private static String sendpostrequest(String path,
Map<String, String> params) throws Exception {
// name=xx&phone=xx
StringBuilder data = new StringBuilder();
if (params != null && !params.isEmpty()) {
for (Map.Entry<String, String> entry : params.entrySet()) {
data.append(entry.getKey()).append("=");
data.append(entry.getValue()).append("&");
}
data.deleteCharAt(data.length() - 1);
}
byte[] entiy = data.toString().getBytes(); // 生成实体数据
URL url = new URL(path);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(5000);
conn.setRequestMethod("POST");
conn.setDoOutput(true);// 允许对外输出数据
conn.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
conn.setRequestProperty("Content-Length", String.valueOf(entiy.length));
OutputStream outstream = conn.getOutputStream();
outstream.write(entiy);
if (conn.getResponseCode() == 200) {
InputStream instream = conn.getInputStream();
ByteArrayOutputStream byteoutstream = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
while (instream.read(buffer) != -1) {
byteoutstream.write(buffer);
}
instream.close();
return byteoutstream.toString().trim();
}
return "提交失败";
}

sendpostrequest()

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

1.对多个参数的封装

 public static String httpclient_postsave(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<String, String> params = new HashMap<String, String>();
try {
params.put("name", name);
params.put("phone", phone);
return sendhttpclient_postrequest(path, params);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return "提交失败";
}

httpclient_postsave

2.提交参数

 private static String sendhttpclient_postrequest(String path,Map<String, String> params) {
List<NameValuePair> pairs = new ArrayList<NameValuePair>();
for (Map.Entry<String, String> entry : params.entrySet()) {
pairs.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
}
try {
UrlEncodedFormEntity entity=new UrlEncodedFormEntity(pairs,"UTF-8");
HttpPost httpost=new HttpPost(path);
httpost.setEntity(entity);
HttpClient client=new DefaultHttpClient();
HttpResponse response= client.execute(httpost);
if(response.getStatusLine().getStatusCode()==200){ return EntityUtils.toString(response.getEntity(), "utf-8");
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
} return null;
}

sendhttpclient_postrequest()

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

1.多个参数的封装

 public static String httpclient_getsave(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<String, String> params = new HashMap<String, String>();
try {
params.put("name", name);
params.put("phone", phone);
return sendhttpclient_getrequest(path, params);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return "提交失败";
}

httpclient_getsave

2.提交参数

     private static String sendhttpclient_getrequest(String path,Map<String, String> map_params) {
List<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
for (Map.Entry<String, String> entry : map_params.entrySet()) {
params.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
}
String param=URLEncodedUtils.format(params, "UTF-8");
HttpGet getmethod=new HttpGet(path+"?"+param);
HttpClient httpclient=new DefaultHttpClient();
try {
HttpResponse response=httpclient.execute(getmethod);
if(response.getStatusLine().getStatusCode()==200){
return EntityUtils.toString(response.getEntity(), "utf-8");
}
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}

sendhttpclient_getrequest()

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

 package caicai.web;

 import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView; public class Cai_webActivity extends Activity { TextView success;
String name;
String phone;
EditText name_view;
EditText phone_view;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
name_view=(EditText) findViewById(R.id.name);
phone_view=(EditText) findViewById(R.id.phone);
success=(TextView) findViewById(R.id.success);
}
public void get_save(View v){
name=name_view.getText().toString();
phone=phone_view.getText().toString();
success.setText(service.get_save(name,phone));
}
public void post_save(View v){
name=name_view.getText().toString();
phone=phone_view.getText().toString();
success.setText(service.post_save(name,phone));
}
public void httpclient_postsave(View v){
name=name_view.getText().toString();
phone=phone_view.getText().toString();
success.setText(service.httpclient_postsave(name,phone));
}
public void httpclient_getsave(View v){
name=name_view.getText().toString();
phone=phone_view.getText().toString();
success.setText(service.httpclient_getsave(name,phone));
} }

Cai_webActivity.java

 package caicai.web;

 import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils; public class service { public static String 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<String, String> params = new HashMap<String, String>();
try {
params.put("name", URLEncoder.encode(name, "UTF-8"));
params.put("phone", phone);
return sendgetrequest(path, params);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return "提交失败";
} private static String sendgetrequest(String path, Map<String, String> params)
throws Exception { // path="http://192.168.0.117/testxml/web.php?name=xx&phone=xx";
StringBuilder url = new StringBuilder(path);
url.append("?");
for (Map.Entry<String, String> entry : params.entrySet()) {
url.append(entry.getKey()).append("=");
url.append(entry.getValue()).append("&");
}
url.deleteCharAt(url.length() - 1);
URL url1 = new URL(url.toString());
HttpURLConnection conn = (HttpURLConnection) url1.openConnection();
conn.setConnectTimeout(5000);
conn.setRequestMethod("GET");
if (conn.getResponseCode() == 200) {
InputStream instream = conn.getInputStream();
ByteArrayOutputStream outstream = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
while (instream.read(buffer) != -1) {
outstream.write(buffer);
}
instream.close();
return outstream.toString().trim(); }
return "连接失败";
} public static String post_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<String, String> params = new HashMap<String, String>();
try {
params.put("name", URLEncoder.encode(name, "UTF-8"));
params.put("phone", phone);
return sendpostrequest(path, params);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return "提交失败";
} private static String sendpostrequest(String path,
Map<String, String> params) throws Exception {
// name=xx&phone=xx
StringBuilder data = new StringBuilder();
if (params != null && !params.isEmpty()) {
for (Map.Entry<String, String> entry : params.entrySet()) {
data.append(entry.getKey()).append("=");
data.append(entry.getValue()).append("&");
}
data.deleteCharAt(data.length() - 1);
}
byte[] entiy = data.toString().getBytes(); // 生成实体数据
URL url = new URL(path);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(5000);
conn.setRequestMethod("POST");
conn.setDoOutput(true);// 允许对外输出数据
conn.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
conn.setRequestProperty("Content-Length", String.valueOf(entiy.length));
OutputStream outstream = conn.getOutputStream();
outstream.write(entiy);
if (conn.getResponseCode() == 200) {
InputStream instream = conn.getInputStream();
ByteArrayOutputStream byteoutstream = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
while (instream.read(buffer) != -1) {
byteoutstream.write(buffer);
}
instream.close();
return byteoutstream.toString().trim();
}
return "提交失败";
} public static String httpclient_postsave(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<String, String> params = new HashMap<String, String>();
try {
params.put("name", name);
params.put("phone", phone);
return sendhttpclient_postrequest(path, params);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return "提交失败";
} private static String sendhttpclient_postrequest(String path,Map<String, String> params) {
List<NameValuePair> pairs = new ArrayList<NameValuePair>();
for (Map.Entry<String, String> entry : params.entrySet()) {
pairs.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
}
try {
UrlEncodedFormEntity entity=new UrlEncodedFormEntity(pairs,"UTF-8");
HttpPost httpost=new HttpPost(path);
httpost.setEntity(entity);
HttpClient client=new DefaultHttpClient();
HttpResponse response= client.execute(httpost);
if(response.getStatusLine().getStatusCode()==200){ return EntityUtils.toString(response.getEntity(), "utf-8");
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
} return null;
} public static String httpclient_getsave(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<String, String> params = new HashMap<String, String>();
try {
params.put("name", name);
params.put("phone", phone);
return sendhttpclient_getrequest(path, params);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return "提交失败";
} private static String sendhttpclient_getrequest(String path,Map<String, String> map_params) {
List<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
for (Map.Entry<String, String> entry : map_params.entrySet()) {
params.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
}
String param=URLEncodedUtils.format(params, "UTF-8");
HttpGet getmethod=new HttpGet(path+"?"+param);
HttpClient httpclient=new DefaultHttpClient();
try {
HttpResponse response=httpclient.execute(getmethod);
if(response.getStatusLine().getStatusCode()==200){
return EntityUtils.toString(response.getEntity(), "utf-8");
}
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
} }

service.java

 <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" > <TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="姓名:" /> <EditText
android:id="@+id/name"
android:layout_width="match_parent"
android:layout_height="wrap_content" /> <TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="电话:" /> <EditText
android:id="@+id/phone"
android:layout_width="match_parent"
android:layout_height="wrap_content" /> <Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="get提交"
android:onClick="get_save"
android:layout_marginRight="30px"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="post提交"
android:onClick="post_save"
android:layout_marginRight="30px"/> <Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Httpclient_post提交"
android:onClick="httpclient_postsave"
android:layout_marginRight="30px"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Httpclient_get提交"
android:onClick="httpclient_getsave"/>
<TextView
android:id="@+id/success"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/> </LinearLayout>

main.xml

 <?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="caicai.web"
android:versionCode="1"
android:versionName="1.0" > <uses-sdk android:minSdkVersion="8" />
<uses-permission android:name="android.permission.INTERNET"/> <application
android:icon="@drawable/ic_launcher"
android:label="@string/app_name" >
<activity
android:label="@string/app_name"
android:name=".Cai_webActivity" >
<intent-filter >
<action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application> </manifest>

AndroidManifest.xml

android向web提交参数的4种方式总结,附带网站案例源码的更多相关文章

  1. Spring接收web请求参数的几种方式

    1 查询参数 请求格式:url?参数1=值1&参数2=值2...同时适用于GET和POST方式spring处理查询参数的方法又有几种写法: 方法一:方法参数名即为请求参数名 // 查询参数1 ...

  2. spring mvc获取路径参数的几种方式 - 浅夏的个人空间 - 开源中国社区

    body { font-family: "Microsoft YaHei UI","Microsoft YaHei",SimSun,"Segoe UI ...

  3. 讨论HTTP POST 提交数据的几种方式

    转自:http://www.cnblogs.com/softidea/p/5745369.html HTTP/1.1 协议规定的 HTTP 请求方法有 OPTIONS.GET.HEAD.POST.PU ...

  4. flink01--------1.flink简介 2.flink安装 3. flink提交任务的2种方式 4. 4flink的快速入门 5.source 6 常用算子(keyBy,max/min,maxBy/minBy,connect,union,split+select)

    1. flink简介 1.1 什么是flink Apache Flink是一个分布式大数据处理引擎,可以对有限数据流(如离线数据)和无限流数据及逆行有状态计算(不太懂).可以部署在各种集群环境,对各种 ...

  5. php获取post参数的几种方式 RPC 规定接收取值方式 $GLOBALS['HTTP_RAW_POST_DATA'];

    http://www.cnblogs.com/zhepama/p/4022606.html PHP默认识别的数据类型是application/x-www.form-urlencoded标准的数据类型. ...

  6. 实现web数据同步的四种方式

    http://www.admin10000.com/document/6067.html 实现web数据同步的四种方式 1.nfs实现web数据共享 2.rsync +inotify实现web数据同步 ...

  7. php获取post参数的几种方式

    php获取post参数的几种方式 1.$_POST['paramName'] 只能接收Content-Type: application/x-www-form-urlencoded提交的数据 2.fi ...

  8. ssh框架总结之action接收参数的三种方式

    页面将参数传递给action的三种方式 一是通过属性传值: 将页面和action的的属性值保持一致,在action上写上该属性的set和get方法,这样在页面提交参数的时候,action就会调用set ...

  9. asp传递参数的几种方式

    把下列代码分别加入a.asp和b.asp的<body></body>中,点提交,就可以将a.asp文本框的内容传给b.asp并显示出来 a.ASP <form actio ...

随机推荐

  1. poj1992 数论

    //Accepted 168 KB 969 ms //n!中含有质因数p的个数为t=n/p+n/p^2+n/p^3+... #include <cstdio> #include <c ...

  2. Design Patterns

    经典的<设计模式>一书归纳出23种设计模式,本文按<易学设计模式>一书归纳分类如下:1.创建型模式 前面讲过,社会化的分工越来越细,自然在软件设计方面也是如此,因此对象的创建和 ...

  3. hdoj-2033

    A+B系列: #include "stdio.h"int main(){ int a[3],b[3],c[3],i,n,j,flag; while(~scanf("%d& ...

  4. 使用Qemu调试内核

    利用Qemu进行内核源码级调试 http://blog.csdn.net/gdt_a20/article/details/7231652 用Qemu调试Linux内核 http://blog.chin ...

  5. Bash简介

    Bash(GNU bourne-Again Shell)是一个为GNU计划编写的Unix shell,它是很多Linux平台默认的使用的shell. shell是一个命令解析器,是介于操作系统内核与用 ...

  6. Android屏幕底部弹出DialogFragment(3)

     Android屏幕底部弹出DialogFragment(3) 附录文章1,2的DialogFragment是常规的DialogFragment,但是现在的一些Android开发中,往往需要从底部 ...

  7. javascript:;与javascript:void(0)使用介绍

    有时候我们在编写js过程中,需要触发事件而不需要返回值,那么就可能需要这样的写法 href=”#”,包含了一个位置信息.默认的锚是#top,也就是网页的上端,当连续快速点击此链接时会导致浏览器巨慢甚至 ...

  8. 解决CSS小于12px的文字在谷歌浏览器显示问题

    做前端设计的人经常要接触CSS方面的问题,估计有不少人会遇到Chrome谷歌浏览器中CSS设置字体小于12px显示不正常,强创网络在做magento模板过程中就遇到了,起初以为是自己写的CSS的问题, ...

  9. php-抽象

    //继承//子类可以继承父类的一切//特点:单继承//函数的重写 //多态//当父类引用指向子类实例,由于子类对父类的方法进行了重写,父类引用在调用该方法的时候表现出的不同//如果一个方法需要一个父类 ...

  10. win7 通过命令行压缩文件

    1,下载winrar这款软件(可能要正式版) 2,安装完之后在c:\programe files里找到winrar目录,复制winrar目录里的winRar.exe文件到c盘下的windows目录 3 ...