1. 准备条件,

  1. 编写一个web项目。编写一个servlet,若用户名为lisi,密码为123,则返回“登录成功”,否则”登录失败”。项目名为ServerItheima28。代码如下:

package com.itheima28.servlet;

import java.io.IOException;

import java.io.PrintWriter;

import javax.servlet.ServletException;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

public class LoginServlet extends HttpServlet {

/**

* The doGet method of the servlet. <br>

*

* This method is called when a form has its tag value method equals to get.

*

* @param request the request send by the client to the server

* @param response the response send by the server to the client

* @throws ServletException if an error occurred

* @throws IOException if an error occurred

*/

public void doGet(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

String username = request.getParameter("username");       // 采用的编码是: iso-8859-1

String password = request.getParameter("password");

// 采用iso8859-1的编码对姓名进行逆转, 转换成字节数组, 再使用utf-8编码对数据进行转换, 字符串

username = new String(username.getBytes("iso8859-1"), "utf-8");

password = new String(password.getBytes("iso8859-1"), "utf-8");

System.out.println("姓名: " + username);

System.out.println("密码: " + password);

if("lisi".equals(username) && "123".equals(password)) {

/*

* getBytes 默认情况下, 使用的iso8859-1的编码, 但如果发现码表中没有当前字符,

* 会使用当前系统下的默认编码: GBK

*/

response.getOutputStream().write("登录成功".getBytes("utf-8"));

} else {

response.getOutputStream().write("登录失败".getBytes("utf-8"));

}

}

/**

* The doPost method of the servlet. <br>

*

* This method is called when a form has its tag value method equals to post.

*

* @param request the request send by the client to the server

* @param response the response send by the server to the client

* @throws ServletException if an error occurred

* @throws IOException if an error occurred

*/

public void doPost(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

System.out.println("doPost");

doGet(request, response);

}

}

  1. 使用github上的android-async-http-master框架:

2 编写Android应用,应用截图如下:

代码结构如下:

清单文件

<?xml   编写布局文件activity_main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

xmlns:tools="http://schemas.android.com/tools"

android:layout_width="match_parent"

android:layout_height="match_parent"

android:orientation="vertical"

tools:context=".MainActivity" >

<EditText

android:id="@+id/et_username"

android:layout_width="fill_parent"

android:layout_height="wrap_content"

android:hint="请输入姓名" />

<EditText

android:id="@+id/et_password"

android:layout_width="fill_parent"

android:layout_height="wrap_content"

android:hint="请输入密码" />

<Button

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:onClick="doGet"

android:text="Get方式提交" />

<Button

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:onClick="doPost"

android:text="Post方式提交" />

<Button

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:onClick="doHttpClientOfGet"

android:text="使用HttpClient方式提交Get请求" />

<Button

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:onClick="doHttpClientOfPost"

android:text="使用HttpClient方式提交Post请求" />

</LinearLayout>

4 NetUtils的内容如下:

package com.itheim28.submitdata.utils;

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 android.util.Log;

public class NetUtils {

private static final String TAG = "NetUtils";

/**

* 使用post的方式登录

*

* @param userName

* @param password

* @return

*/

public static String loginOfPost(String userName, String password) {

HttpURLConnection conn = null;

try {

URL url = new URL(

"http://114.215.142.191:8080/ServerItheima28/servlet/LoginServlet");

conn = (HttpURLConnection) url.openConnection();

conn.setRequestMethod("POST");

conn.setConnectTimeout(10000); // 连接的超时时间

conn.setReadTimeout(5000); // 读数据的超时时间

conn.setDoOutput(true); // 必须设置此方法, 允许输出

// conn.setRequestProperty("Content-Length", 234); // 设置请求头消息,

// 可以设置多个

// post请求的参数

String data = "username=" + userName + "&password=" + password;

// 获得一个输出流, 用于向服务器写数据, 默认情况下, 系统不允许向服务器输出内容

OutputStream out = conn.getOutputStream();

out.write(data.getBytes());

out.flush();

out.close();

int responseCode = conn.getResponseCode();

if (responseCode == 200) {

InputStream is = conn.getInputStream();

String state = getStringFromInputStream(is);

return state;

} else {

Log.i(TAG, "访问失败: " + responseCode);

}

} catch (Exception e) {

e.printStackTrace();

} finally {

if (conn != null) {

conn.disconnect();

}

}

return null;

}

/**

* 使用get的方式登录

*

* @param userName

* @param password

* @return 登录的状态

*/

public static String loginOfGet(String userName, String password) {

HttpURLConnection conn = null;

try {

String data = "username=" + URLEncoder.encode(userName)

+ "&password=" + URLEncoder.encode(password);

URL url = new URL(

"http://114.215.142.191:8080/ServerItheima28/servlet/LoginServlet?"

+ data);

conn = (HttpURLConnection) url.openConnection();

conn.setRequestMethod("GET"); // get或者post必须得全大写

conn.setConnectTimeout(10000); // 连接的超时时间

conn.setReadTimeout(5000); // 读数据的超时时间

int responseCode = conn.getResponseCode();

if (responseCode == 200) {

InputStream is = conn.getInputStream();

String state = getStringFromInputStream(is);

return state;

} else {

Log.i(TAG, "访问失败: " + responseCode);

}

} catch (Exception e) {

e.printStackTrace();

} finally {

if (conn != null) {

conn.disconnect(); // 关闭连接

}

}

return null;

}

/**

* 根据流返回一个字符串信息

*

* @param is

* @return

* @throws IOException

*/

private static String getStringFromInputStream(InputStream is)

throws IOException {

ByteArrayOutputStream baos = new ByteArrayOutputStream();

byte[] buffer = new byte[1024];

int len = -1;

while ((len = is.read(buffer)) != -1) {

baos.write(buffer, 0, len);

}

is.close();

String html = baos.toString(); // 把流中的数据转换成字符串, 采用的编码是: utf-8

// String html = new String(baos.toByteArray(), "GBK");

baos.close();

return html;

}

}

5 NetUtils2代码如下:

package com.itheim28.submitdata.utils;

import java.io.ByteArrayOutputStream;

import java.io.IOException;

import java.io.InputStream;

import java.util.ArrayList;

import java.util.List;

import org.apache.http.HttpResponse;

import org.apache.http.NameValuePair;

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.impl.client.DefaultHttpClient;

import org.apache.http.message.BasicNameValuePair;

import android.util.Log;

public class NetUtils2 {

private static final String TAG = "NetUtils";

/**

* 使用post的方式登录

*

* @param userName

* @param password

* @return

*/

public static String loginOfPost(String userName, String password) {

HttpClient client = null;

try {

// 定义一个客户端

client = new DefaultHttpClient();

// 定义post方法

HttpPost post = new HttpPost(

"http://114.215.142.191:8080/ServerItheima28/servlet/LoginServlet");

// 定义post请求的参数

List<NameValuePair> parameters = new ArrayList<NameValuePair>();

parameters.add(new BasicNameValuePair("username", userName));

parameters.add(new BasicNameValuePair("password", password));

// 把post请求的参数包装了一层.

// 不写编码名称服务器收数据时乱码. 需要指定字符集为utf-8

UrlEncodedFormEntity entity = new UrlEncodedFormEntity(parameters,

"utf-8");

// 设置参数.

post.setEntity(entity);

// 设置请求头消息

// post.addHeader("Content-Length", "20");

// 使用客户端执行post方法

HttpResponse response = client.execute(post); // 开始执行post请求,

// 会返回给我们一个HttpResponse对象

// 使用响应对象, 获得状态码, 处理内容

int statusCode = response.getStatusLine().getStatusCode(); // 获得状态码

if (statusCode == 200) {

// 使用响应对象获得实体, 获得输入流

InputStream is = response.getEntity().getContent();

String text = getStringFromInputStream(is);

return text;

} else {

Log.i(TAG, "请求失败: " + statusCode);

}

} catch (Exception e) {

e.printStackTrace();

} finally {

if (client != null) {

client.getConnectionManager().shutdown(); // 关闭连接和释放资源

}

}

return null;

}

/**

* 使用get的方式登录

*

* @param userName

* @param password

* @return 登录的状态

*/

public static String loginOfGet(String userName, String password) {

HttpClient client = null;

try {

// 定义一个客户端

client = new DefaultHttpClient();

// 定义一个get请求方法

String data = "username=" + userName + "&password=" + password;

HttpGet get = new HttpGet(

"http://114.215.142.191:8080/ServerItheima28/servlet/LoginServlet?" + data);

// response 服务器相应对象, 其中包含了状态信息和服务器返回的数据

// 开始执行get方法, 请求网络

HttpResponse response = client.execute(get);

// 获得响应码

int statusCode = response.getStatusLine().getStatusCode();

if (statusCode == 200) {

InputStream is = response.getEntity().getContent();

String text = getStringFromInputStream(is);

return text;

} else {

Log.i(TAG, "请求失败: " + statusCode);

}

} catch (Exception e) {

e.printStackTrace();

} finally {

if (client != null) {

client.getConnectionManager().shutdown(); // 关闭连接, 和释放资源

}

}

return null;

}

/**

* 根据流返回一个字符串信息

*

* @param is

* @return

* @throws IOException

*/

private static String getStringFromInputStream(InputStream is)

throws IOException {

ByteArrayOutputStream baos = new ByteArrayOutputStream();

byte[] buffer = new byte[1024];

int len = -1;

while ((len = is.read(buffer)) != -1) {

baos.write(buffer, 0, len);

}

is.close();

String html = baos.toString(); // 把流中的数据转换成字符串, 采用的编码是: utf-8

// String html = new String(baos.toByteArray(), "GBK");

baos.close();

return html;

}

}

6 MainActivity代码如下:

package com.itheim28.submitdata;

import android.app.Activity;

import android.os.Bundle;

import android.text.TextUtils;

import android.util.Log;

import android.view.View;

import android.widget.EditText;

import android.widget.Toast;

import com.itheim28.submitdata.utils.NetUtils;

import com.itheim28.submitdata.utils.NetUtils2;

public class MainActivity extends Activity {

private static final String TAG = "MainActivity";

private EditText etUserName;

private EditText etPassword;

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

etUserName = (EditText) findViewById(R.id.et_username);

etPassword = (EditText) findViewById(R.id.et_password);

}

/**

* 使用httpClient方式提交get请求

*

* @param v

*/

public void doHttpClientOfGet(View v) {

Log.i(TAG, "doHttpClientOfGet");

final String userName = etUserName.getText().toString();

final String password = etPassword.getText().toString();

new Thread(new Runnable() {

@Override

public void run() {

// 请求网络

final String state = NetUtils2.loginOfGet(userName, password);

// 执行任务在主线程中

runOnUiThread(new Runnable() {

@Override

public void run() {

// 就是在主线程中操作

Toast.makeText(MainActivity.this, state, 0).show();

}

});

}

}).start();

}

/**

* 使用httpClient方式提交post请求

*

* @param v

*/

public void doHttpClientOfPost(View v) {

Log.i(TAG, "doHttpClientOfPost");

final String userName = etUserName.getText().toString();

final String password = etPassword.getText().toString();

new Thread(new Runnable() {

@Override

public void run() {

final String state = NetUtils2.loginOfPost(userName, password);

// 执行任务在主线程中

runOnUiThread(new Runnable() {

@Override

public void run() {

// 就是在主线程中操作

Toast.makeText(MainActivity.this, state, 0).show();

}

});

}

}).start();

}

public void doGet(View v) {

final String userName = etUserName.getText().toString();

final String password = etPassword.getText().toString();

new Thread(new Runnable() {

@Override

public void run() {

// 使用get方式抓去数据

final String state = NetUtils.loginOfGet(userName, password);

// 执行任务在主线程中

runOnUiThread(new Runnable() {

@Override

public void run() {

// 就是在主线程中操作

Toast.makeText(MainActivity.this, state, 0).show();

}

});

}

}).start();

}

public void doPost(View v) {

final String userName = etUserName.getText().toString();

final String password = etPassword.getText().toString();

new Thread(new Runnable() {

@Override

public void run() {

final String state = NetUtils.loginOfPost(userName, password);

// 执行任务在主线程中

runOnUiThread(new Runnable() {

@Override

public void run() {

// 就是在主线程中操作

Toast.makeText(MainActivity.this, state, 0).show();

}

});

}

}).start();

}

}

7 MainActivity2 的代码如下:

package com.itheim28.submitdata;

import java.net.URLEncoder;

import org.apache.http.Header;

import android.app.Activity;

import android.os.Bundle;

import android.view.View;

import android.widget.EditText;

import android.widget.Toast;

import com.loopj.android.http.AsyncHttpClient;

import com.loopj.android.http.AsyncHttpResponseHandler;

import com.loopj.android.http.RequestParams;

public class MainActivity2 extends Activity {

protected static final String TAG = "MainActivity2";

private EditText etUserName;

private EditText etPassword;

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

etUserName = (EditText) findViewById(R.id.et_username);

etPassword = (EditText) findViewById(R.id.et_password);

}

public void doGet(View v) {

final String userName = etUserName.getText().toString();

final String password = etPassword.getText().toString();

AsyncHttpClient client = new AsyncHttpClient();

String data = "username=" + URLEncoder.encode(userName) + "&password="

+ URLEncoder.encode(password);

client.get("http://114.215.142.191:8080/ServerItheima28/servlet/LoginServlet?"

+ data, new MyResponseHandler());

}

public void doPost(View v) {

final String userName = etUserName.getText().toString();

final String password = etPassword.getText().toString();

AsyncHttpClient client = new AsyncHttpClient();

RequestParams params = new RequestParams();

params.put("username", userName);

params.put("password", password);

client.post(

"http://114.215.142.191:8080/ServerItheima28/servlet/LoginServlet",

params, new MyResponseHandler());

}

class MyResponseHandler extends AsyncHttpResponseHandler {

@Override

public void onSuccess(int statusCode, Header[] headers,

byte[] responseBody) {

// Log.i(TAG, "statusCode: " + statusCode);

Toast.makeText(

MainActivity2.this,

"成功: statusCode: " + statusCode + ", body: "

+ new String(responseBody), 0).show();

}

@Override

public void onFailure(int statusCode, Header[] headers,

byte[] responseBody, Throwable error) {

Toast.makeText(MainActivity2.this, "失败: statusCode: " + statusCode,

0).show();

}

}

}

12_Android中HttpClient的应用,doGet,doPost,doHttpClientGet,doHttpClient请求,另外借助第三方框架实现网络连接的应用,的更多相关文章

  1. C#中HttpClient使用注意:预热与长连接

    最近在测试一个第三方API,准备集成在我们的网站应用中.API的调用使用的是.NET中的HttpClient,由于这个API会在关键业务中用到,对调用API的整体响应速度有严格要求,所以对HttpCl ...

  2. [转]C#中HttpClient使用注意:预热与长连接

    最近在测试一个第三方API,准备集成在我们的网站应用中.API的调用使用的是.NET中的HttpClient,由于这个API会在关键业务中用到,对调用API的整体响应速度有严格要求,所以对HttpCl ...

  3. VMware Workstation中网络连接之桥接、NAT和Host-only

    在Windows XP系统中,安装好VMware Workstation虚拟机软件以后,我们可以查看一下"网络连接"窗口: 在窗口中多出了两块网卡: VMware Network ...

  4. C# 网络连接中异常断线的处理:ReceiveTimeout, SendTimeout 及 KeepAliveValues(设置心跳)

    C# 网络连接中异常断线的处理:ReceiveTimeout, SendTimeout 及 KeepAliveValues(设置心跳) 在使用 TcpClient 网络连接中常常会发生客户端连接异常断 ...

  5. [转]servlet中的service, doGet, doPost方法的区别和联系

    原文地址:http://m.blog.csdn.net/blog/ghyg525/22928567 大家都知道在javax.servlet.Servlet接口中只有init, service, des ...

  6. servlet 中 service ,doGet , doPost 关系

    web.xml <?xml version="1.0" encoding="UTF-8"?> <web-app version="2 ...

  7. Servlet -doGet() doPost()原理

    一.自定义类只需要重写doGet(HttpServletRequest request, HttpServletResponse response) 和doPost(HttpServletReques ...

  8. .net4.5中HttpClient使用注意点

    .net4.5中的HttpClinet是个非常强大的类,但是在最近实际项目运用中发现了些很有意思的事情. 起初我是这样用的: using (var client = new HttpClient()) ...

  9. Java中httpClient中三种超时设置

    本文章给大家介绍一下关于Java中httpClient中的三种超时设置小结 在Apache的HttpClient包中,有三个设置超时的地方: /* 从连接池中取连接的超时时间*/ ConnManage ...

随机推荐

  1. CMS垃圾收集器

    介绍 CMS垃圾回收器的全称是Concurrent Mark-Sweep Collector,从名字上可以看出两点,一个是使用的是并发收集,第二个是使用的收集算法是Mark-Sweep.从而也可以推测 ...

  2. android M Launcher之LauncherModel (三)

    通过前两篇的分析,我们已经知道了LauncherModel的初始化及工作流程,如果您还不熟悉的话请看前两篇博文 android M Launcher之LauncherModel (一) android ...

  3. Objective-C's Init Method

    初始化器在其他面向对象的语言中(比如Java)指的是构造器. Objective-C同样拥有对象构造器在init形式的方法中.不管如何,在Objc中这些方法没有什么特殊的行为. 按照惯例,程序猿在in ...

  4. GitHub无法访问或访问缓慢解决办法

    缘由 由于众所周知的原因,Github最近无法访问或访问很慢.由于Github支持https,因此此次屏蔽Github采用的方法是dns污染,用户访问github会返回一个错误的IPFQ当然是一种解决 ...

  5. Java提升篇之反射的原理(二)

    Java提升篇之通过反射越过泛型检查 /* *问题:在一个ArrayList<Integer>对象中,在这个集合中添加一个字符串. */ 在我们还没有学反射前,遇到这个问题都是无法实现的, ...

  6. MySQL 存储过程探秘

    关于存储过程的优点,本文不再阐述.这里只是对创建存储过程时可能遇到的问题做一下简单的分析. 必备基础 这里说的基础,是相关于如何创建一个存储过程的. DELIMITER:分隔符,定界符. 作用就是:作 ...

  7. 安卓自定义日期控件(仿QQ,IOS7)

    还记得上篇:高大上的安卓日期时间选择器,本篇是根据上篇修改而来,先看下qq中日期选择的效果: 鉴于目前还没有相似的开源日期控件,因此本人花费了一些时间修改了下之前的日期控件,效果如图: 虽说相似度不是 ...

  8. Dynamics CRM 安装Microsoft Dynamics CRM Reporting Extensions

    在装完CRM Server 后这个组件是必须安装的,但今天由于我的大意在客户安装生产环境时,告诉客户这个组件装在APP服务器上,导致客户安装时 SSRSInstance怎么都是空的,害的人家找了半天原 ...

  9. shell入门之流程控制语句

    1.case 脚本: #!/bin/bash #a test about case case $1 in "lenve") echo "input lenve" ...

  10. 【Unity Shaders】游戏性和画面特效——创建一个老电影式的画面特效

    本系列主要参考<Unity Shaders and Effects Cookbook>一书(感谢原书作者),同时会加上一点个人理解或拓展. 这里是本书所有的插图.这里是本书所需的代码和资源 ...