异步http框架简介&实现原理
1.Activity
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void click(View view) {
String path = "http://110.65.99.66:8080/androidserver/WebServlet?userName="
+ "伟杰" + "&password=" + "1";
SimpleAsyncHttp simpleAsyncHttp = new SimpleAsyncHttp();
simpleAsyncHttp.get(path, new MyHandler() {
@Override
public void doSuccess(String content) {
Toast.makeText(MainActivity.this, content, 0).show();
}
@Override
public void doFailure(String content) {
Toast.makeText(MainActivity.this, content, 0).show();
}
});
}
}
2.自定义一个Handler类
public class MyHandler extends Handler {
public void doSuccess(String content) {
}
public void doFailure(String content) {
}
@Override
public void handleMessage(Message msg) {
String content = (String) msg.obj;
switch (msg.what) {
case 1:
doSuccess(content);
break;
case 2:
doFailure(content);
break;
}
}
}
3.异步http业务类
public class SimpleAsyncHttp {
public void get(final String path, final MyHandler myHandler) {
new Thread() {
public void run() {
try {
HttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(path);
HttpResponse response = client.execute(httpGet);
int code = response.getStatusLine().getStatusCode();
if (code == 200) {
InputStream is = response.getEntity().getContent();
String result = StreamTool.readInputStream(is);
Message msg = new Message();
msg.what = 1;
msg.obj = result;
myHandler.sendMessage(msg);
} else {
Message msg = new Message();
msg.what = 2;
msg.obj = "请求失败,错误代码:" + code;
myHandler.sendMessage(msg);
}
} catch (Exception e) {
e.printStackTrace();
Message msg = new Message();
msg.what = 2;
msg.obj = "请求失败";
myHandler.sendMessage(msg);
}
};
}.start();
}
}
4.授权
<uses-permission android:name="android.permission.INTERNET"/>
异步http框架提交数据到服务器
1.布局文件
<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="match_parent"
android:layout_height="wrap_content"
android:hint="请输入用户名" />
<EditText
android:id="@+id/et_password"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="请输入密码"
android:inputType="textPassword" />
<Button
android:onClick="get"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="get请求登录" />
<Button
android:onClick="post"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="post请求登录" />
</LinearLayout>
2.Activity
public class MainActivity extends Activity {
private EditText et_userName;
private EditText et_password;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
this.et_userName = (EditText) this.findViewById(R.id.et_username);
this.et_password = (EditText) this.findViewById(R.id.et_password);
}
public void get(View view) {
final String userName = this.et_userName.getText().toString().trim();
final String password = this.et_password.getText().toString().trim();
AsyncHttpClient client = new AsyncHttpClient();
String url = "http://110.65.99.66:8080/androidserver/WebServlet";
RequestParams params = new RequestParams();
params.put("userName", userName);
params.put("password", password);
client.get(url, params, new AsyncHttpResponseHandler() {
@Override
public void onSuccess(int statusCode, Header[] headers,
byte[] responseBody) {
Toast.makeText(MainActivity.this, statusCode + "", 0).show();
Toast.makeText(MainActivity.this, new String(responseBody), 0)
.show();
}
@Override
public void onFailure(int statusCode, Header[] headers,
byte[] responseBody, Throwable error) {
Toast.makeText(MainActivity.this, statusCode + "", 0).show();
Toast.makeText(MainActivity.this, new String(responseBody), 0)
.show();
}
});
}
public void post(View view) {
final String userName = this.et_userName.getText().toString().trim();
final String password = this.et_password.getText().toString().trim();
AsyncHttpClient client = new AsyncHttpClient();
String url = "http://110.65.99.66:8080/androidserver/WebServlet";
RequestParams params = new RequestParams();
params.put("userName", userName);
params.put("password", password);
client.post(url, params, new AsyncHttpResponseHandler() {
@Override
public void onSuccess(int statusCode, Header[] headers,
byte[] responseBody) {
Toast.makeText(MainActivity.this, statusCode + "", 0).show();
Toast.makeText(MainActivity.this, new String(responseBody), 0)
.show();
}
@Override
public void onFailure(int statusCode, Header[] headers,
byte[] responseBody, Throwable error) {
Toast.makeText(MainActivity.this, statusCode + "", 0).show();
Toast.makeText(MainActivity.this, new String(responseBody), 0)
.show();
}
});
}
}
3.授权
<uses-permission android:name="android.permission.INTERNET"/>
开源异步http框架下载地址:
上传文件到服务器
需要的jar包:
1.服务器代码
public class UploadFileServlet extends HttpServlet {
private static final long serialVersionUID = -8553764460183221555L;
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
try {
// 1. 判断表单是否是混合表单
boolean = ServletFileUpload.isMultipartContent(request);
// 2. 判断
if () {
// 3. 建立目录
String path = this.getServletContext().getRealPath("files");
System.out.println("path = " + path);
File dir = new File(path);
if (!dir.exists()) {
dir.mkdirs();
}
// 4. 创建ServletFileUpload对象
FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
// 5. 解析请求,将每一个表单项进行封装FileItem
List<FileItem> list = upload.parseRequest(request);
// 6. 循环遍历
for (FileItem item : list) {
// 7. 判断
if (item.isFormField()) {
// 普通字段
String name = item.getFieldName();
String value = item.getString("utf-8");
System.out.println(name + "=" + value);
} else {
// 文件字段
System.out.println("-----------------------");
String fileName = item.getName();
item.write(new File(dir, System.currentTimeMillis()
+ "_" + fileName));
}
}
} else {
System.out.println("普通表单数据处理...");
}
} catch (Exception e) {
e.printStackTrace();
}
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
this.doGet(request, response);
}
}
2.安卓端代码
1.布局文件
<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_path"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="mnt/sdcard/DCIM/Camera/IMG_20130901_185732.jpg"
android:ems="10" >
<requestFocus />
</EditText>
<Button
android:onClick="uploadByHttpClient"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="通过第三方HttpClient上传" />
<Button
android:onClick="uploadByAsyncHttpClient"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="通过asyncHttpClient上传" />
</LinearLayout>
2.Activity
public class MainActivity extends Activity {
private EditText et_path;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
this.et_path = (EditText) this.findViewById(R.id.et_path);
}
public void uploadByHttpClient(View view) {
String path = this.et_path.getText().toString().trim();
final String url = "http://110.65.99.66:8080/androidserver/UploadFileServlet";
final File file = new File(path);
// 先判断文件是否存在
if (file.exists() && file.length() > 0) {
// 网络访问为耗时操作,应该放在子线程中执行
new Thread() {
public void run() {
// 1. 创建第三方HttpClient对象
HttpClient client = new HttpClient();
// 2. 创建POST请求对象
PostMethod post = new PostMethod(url);
// 3. 设置请求体内容
try {
// 参数体
Part[] ps = { new FilePart("file", file) };
post.setRequestEntity(new MultipartRequestEntity(ps,
post.getParams()));
// 4. 获取连接器管理对象
HttpConnectionManager manager = client
.getHttpConnectionManager();
// 5. 设置参数提交的等待时间
manager.getParams().setConnectionTimeout(10000);
// 6. 执行PostMethod方法
client.executeMethod(post);
// 7. 程序执行到这里,说明成功
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(MainActivity.this, "上传成功", 0)
.show();
}
});
} catch (Exception e) {
e.printStackTrace();
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(MainActivity.this, "上传失败", 0)
.show();
}
});
}
};
}.start();
} else {
Toast.makeText(this, "文件不存在!", 0).show();
}
}
public void uploadByAsyncHttpClient(View view) {
String path = this.et_path.getText().toString().trim();
final String url = "http://110.65.99.66:8080/androidserver/UploadFileServlet";
final File file = new File(path);
// 先判断文件是否存在
if (file.exists() && file.length() > 0) {
// 1. 创建AsyncHttpClient对象
AsyncHttpClient client = new AsyncHttpClient();
// 2.设置参数体
RequestParams params = new RequestParams();
try {
// 其实这里的异常不可能出现,因为上边已经做了判断
params.put("profile_picture", file);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// 3.上传文件
client.post(url, params, new AsyncHttpResponseHandler() {
// 上传成功时回调的方法
@Override
public void onSuccess(int statusCode, Header[] headers,
byte[] responseBody) {
Toast.makeText(MainActivity.this, "上传成功!", 0).show();
}
// 上传失败时回调的方法
@Override
public void onFailure(int statusCode, Header[] headers,
byte[] responseBody, Throwable error) {
Toast.makeText(MainActivity.this, "上传失败!错误码:" + statusCode,
0).show();
}
});
} else {
Toast.makeText(this, "文件不存在!", 0).show();
}
}
}
3.授权
<uses-permission android:name="android.permission.INTERNET"/>