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. Python中的编码与解码(转)

    Python中的字符编码与解码困扰了我很久了,一直没有认真整理过,这次下静下心来整理了一下我对方面知识的理解. 文章中对有些知识没有做深入的探讨,一是我自己也没有去深入的了解,例如各种编码方案的实现方 ...

  2. 转:docker的核心技术深度剖析

    一.docker是什么 Docker的英文本意是码头工人,也就是搬运工,这种搬运工搬运的是集装箱(Container),集装箱里面装的可不是商品货物,而是任意类型的App,Docker把App(叫Pa ...

  3. Jmeter(七)Mongodb的增删改查

    1.启动JMeter,新建线程组,设置线程组属性 2.右键添加-MongoDB Source Config 设置属性Server Address List:192.168.0.99 MongoDB S ...

  4. SpringBoot简介及第一个应用

    一.Spring时代变换 1. Spring1.x 时代 Spring初代都是通过xml文件配置bean,随着项目的不断扩大,繁琐的xml配置,混乱的依赖关系,难用的bean装配方式,由此衍生了spr ...

  5. jsonp解决跨域问题

    日常开发网页中,时常遇到跨域问题,通常解决办法:后端提供的接口支持jsonp格式,前端采用dataType:jsonp. 一:Jquery封装的AJAX,dataType:jsonp格式的方法: $. ...

  6. H5移动端的一些坑、、、

    H5项目常见问题及注意事项 Meta基础知识: H5页面窗口自动调整到设备宽度,并禁止用户缩放页面 //一.HTML页面结构 <meta name="viewport" co ...

  7. Guid ToString 格式知多少?

    在日常编程中,Guid是比较常用的,最常见的使用就是如下所示: string id = Guid.NewGuid().ToString(); 这条语句会生成一个新的Guid并转成字符串,如下: // ...

  8. Python(异常处理)

    一 错误和异常 程序中难免出现错误,而错误分成两种 1.语法错误(这种错误,根本过不了python解释器的语法检测,必须在程序执行前就改正) 2.逻辑错误(逻辑错误) 什么是异常 异常就是程序运行时发 ...

  9. Python(面向对象5——高级)

    面向对象进阶 一 isinstance(obj,cls)和issubclass(sub,super) isinstance(obj,cls)检查是否obj是否是类 cls 的对象 1 class Fo ...

  10. Multiple encodings set for module chunk explatform "GBK" will be used by compiler

    项目用idea启动的时候,突然报了个这个 Multiple encodings set for module explatform "GBK" will be used by co ...