1.Android操作UI的方法不是线程安全的,开发者自己生成的线程对象是不能直接操作UI的,比如在新线程里修改某个TextView,生成某个Toast。
异步AsyncHttpClient封装了httpclient,用起来比较方便
下面就例子来实践一下怎么用异步http框架 和 简单地仿写异步http框架
1.AndroidManifest.xml添加网络访问权限
<uses-permission android:name="android.permission.INTERNET"/>
2.在web项目中新建servlet,部署到服务器上
package cn.com.servlet;
import java.io.IOException;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class LoginServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
// 服务器接受统一编码iso-8859-1,然后获取字符串时转化为utf-8
String name = new String(request.getParameter("name").getBytes(
"iso-8859-1"), "utf-8");
String password = request.getParameter("password");
System.out.println("name:" + name);
System.out.println("password:" + password);
if (name.equals("张三") && password.equals("123")) {
// 往浏览器写字符串
response.getOutputStream().write(
"HttpClienget方式登录成功".getBytes("utf-8")); // 写到浏览器的编码是utf-8
} else {
response.getOutputStream().write(
"HttpClienget方式登录失败".getBytes("utf-8")); // 写到浏览器的编码是utf-8
}
}
@Override
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
// doGet(request, response);
// 服务器接受统一编码iso-8859-1,然后获取字符串时转化为utf-8
String name = new String(request.getParameter("name").getBytes(
"iso-8859-1"), "utf-8");
String password = request.getParameter("password");
System.out.println("name:" + name);
System.out.println("password:" + password);
if (name.equals("张三") && password.equals("123")) {
// 往浏览器写字符串
response.getOutputStream().write(
"HttpClienpost方式登录成功".getBytes("utf-8")); // 写到浏览器的编码是utf-8
} else {
response.getOutputStream().write(
"HttpClientpost方式登录失败".getBytes("utf-8")); // 写到浏览器的编码是utf-8
}
}
}
3.文件布局
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<EditText
android:id="@+id/name"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:hint="输入用户名"
android:text="张三"
/>
<EditText
android:id="@+id/password"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:hint="输入密码" />
<Button
android:id="@+id/button"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="异步提交get方式提交"
android:onClick="onClick1"
/>
<Button
android:id="@+id/button"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="异步提交post方式提交"
android:onClick="onClick2"
/>
</LinearLayout>
4.要想使用异步http框架,首先要下载已经封装好的源代码
下载地址:https://github.com/search?p=2&q=android&ref=cmdform&type=Repositories
下载这个开源代码。下载解压后,里面有例子可参考。把src目录下地包复制项目src中,这样就可以使用里面的做好的异步http框架了。
MainActivity.java
package com.example.get;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends Activity {
private EditText name,password;
private final int SUCCESS=1;
private Handler handler = new Handler(){
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
name = (EditText) findViewById(R.id.name);
password = (EditText) findViewById(R.id.password);
}
//get方法请求
public void onClick1(View view){
final String loginName = name.getText().toString();
final String loginPasswor = password.getText().toString();
//实例化异步http类
AsyncHttpClient client = new AsyncHttpClient();
String path = "http://10.162.0.171:8080/WebGet/LoginServlet?name="+URLEncoder.encode(loginName)+"&password="+URLEncoder.encode(loginPasswor);
//调用get方法,调用做好的AsyncHttpResponseHandler消息处理器,更新ui
client.get(path, new AsyncHttpResponseHandler(){
@Override
public void onSuccess(String content) {
Toast.makeText(MainActivity.this, content, 1).show();
}
@Override
public void onFailure(int statusCode, Throwable error, String content) {
// TODO Auto-generated method stub
super.onFailure(statusCode, error, content);
Toast.makeText(MainActivity.this,content, 1).show();
}
} );
}
//post方法请求
public void onClick2(View view){
final String loginName = name.getText().toString();
final String loginPassword = password.getText().toString();
AsyncHttpClient client = new AsyncHttpClient();
String postpath = "http://10.162.0.171:8080/WebGet/LoginServlet";
//设置参数
RequestParams params = new RequestParams();
params.put("name", loginName);
params.put("password", loginPassword);
client.post(postpath, params, new AsyncHttpResponseHandler(){
@Override
public void onSuccess(String content) {
// TODO Auto-generated method stub
super.onSuccess(content);
Toast.makeText(MainActivity.this, "发送请求:"+content, 1).show();
}
@Override
public void onFailure(Throwable error, String content) {
// TODO Auto-generated method stub
super.onFailure(error, content);
Toast.makeText(MainActivity.this, "发送请求:"+content, 1).show();
}
});
}
}
Post方法请求设置参数是,点进去可见到有丰富的各种参数类型
简单的几步就完成了,乱码问题都已经帮我们解决了。
运行结果
到底异步http框架是如何封装httpclient的呢?下面我们通过一个简单的仿写http框架例子来理解它(这里仿写只是get方式提交)
1.这里是访问上面部署好的web,也用上面的布局文件。(这里就不在重复写了)
(1)
MainActivity.java
package com.example.asnychttp;
import java.net.URLEncoder;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends Activity {
private EditText name, password;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
name = (EditText) findViewById(R.id.name);
password = (EditText) findViewById(R.id.password);
}
public void onClick(View view) {
String loginName = name.getText().toString();
String loginPwd = password.getText().toString();
// 1 开启子线程,执行一个http请求【在后台执行,在子线程执行】
// 2.子线程执行完毕后,通知ui,更新页面
// AsyncHttpClient类,我们自己写出来
AsyncHttpClient client = new AsyncHttpClient();
// 输入地址
String path = "http://10.162.0.171:8080/WebGet/LoginServlet?name="
+ URLEncoder.encode(loginName) + "&password="
+ URLEncoder.encode(loginPwd);
// 我们自定义一个MyHandler消息处理器来更改ui
client.get(path, new MyHandler() {
@Override
public void onSuccess(String content) {
// TODO Auto-generated method stub
super.onSuccess(content);
Toast.makeText(MainActivity.this, "发出请求:" + content, 2).show();
}
@Override
public void onFailure(String content) {
// TODO Auto-generated method stub
super.onFailure(content);
Toast.makeText(MainActivity.this, "发出请求:" + content, 2).show();
}
});
}
}
(2)
AsyncHttpClient.java
package com.example.asnychttp;
import java.io.IOException;
import java.io.InputStream;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import android.os.Message;
/**
* 异步http类
*
* @author lenovo
*
*/
public class AsyncHttpClient {
private final int SUCCESS = 1;
private final int ERROR = 2;
public void get(final String path, final MyHandler myHandler) {
new Thread() {
public void run() {
// 打开浏览器
HttpClient httpClient = new DefaultHttpClient();
// 输入地址
HttpGet httpGet = new HttpGet(path);
// 敲回车
try {
HttpResponse httpResponse = httpClient.execute(httpGet);
InputStream is = httpResponse.getEntity().getContent();
String content = StreamTools.readInputStream(is);
// 执行成功,发送消息
Message msg = new Message();
msg.what = SUCCESS;
msg.obj = content;
myHandler.sendMessage(msg);
} catch (IOException e) {
// 执行失败,发送消息
Message msg = new Message();
msg.what = ERROR;
msg.obj = "请求失败";
myHandler.sendMessage(msg);
e.printStackTrace();
}
}
}.start();
}
}
(3)消息处理器类
MyHandler.java
package com.example.asnychttp;
import android.os.Handler;
import android.os.Message;
/**
* 自定义主线程消息处理器
* @author lenovo
*
*/
public class MyHandler extends Handler{
//成功执行的方法
public void onSuccess(String content){
}
//失败执行的方法
public void onFailure(String content){
}
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
String content = (String) msg.obj;
switch(msg.what){
case 1:
onSuccess(content);
break;
case 2:
onFailure(content);
break;
}
}
}
(4)读流工具类
StreamTools.java
package com.example.asnychttp;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
public class StreamTools {
/**
* 读取流
* @param is
* @return
*/
public static String readInputStream(InputStream is) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len =0;
try {
if((len=is.read(buffer))!=-1){
baos.write(buffer, 0, len);
}
byte[] b = baos.toByteArray();
return new String(b);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
}
}
这就是一个简单的仿异步http框架