第一种:基于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. WABAPI使用

    最近写一个供其他系统调用的接口,决定使用wabapi,以前只是大概了解wabapi是什么东西,没有写过自己的api,从头开始学习. 1.开始创建一个webapi的项目,不得不说VS真的替我们省了好多事 ...

  2. SYN Cookie的原理和实现

          本文主要内容:SYN Cookie的原理,以及它的内核实现. 内核版本:3.6 SYN Flood 下面这段介绍引用自[1]. SYN Flood是一种非常危险而常见的Dos攻击方式.到目 ...

  3. FineUI疑难杂症

    1. 导出excel操作:因为fineui里的按钮自带异步功能,所以要把 EnableAjax="false" DisableControlBeforePostBack=" ...

  4. (spring-第2回【IoC基础篇】)Spring的Schema,基于XML的配置

    要深入了解Spring机制,首先需要知道Spring是怎样在IoC容器中装配Bean的.而了解这一点的前提是,要搞清楚Spring基于Schema的Xml配置方案. 在深入了解之前,必须要先明白几个标 ...

  5. HDOJ-三部曲-1001-Flip Game

    Flip Game Time Limit : 2000/1000ms (Java/Other)   Memory Limit : 131072/65536K (Java/Other) Total Su ...

  6. Makefile总结和反序字符数组,整体右移数组,杨辉三角!

    2015.1.23今天我值日 继续接着昨天Makefile的目标开始记录:第一种:有 .PHNOY声明,但是冒号后面没有依赖文件.PHNOY:clean clean://没有依赖文件 rm *.0 t ...

  7. Magento速度优化

    一.Magento Compiler可以提高 25% 到 50% 速度 Magento的性能一直是大家比较关心的焦点,现在Magento最新的版本 1.3.2.2 增加了 Magento Compil ...

  8. H - 放苹果

      Time Limit:1000MS     Memory Limit:10000KB     64bit IO Format:%I64d & %I64u Submit Status Des ...

  9. tracking 问题解决

    1.dir,或者C++函数读文件名,不推荐.搞乱了名字 2. matio读写矩阵

  10. [转载] 动态链接库dll的 静态加载 与 动态加载

    转载自:http://blog.csdn.net/youxin2012/article/details/11538491 dll 两种链接方式  : 动态链接和静态链接(链接亦称加载)   动态链接是 ...