第一种:基于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. sap 根据TOCE找 USER_EXIT

    *&---------------------------------------------------------------------* *& Report  ZUSER_EX ...

  2. iOS interface guidelines (界面设计指南)<一>

    一.      为iOS而设计 1.iOS体现的主题: (1)Deference(顺从):UI的存在就是为了让顾客更加容易理解和进行交互,而不是要和顾客玩智力游戏 (2)Clarity(清晰):在每个 ...

  3. HDU5090--Game with Pearls 二分图匹配 (匈牙利算法)

    题意:给N个容器,每个容器里有一定数目的珍珠,现在Jerry开始在管子上面再放一些珍珠,放上的珍珠数必须是K的倍数,可以不放.最后将容器排序,如果可以做到第i个容器上面有i个珍珠,则Jerry胜出,反 ...

  4. 创建XML文档结构

    static void CreateXML(string outputPath) { XmlDocument _xmlDoc = new XmlDocument(); string _xmlNode ...

  5. java 读取XML文件作为配置文件

    首先,贴上自己的实例: XML文件:NewFile.xml(该文件与src目录同级) <?xml version="1.0" encoding="UTF-8&quo ...

  6. web相关问题总结 - imsoft.cnblogs

    1,问题:编辑好的web程序乱码,显示不正常 解决方法:在head中加入一下代码,设置网页使用的语言为中文. <meta http-equiv="Content-Type" ...

  7. abap程序修改程序

    *&———————————————————————**& Report ZHELI_CODE*&*&———————————————————————**&*&am ...

  8. Codeforces Round #313 (Div. 2) A B C 思路 枚举 数学

    A. Currency System in Geraldion time limit per test 2 seconds memory limit per test 256 megabytes in ...

  9. ZOJ 1101 Gamblers

    原题链接 题目大意:一群人聚众赌博.每个人先分别押注不同的金额,可以相互借钱.开奖之后,如果某个人的押注的金额正好等于任何其他三个人金额总和,那这个人就赢得其他三个人的赌注.如果同时有两个以上的赢家, ...

  10. mybatis+spring的简单介绍学习

    参考下面链接 http://mybatis.github.io/spring/zh/index.html