android开发--android-async-http
2016-04-04 21:10
519 查看
做了个demo,主要用android-async-http第三方库中AsyncHttpClient来实现对服务器上传(1)简单键值对数据,(2)json数据以及(3)文件资源.
一.android客户端
tip:需要往libs中导入android-async-http的jar包
下载 android-async-http jar 包
1.UI布局文件main_activity.xml:
UI效果如下:
(1)et_name,et_pw用来提交键值对数据,tv1显示btn_upload_1提交后获取服务器返回的数据信息
(2)et_sex,et_age用来输入数据(这些数据会封装成jsonobject),tv2显示btn_upload_2提交后获取服务器返回的数据信息
(3)btn_upload_3文件上传按钮
2.MainActivity.java代码:
最后记得给予网络访问权限,在manifest.xml中,
二.servlet服务端编程:
用了3个servlet对应3中提交处理:
处理键值对参数:AsyncHttpClient.java(servlet):
处理提交的json数据:AsyncJson.java(servlet):
需要导入json包到servlet的项目中
下载 json jar 包
处理文件上传:AsyncFile.java(servlet):
这里用到了第三方jar,需要导入commons-fileupload和commons-io的jar包
下载 commons-fileupload jar 包
下载commons-io jar包
tip:请配置好web.xml:
关于android客户端访问地址:用原生模拟器:10.0.2.2;genymotion模拟器为10.0.3.2
一.android客户端
tip:需要往libs中导入android-async-http的jar包
下载 android-async-http jar 包
1.UI布局文件main_activity.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="com.min.myandroid_async_http.MainActivity" > <TextView android:id="@+id/tv1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_horizontal" android:text="上传登录信息" android:textSize="16sp" > <requestFocus /> </TextView> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal" > <EditText android:id="@+id/et_name" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:ems="12" android:hint="登录名" > </EditText> <EditText android:id="@+id/et_pw" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:ems="12" android:hint="登录密码" /> </LinearLayout> <Button android:id="@+id/btn_upload_1" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="提交" /> <TextView android:id="@+id/tv2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_horizontal" android:layout_marginTop="20dp" android:text="上传Json" android:textSize="16sp" > </TextView> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal" > <EditText android:id="@+id/et_sex" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:ems="12" android:hint="性别" > </EditText> <EditText android:id="@+id/et_age" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:ems="12" android:hint="年龄" /> </LinearLayout> <Button android:id="@+id/btn_upload_2" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="确定" /> <Button android:id="@+id/btn_upload_3" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="上传文件" /> </LinearLayout>
UI效果如下:
(1)et_name,et_pw用来提交键值对数据,tv1显示btn_upload_1提交后获取服务器返回的数据信息
(2)et_sex,et_age用来输入数据(这些数据会封装成jsonobject),tv2显示btn_upload_2提交后获取服务器返回的数据信息
(3)btn_upload_3文件上传按钮
2.MainActivity.java代码:
package com.min.myandroid_async_http; import java.io.File; import java.io.FileNotFoundException; import org.apache.http.Header; import org.apache.http.protocol.HTTP; import org.json.JSONException; import org.json.JSONObject; import android.app.Activity; import android.os.Bundle; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; import com.loopj.android.http.AsyncHttpClient; import com.loopj.android.http.JsonHttpResponseHandler; import com.loopj.android.http.RequestParams; import com.loopj.android.http.TextHttpResponseHandler; public class MainActivity extends Activity { private Button btn_upload_1; private Button btn_upload_2; private Button btn_upload_3; private EditText et_name; private EditText et_pw; private EditText et_sex; private EditText et_age; private TextView tv1; private TextView tv2; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // 初始化控件 init(); // 提交登录事件监听 btn_upload_1.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { uploadData(); et_name.setText(""); et_pw.setText(""); // Toast.makeText(getApplicationContext(), "你click1", // Toast.LENGTH_SHORT).show(); } }); // 提交json数据监听 btn_upload_2.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { uploadJson(); // Toast.makeText(getApplicationContext(), "你click2", // Toast.LENGTH_SHORT).show(); } }); //上传文件监听 btn_upload_3.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { uploadFile(); // Toast.makeText(getApplicationContext(), "你click3", // Toast.LENGTH_SHORT).show(); } }); } private void init() { tv1 = (TextView) findViewById(R.id.tv1); btn_upload_1 = (Button) findViewById(R.id.btn_upload_1); btn_upload_2 = (Button) findViewById(R.id.btn_upload_2); btn_upload_3 = (Button) findViewById(R.id.btn_upload_3); et_age = (EditText) findViewById(R.id.et_age); et_name = (EditText) findViewById(R.id.et_name); et_pw = (EditText) findViewById(R.id.et_pw); et_sex = (EditText) findViewById(R.id.et_sex); tv2 = (TextView) findViewById(R.id.tv2); } public void uploadData() { // 传递的参数设置 RequestParams requestParams = new RequestParams(); // 设置编码 requestParams.setContentEncoding(HTTP.UTF_8); requestParams.put("name", et_name.getText().toString()); requestParams.put("password", et_pw.getText().toString()); // 获取AsyncHttpClient对象 AsyncHttpClient client = new AsyncHttpClient(); String urladdress = "http://10.0.3.2:8080/MyServer/async"; client.post(urladdress, requestParams, new TextHttpResponseHandler( "UTF-8") { @Override // 当得到正确响应,以字符串形式返回 public void onSuccess(int arg0, Header[] arg1, String result) { tv1.setText(result); Log.i("result", result); } @Override // 当访问出错响应 public void onFailure(int arg0, Header[] arg1, String arg2, Throwable arg3) { } }); } protected void uploadJson() { String urladdress = "http://10.0.3.2:8080/MyServer/asyncjson"; RequestParams requestParams = new RequestParams(); JSONObject jObject = new JSONObject(); try { jObject.put("set", et_sex.getText().toString()); jObject.put("age", et_age.getText().toString()); requestParams.setContentEncoding(HTTP.UTF_8); requestParams.put("info", jObject); AsyncHttpClient client = new AsyncHttpClient(); client.post(urladdress, requestParams, new JsonHttpResponseHandler() { @Override public void onSuccess(int statusCode, Header[] headers, JSONObject response) { tv2.setText(response.toString()); } @Override public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) { super.onFailure(statusCode, headers, responseString, throwable); } }); } catch (JSONException e) { e.printStackTrace(); } } public void uploadFile() { String urladdress = "http://10.0.3.2:8080/MyServer/asyncfile"; RequestParams requestParams = new RequestParams(); requestParams.setContentEncoding(HTTP.UTF_8); File file = new File("/data/anr/traces.txt"); try { requestParams.put("myfile", file); AsyncHttpClient client = new AsyncHttpClient(); client.post(urladdress, requestParams, new TextHttpResponseHandler() { @Override public void onSuccess(int arg0, Header[] arg1, String result) { // TODO Auto-generated method stub System.out.println(result); Toast.makeText(getApplicationContext(), result, Toast.LENGTH_SHORT).show(); } @Override public void onFailure(int arg0, Header[] arg1, String arg2, Throwable arg3) { // TODO Auto-generated method stub System.out.println("上传失败"); } }); } catch (FileNotFoundException e) { e.printStackTrace(); } } }
最后记得给予网络访问权限,在manifest.xml中,
<uses-permission android:name="android.permission.INTERNET"/>
二.servlet服务端编程:
用了3个servlet对应3中提交处理:
处理键值对参数:AsyncHttpClient.java(servlet):
package com.min.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 AsyncHttpClient extends HttpServlet { private static final long serialVersionUID = 1L; public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { System.out .println("--------------------async_get----------------------"); request.setCharacterEncoding("UTF-8"); response.setCharacterEncoding("UTF-8"); PrintWriter out = response.getWriter(); out.println("<HTML>"); out.flush(); out.close(); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { System.out.println("-----------------async_post-------------"); request.setCharacterEncoding("UTF-8"); response.setCharacterEncoding("UTF-8"); String name = request.getParameter("name"); String pw = request.getParameter("password"); PrintWriter out = response.getWriter(); System.out.println("name="+name+"&&password="+pw); if (name.equals("jack") && pw.equals("12345")) { out.print("登录信息正确"); } else { out.print("登录信息有误"); } out.flush(); out.close(); } }
处理提交的json数据:AsyncJson.java(servlet):
需要导入json包到servlet的项目中
下载 json jar 包
package com.min.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; import org.json.JSONException; import org.json.JSONObject; public class AsyncJson extends HttpServlet { private static final long serialVersionUID = 1L; public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { System.out.println("------------------get_json--------------"); response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">"); out.println("<HTML>"); out.println(" <HEAD><TITLE>A Servlet</TITLE></HEAD>"); out.println(" <BODY>"); out.print(" This is "); out.print(this.getClass()); out.println(", using the GET method"); out.println(" </BODY>"); out.println("</HTML>"); out.flush(); out.close(); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { System.out.println("--------------post_json------------"); request.setCharacterEncoding("UTF-8"); response.setCharacterEncoding("UTF-8"); JSONObject jObject; try { jObject = new JSONObject(request.getParameter("info")); System.out.println(jObject.toString()); PrintWriter out = response.getWriter(); out.print(jObject); out.flush(); out.close(); } catch (JSONException e) { e.printStackTrace(); } } }
处理文件上传:AsyncFile.java(servlet):
这里用到了第三方jar,需要导入commons-fileupload和commons-io的jar包
下载 commons-fileupload jar 包
下载commons-io jar包
package com.min.servlet; import java.io.File; import java.io.IOException; import java.io.PrintWriter; import java.util.List; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.fileupload.FileItem; import org.apache.commons.fileupload.FileUploadException; import org.apache.commons.fileupload.disk.DiskFileItemFactory; import org.apache.commons.fileupload.servlet.ServletFileUpload; public class AsyncFile extends HttpServlet { private static final long serialVersionUID = 1L; public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { System.out.println("---------------get_file-------------"); response.setCharacterEncoding("UTF-8"); PrintWriter out = response.getWriter(); out.print("get请求"); out.flush(); out.close(); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { System.out.println("-------------post_file-----------"); response.setCharacterEncoding("UTF-8"); PrintWriter out = response.getWriter(); // 1、创建一个DiskFileItemFactory工厂 DiskFileItemFactory factory = new DiskFileItemFactory(); // 配置好缓存区 // factory.setSizeThreshold(1024*1024*2); // File folder=new File("c:\\EFI"); // if(!folder.exists()){ // folder.mkdir(); // } // factory.setRepository(folder); // 2、创建一个文件上传解析器 ServletFileUpload upload = new ServletFileUpload(factory); // 解决上传文件名的中文乱码 upload.setHeaderEncoding("UTF-8"); // 设置提交的最大文件类型数据的大小 upload.setSizeMax(1024 * 1024 * 20); // 设置提交的数据的大小 upload.setFileSizeMax(1024 * 1024 * 25); // 判断提交上来的数据是否是复杂类型数据的提交,如果是文件提交,则为复杂类型 if (!ServletFileUpload.isMultipartContent(request)) { // 按照传统方式获取数据 System.out.println("简单类型提交"); return; } else { // 处理文件提交 try { List<FileItem> lists = upload.parseRequest(request); if (lists != null) { for (FileItem item : lists) { //判断一个参数域是普通的表单输入域,还是文件上传域 if (item.isFormField()) { //上传的没有这类型的,不做处理 // if(item.getName().equals("json")){ // // } } else { // System.out.println(item.getName()); // System.out.println(item.getFieldName()); try { // 以文件形式存入到对应目录下 item.write(new File("D:\\" + item.getName())); out.write("文件上传成功"); out.flush(); out.close(); } catch (Exception e) { e.printStackTrace(); } } } } } catch (FileUploadException e) { e.printStackTrace(); } } } }
tip:请配置好web.xml:
<servlet-mapping> <servlet-name>AsyncHttpClient</servlet-name> <url-pattern>/async</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>AsyncJson</servlet-name> <url-pattern>/asyncjson</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>AsyncFile</servlet-name> <url-pattern>/asyncfile</url-pattern> </servlet-mapping>
关于android客户端访问地址:用原生模拟器:10.0.2.2;genymotion模拟器为10.0.3.2
相关文章推荐
- RTSP协议、RTMP协议、HTTP协议的区别
- mormort 土拨鼠,做后端服务那是杠杠的,基于http.sys
- 【iOS学习】十二、使用NSURLSession发送HTTP请求的问题
- stm单片机之STM32F4-Discovery资料汇总 (转载自http://blog.163.com/thinki_cao/blog/static/83944875201362493134992/)
- http 错误代码表
- Muduo网络库源码分析(二) 定时器TimeQueue,Timer,TimerId
- CodeForces - 659E New Reform (网络流)求最少的入度为0的点的个数
- TCP回射客户程序:str_cli函数
- HttpClient使用SESSIONID模拟用户发送请求
- 神经网络机器翻译Neural Machine Translation(2): Attention Mechanism
- 一个简易的http服务器。
- 一站式学习Wireshark(八):应用Wireshark过滤条件抓取特定数据流
- 一站式学习Wireshark(七):Statistics统计工具功能详解与应用
- IntelliJ IDEA 12 创建Web项目 教程 超详细版--http://www.cnblogs.com/cnjava/archive/2013/01/29/2881654.html
- 安装源码httpd-2.4.1错误解决办法
- RNN循环神经网络Recurrent Networks
- 循环神经网络教程4-用Python和Theano实现GRU/LSTM RNN, Part 4 – Implementing a GRU/LSTM RNN with Python and Theano
- 一站式学习Wireshark(四):网络性能排查之TCP重传与重复ACK
- 循环神经网络教程3-BP算法和梯度消失问题, Part 3 – Backpropagation Through Time and Vanishing Gradients
- 循环神经网络教程Recurrent Neural Networks Tutorial, Part 1 – Introduction to RNNs