1. 发送请求到服务器有几种方式

(1)HttpURLConnection

(2)Httpclient 同步框架

(3)AsyncHttpClient 异步框架 (https://github.com/loopj/android-async-http 下载源码和lib包)

示例代码(3)示例 (最简便实用)

public void asyncGet(View v){
final String username = et_username.getText().toString().trim();
final String password = et_password.getText().toString().trim();
String uri = "http://192.168.1.100:8080/TestLogin/servlet/Login?"
+ "username=" + URLEncoder.encode(username)
+ "&password=" + URLEncoder.encode(password); AsyncHttpClient client = new AsyncHttpClient();
client.get(uri, new AsyncHttpResponseHandler() {
@Override
public void onSuccess(String response) {
Toast.makeText(MainActivity.this, response, Toast.LENGTH_SHORT).show();
} @Override
public void onFailure(Throwable error, String content) {
Toast.makeText(MainActivity.this, content, Toast.LENGTH_SHORT).show();
} });
} public void asyncPost(View v){
final String username = et_username.getText().toString().trim();
final String password = et_password.getText().toString().trim();
String uri = "http://192.168.1.100:8080/TestLogin/servlet/Login"; AsyncHttpClient client = new AsyncHttpClient();
RequestParams params = new RequestParams();
params.put("username", username);
params.put("password", password); client.post(uri, params, new AsyncHttpResponseHandler() {
@Override
public void onSuccess(String response) {
Toast.makeText(MainActivity.this, response, Toast.LENGTH_SHORT).show();
} @Override
public void onFailure(Throwable error, String content) {
Toast.makeText(MainActivity.this, content, Toast.LENGTH_SHORT).show();
} });
}

示例代码 (1)(2)示例

public class MainActivity extends Activity {
private EditText et_password;
private EditText et_username; public void loginByGet(View paramView) {
String str1 = this.et_password.getText().toString().trim();
String str2 = this.et_username.getText().toString().trim();
if ((TextUtils.isEmpty(str1)) || (TextUtils.isEmpty(str2))) {
Toast.makeText(this, "用户名密码不能为空", 1).show();
return;
}
try {
String str3 = String
.valueOf("http://192.168.1.100:8080/web/LoginServlet?");
StringBuilder localStringBuilder1 = new StringBuilder(str3)
.append("name=");
String str4 = URLEncoder.encode(str2, "UTF-8");
StringBuilder localStringBuilder2 = localStringBuilder1
.append(str4).append("&password=");
String str5 = URLEncoder.encode(str1, "UTF-8");
String str6 = str5;
HttpURLConnection localHttpURLConnection = (HttpURLConnection) new URL(
str6).openConnection();
localHttpURLConnection.setRequestMethod("GET");
localHttpURLConnection.setConnectTimeout(5000);
localHttpURLConnection
.setRequestProperty(
"User-Agent",
"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET4.0C; .NET4.0E; .NET CLR 2.0.50727)");
if (localHttpURLConnection.getResponseCode() == 200) {
String str7 = StreamTools.readFromStream(localHttpURLConnection
.getInputStream());
Toast.makeText(this, str7, 1).show();
return;
}
} catch (Exception localException) {
localException.printStackTrace();
Toast.makeText(this, "登陆失败", 1).show();
return;
}
Toast.makeText(this, "登陆失败,http响应吗不正确.", 1).show();
} public void loginByPost(View paramView) {
String str1 = this.et_password.getText().toString().trim();
String str2 = this.et_username.getText().toString().trim();
if ((TextUtils.isEmpty(str1)) || (TextUtils.isEmpty(str2))) {
Toast.makeText(this, "用户名密码不能为空", 1).show();
return;
}
try {
HttpURLConnection localHttpURLConnection = (HttpURLConnection) new URL(
"http://192.168.1.100:8080/web/LoginServlet")
.openConnection();
localHttpURLConnection.setRequestMethod("POST");
localHttpURLConnection.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
StringBuilder localStringBuilder1 = new StringBuilder("name=");
String str3 = URLEncoder.encode(str2, "UTF-8");
StringBuilder localStringBuilder2 = localStringBuilder1
.append(str3).append("&password=");
String str4 = URLEncoder.encode(str1, "UTF-8");
String str5 = str4;
String str6 = String.valueOf(str5.length());
String str7 = str6;
localHttpURLConnection.setRequestProperty("Content-Length", str7);
//允许对外写数据
localHttpURLConnection.setDoOutput(true);
OutputStream localOutputStream = localHttpURLConnection
.getOutputStream();
byte[] arrayOfByte = str5.getBytes();
localOutputStream.write(arrayOfByte);
localOutputStream.flush();
if (localHttpURLConnection.getResponseCode() == 200) {
String str8 = StreamTools.readFromStream(localHttpURLConnection
.getInputStream());
Toast.makeText(this, str8, 1).show();
localOutputStream.close();
return;
}
} catch (Exception localException) {
Toast.makeText(this, "post登陆失败", 1).show();
return;
}
Toast.makeText(this, "post登陆失败,http响应吗不正确.", 1).show();
} protected void onCreate(Bundle paramBundle) {
super.onCreate(paramBundle);
setContentView(R.layout.activity_main);
EditText localEditText1 = (EditText) findViewById(R.id.et_username);
this.et_username = localEditText1;
EditText localEditText2 = (EditText) findViewById(R.id.et_password);
this.et_password = localEditText2;
} /**
* 采用httpclient的方式 用get提交数据到服务器
*/ public void loginByClientGet(View view) {
String password = et_password.getText().toString().trim();
String name = et_username.getText().toString().trim();
if (TextUtils.isEmpty(name) || TextUtils.isEmpty(password)) {
Toast.makeText(this, "用户名密码不能为空", 1).show();
return;
}
// 1.打开浏览器
HttpClient client = new DefaultHttpClient();
// 2.输入浏览器的地址
String uri = "http://192.168.1.100:8080/web/LoginServlet?" + "name="
+ URLEncoder.encode(name) + "&password="
+ URLEncoder.encode(password);
HttpGet httpGet = new HttpGet(uri);
// 3.敲回车.
try {
HttpResponse response = client.execute(httpGet);
int code = response.getStatusLine().getStatusCode();
if (code == 200) {
InputStream is = response.getEntity().getContent();
String result = StreamTools.readFromStream(is);
Toast.makeText(this, result, 1).show();
} else {
Toast.makeText(this, "服务器异常", 1).show();
}
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(this, "访问网络异常", 1).show();
} } /**
* 采用httpclient post数据到服务器
*/
public void loginByClientPost(View view) {
String password = et_password.getText().toString().trim();
String name = et_username.getText().toString().trim();
if (TextUtils.isEmpty(name) || TextUtils.isEmpty(password)) {
Toast.makeText(this, "用户名密码不能为空", 1).show();
return;
}
try {
// 1.创建一个浏览器
HttpClient client = new DefaultHttpClient();
// 2.准备一个连接
HttpPost post = new HttpPost(
"http://192.168.1.100:8080/web/LoginServlet");
// 要向服务器提交的数据实体
List<NameValuePair> parameters = new ArrayList<NameValuePair>();
parameters.add(new BasicNameValuePair("name", name));
parameters.add(new BasicNameValuePair("password", password));
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(parameters,
"utf-8");
post.setEntity(entity);
// 3.敲回车
HttpResponse response = client.execute(post);
int code = response.getStatusLine().getStatusCode();
if (code == 200) {
InputStream is = response.getEntity().getContent();
String result = StreamTools.readFromStream(is);
Toast.makeText(this, result, 1).show();
} else {
Toast.makeText(this, "服务器异常", 1).show();
}
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(this, "client post 失败", 1).show();
} }
}

Android -- 提交数据到服务器,Get Post方式, 异步Http框架提交的更多相关文章

  1. Android 采用post方式提交数据到服务器

    接着上篇<Android 采用get方式提交数据到服务器>,本文来实现采用post方式提交数据到服务器 首先对比一下get方式和post方式: 修改布局: <LinearLayout ...

  2. Android 采用get方式提交数据到服务器

    首先搭建模拟web 服务器,新建动态web项目,servlet代码如下: package com.wuyudong.web; import java.io.IOException; import ja ...

  3. Android提交数据到服务器的两种方式四种方法

    本帖最后由 yanghe123 于 2012-6-7 09:58 编辑 Android应用开发中,会经常要提交数据到服务器和从服务器得到数据,本文主要是给出了利用http协议采用HttpClient方 ...

  4. Android 采用HttpClient提交数据到服务器

    在前几篇文章中<Android 采用get方式提交数据到服务器><Android 采用post方式提交数据到服务器>介绍了android的两种提交数据到服务器的方法 本文继续介 ...

  5. Android(java)学习笔记210:采用post请求提交数据到服务器(qq登录案例)

    1.POST请求:  数据是以流的方式写给服务器 优点:(1)比较安全 (2)长度不限制 缺点:编写代码比较麻烦   2.我们首先在电脑模拟下POST请求访问服务器的场景: 我们修改之前编写的logi ...

  6. Android(java)学习笔记153:采用post请求提交数据到服务器(qq登录案例)

    1.POST请求:  数据是以流的方式写给服务器 优点:(1)比较安全 (2)长度不限制 缺点:编写代码比较麻烦   2.我们首先在电脑模拟下POST请求访问服务器的场景: 我们修改之前编写的logi ...

  7. Android(java)学习笔记209:采用get请求提交数据到服务器(qq登录案例)

    1.GET请求:    组拼url的路径,把提交的数据拼装url的后面,提交给服务器. 缺点:(1)安全性(Android下提交数据组拼隐藏在代码中,不存在安全问题)  (2)长度有限不能超过4K(h ...

  8. Android(java)学习笔记152:采用get请求提交数据到服务器(qq登录案例)

    1.GET请求:    组拼url的路径,把提交的数据拼装url的后面,提交给服务器. 缺点:(1)安全性(Android下提交数据组拼隐藏在代码中,不存在安全问题)  (2)长度有限不能超过4K(h ...

  9. 采用httpclient提交数据到服务器

    1)Get提交数据 效果演示:

随机推荐

  1. php中mysql_pconnect()的实现方式.

    网上有人说要想让mysql_pconnect正常稳定的工作,必须保证mysql max_connect参数设定大于或等于apache的最大线程(进程)数.这句话是有一定道理的.这要简单了解mysql_ ...

  2. Python高级特性(1):Iterators、Generators和itertools(转)

    译文:Python高级特性(1):Iterators.Generators和itertools [译注]:作为一门动态脚本语言,Python 对编程初学者而言很友好,丰富的第三方库能够给使用者带来很大 ...

  3. java获取src下文件

    方式一: InputStream in = Test.class .getResourceAsStream("/env.properties"); URL url = Test.c ...

  4. Unity3D优化技巧系列七

    笔者介绍:姜雪伟,IT公司技术合伙人.IT高级讲师,CSDN社区专家,特邀编辑.畅销书作者,国家专利发明人;已出版书籍:<手把手教你架构3D游戏引擎>电子工业出版社和<Unity3D ...

  5. 【开发者笔记】解析具有合并单元格的Excel

    最近公司让做各种数据表格的导入导出,就涉及到电子表格的解析,做了这么多天总结一下心得. 工具:NOPI 语言:C# 目的:因为涉及到导入到数据库,具有合并单元格的多行必然要拆分,而NPOI自动解析的时 ...

  6. APP移动端自动化测试工具选型“兵器谱”一览(主流开源工具)

    (下面大多数工具都是开源工具,在github,码云等开源平台都能找到) "测试那点事儿”在看到360旗下的测试团队整理的关于目前APP移动端自动化相关的工具,觉得总结的很到位,对目前大多数中 ...

  7. Windows下IIS+PHP 5.2的安装与配置

    Windows下IIS+PHP 5.2的安装与配置   Windows下PHP的安装虽然简单,但如果不注意方法,仍然会让你头疼.此外,PHP 5.2版本与之前4.x版本也有一些不同,所以有必要记录一下 ...

  8. logstash安装

    1.下载并安装公共签名密钥 rpm --import https://artifacts.elastic.co/GPG-KEY-elasticsearch 2.创建镜像源文件:/etc/yum.rep ...

  9. AtCoder Regular Contest 080 C - 4-adjacent

    地址:http://arc080.contest.atcoder.jp/tasks/arc080_a 题目: C - 4-adjacent Time limit : 2sec / Memory lim ...

  10. 51nod 1391 01串(hash+DP)

    题目链接题意:给定一个01串S,求出它的一个尽可能长的子串S[i..j],满足存在一个位置i<=x <=j, S[i..x]中0比1多,而S[x + 1..j]中1比0多.求满足条件的最长 ...