第一种:基于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. Ubuntu 14.10 下grep命令详解

    简介 grep (global search regular expression(RE) and print out the line,全面搜索正则表达式并把行打印出来)是一种强大的文本搜索工具,它 ...

  2. Android res/raw vs assets

    common: 1.两者目录下的文件在打包后会原封不动的保存在apk包中,不会被编译成二进制. difference: 1.res/raw中的文件会被映射到R.java文件中,访问的时候直接使用资源I ...

  3. struts2和servlet同时用(访问servlet时被struts2过滤器拦截问题的解决)

    在同一个项目中间,如果既用到servlet有用了struts2的框架,运行项目时可能无法正常使用servlet,原因是在配置struts2的核心控制器时<url-pattern>/*< ...

  4. Java Proxy

    Client---->Interface A --        -- 代理类     Class AImpl 代理类是动态生成的,借助Proxy类和InvocationHandler接口进行实 ...

  5. 沙盒密探——可实现的js缓存攻击

    我们描述了第一次完全运行在浏览器端的微结构单通道攻击.与其他参和这种类型的相反,这种攻击不再需要攻击者在肉鸡上安装任何软件,为了让攻击更容易,肉鸡仅仅需要浏览哪些攻击者控制的不被信任的网页内容.这会让 ...

  6. 使用java理解程序逻辑 第三章 选择结构一

    if 选择结构: if(条件){       代码块  //条件成立后要执行的代码.可以是一条语句,也可以是一组语句 } 可以处理单一或组合条件的情况. if-else 选择结构: if(条件){   ...

  7. 【转】DOM事件简介

    原文转自:http://blog.jobbole.com/52430/ Click.touch.load.drag.change.input.error.risize — 这些都是冗长的DOM(文档对 ...

  8. beta 阶段的 postmortem 报告

    part一: 用户数:目前约30人 总结:与当初的预算差不多,首先1.第一次开发软件,经验效率不足,那是很正常的事情.2.用户数量少,因为宣传力度还是比较的少.应该加强软件的推广才行. part二: ...

  9. C#实现union以及lock的使用

    1.什么是Union类型数据 联合(Union)是一种特殊的类,一个联合中的数据成员在内存中的存储是互相重叠的.每个数据成员都在相同的内存地址开始. 分配给联合的存储区数量是“要包含它最大的数据成员” ...

  10. matio使用

    http://na-wiki.csc.kth.se/mediawiki/index.php/MatIO (1)build根据教程 (2)sudo ldconfig (3)写main根据链接:修改几个类 ...