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. Count the string---hdu3336(kmp Next数组的运用)

    题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=3336 题意就是求串s的前缀的个数和: 例如:abab 前缀 个数 a     2 ab    2 ab ...

  2. CentOS7安装MySQL 5.7

    1.源码包下载 wget https://dev.mysql.com/get/Downloads/MySQL-5.7/mysql-boost-5.7.20.tar.gz 2.编译安装 安装依赖包: y ...

  3. 十個必用的 Vim Plugin

    ◎ The NERD Tree 操作 Vim 時,通常都在 Terminal 底下作用,無法像一般的 GUI    應用程式可以以樹狀目錄來瀏覽檔案. The NERD Tree    是一將檔案目錄 ...

  4. WebRtc(网页即时通讯技术)知识点总结

    前言 WebRTC,名称源自网页实时通信(Web Real-Time Communication)的缩写,简而言之它是一个支持网页浏览器进行实时语音对话或视频对话的技术.并且还支持跨平台:window ...

  5. 技术架构标杆(Certicom Security Architecture)对比思考——By Me at 20140408

    看到一家国外网络安全企业Certicom,官网链接:http://www.certicom.com/,可以作为很好的企业安全技术建构以及产品规划的标杆,下面我绘制了该公司的产品组合以及技术架构框图:

  6. 004-hadoop家族概述

    hadoop家族 名称 简介   Hadoop 分布式基础架构 Hadoop的框架最核心的设计就是:HDFS和MapReduce.HDFS为海量的数据提供了存储,则MapReduce为海量的数据提供了 ...

  7. macOS Sierra上ssh免密码登录linux服务器

    1.生成私钥文件 在客户端终端下输入以下命令 ssh-keygen -t rsa 每次执行 ssh-keygen -t rsa 产生的私钥文件都会不同 如果文件"~/.ssh/id_rsa& ...

  8. matplotlib 的 subplot, axes and axis

    fig = plt.figure('多图', (10, 10), dpi=80) #第一个指定窗口名称,第二个指定图片大小,创建一个figure对象 plt.subplot(222) #2*2的第二个 ...

  9. python数据描述符

    Python的描述符是接触到Python核心编程中一个比较难以理解的内容,自己在学习的过程中也遇到过很多的疑惑,通过google和阅读源码,现将自己的理解和心得记录下来,也为正在为了该问题苦恼的朋友提 ...

  10. docker swarm overlay stack 服务部署记录

    项目xxx(后端),xxx-ui前端(前后端分离的项目) 依赖mysql,elasticsearch.分别制作了四个镜像来做这件事.希望可以制作跨主机的部署,使用了swarm,以下是学习记录. 参考 ...