AsyncHttpClient框架对数据提交的案例

AsyncHttpClient实际上是对HttpClient框架的进一步封装,可在www.github.com下载压缩好的框架文件。

下载下来之后,可将src里面的java源文件直接放入我们的项目或者在releases目录下使用最新的jar包

 

public void click(View view){

    //用户名密码提交到服务器

    AsyncHttpClient client = new AsyncHttpClient();

     String path = "http://192.168.1.110:8080/web/LoginServlet?username="

                        + URLEncoder.encode("飞牛")

                        + "&password="

                        + URLEncoder.encode("321");

    client.get(path, new AsyncHttpResponseHandler(){

                public void onSuccess(String content){

                    super.onSuccess(content);

                    Toast.makeText(MainActivity.this, "请求成功" + content, 0).show();

                }

                public void onFailure(Throwable error, String content){

                    super.onFailure(error, content);

                    Toast.makeText(MainActivity.this, "请求失败" + content, 0).show();

                }

        });

}

 

实现的原理:

自定义一个类AsyncHttpClient:

public class AsyncHttpClient{

    public void get(final String path, final MyHandler myHandler){

        new Thread(){

            public void run(){

                HttpClient client = new DefaultHttpClient();

                HttpGet httpGet = new HttpGet(path);

                try{

                    HttpResponse response = client.execute(httpGet);

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

                    String content = StreamTools.readInputStream(is);

                    //执行成功

                    Message msg = new Message();

                    msg.what = 1;

                    msg.obj = content;

                    myHandler.sendMessage(msg);

                }catch(Exception e){

                    //执行失败

                    e.printStackTrace();

                    Message msg = new Message();

                    msg.what = 2;

                    msg.obj = "请求失败";

                    myHandler.sendMessage(msg);

                }

            };

        }.start();

    }

}

 

自定义一个MyHandler类:

public class MyHandler extends Handler{

   

    public void onFailure(String content){

 

    }

 

    public void onSuccess(String content){

 

    }

 

    public void handleMessage(Message msg){

        String content = (String) msg.obj;

        switch(msg.what){

        case 1:

            onSuccess(content);

            break;

        case 2:

            onFailure(content);

            break;

        }

        super.handleMessage(msg);

    }

}

 

 

点击事件中:

public void click(View view){

    //1. 开启子线程 执行一个http请求在后台执行 在子线程中执行

    //2. 子线程执行完毕后通知UI界面更新

 

    AsyncHttpClient client = new AsyncHttpClient();

    String path = "http://192.168.1.110:8080/web/LoginServlet?username="

                        + URLEncoder.encode("飞牛")

                        + "&password="

                        + URLEncoder.encode("321");

    client.get(path, new MyHandler(){

            public void onFailure(String content){

                Toast.makeText(MainActivity.this, content, 1).show();

                super.onFailure(content);

            }

            public void onSuccess(String content){

                Toast.makeText(MainActivity.this, content, 1).show();

                super.onSuccess(content);

            }

        });

 

}

 

框架的POST请求方式:

public void click(View view){

    final String username = et_username.getText().toString().trim();

    final String password = et_password.getText().toString().trim();

    AsyncHttpClient client = new AsyncHttpClient();

    String url = "http://192.168.1.110/web/LoginServlet";

    RequestParams params = new RequestParams();

    params.put("username", username);

    params.put("password", password);

    client.post(url, params, new AsyncHttpResponseHandler(){

            public void onSuccess(String content){

                super.onSuccess(content);

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

            }

        });

}

 

 

 

上传文件到服务器:

服务端导入commons-fileupload.jar与commons-io.jar两个包:

protected void doPost(HttpServletRequest request,

            HttpServletResponse response) throws ServletException,

            IOException {

                boolean isMultipart =ServletFileUpload.isMultipartContent(request);

                if(isMultipart){

                    String realpath = request.getSession().getServletContext().getRealPath("/files");

                    System.out.println(realpath);

                    File dir = new File(realpath);

                    if(!dir.exists()){

                        dir.mkdirs();

                    }

                    FileItemFactory factory =new DiskFileItemFactory();

                    ServletFileUpload upload = new ServletFileUpload(factory);

                    upload.setHeaderEncoding("UTF-8");

                    try{

                        List<FileItem> items = upload.parseRequest(request);

                        for(FileItem item : items){

                            if(item.isFormField()){

                                String name1 = item.getFieldName();//得到请求参数的名称

                                String value = item.getString("UTF-8");//得到参数值

                                System.out.println(name1+"="+value);

                            }else{

                                item.write(new File(dir, System.currentTimeMillis()

                                            + item.getName().substring(

                                                        item.getName().lastIndexOf("."))));

                            }

                        }

                    }catch(Exception e){

                        e.printStackTrace();

                    }

                }else{

                    doGet(request, response);

                }

 

            }

 

 

Jsp文件:

 

    <form actin="UploadFileServlet" method="post" enctype="multipart/form-data">

        文件:<input name="filename" type="file"><br>

        <input name="submit" type="submit" value="上传">

    </form>

 

客户端

xml文件:

<EditText

    android:id="@+id/et_path"

    android:layout_width="fill_parent"

    android:layout_height="wrap_content"

    android:hint="请输入文件的路径"/>

 

<Button

    android:layout_width="fill_parent"

    android:layout_height="wrap_content"

    android:onClick="click"

    android:text="上传"/>

 

 

MainActivity文件:

public void click(View view){

    String path = et_path.getText().toString().trim();

    File file = new File(path);

    if(file.exists() && file.length > 0){

        AsyncHttpClient client = new AsyncHttpClient();

        RequestParams params = new RequestParams();

        try{   

            params.put("profile_picture", file);

        }catch(FileNotFoundException e){

            e.printStackTrace();

        }

        client.post("http://192.168.1.110:8080/web/UploadFileServlet",

                    params, new AsyncHttpResponseHandler(){

                       

                        public void onSuccess(String content){

                            Toast.makeText(MainActivity.this, "上传成功", 1).show();

                            super.onSuccess(content);

                        }

 

                        public void onFailure(Throwable error, String content){

                            Toast.makeText(MainActivity.this, "上传失败", 1).show();

                            super.onFailure(error, content);

                        }

            });

        }else{

        }

}

posted @ 2015-10-25 17:05  飞牛冲天  阅读(430)  评论(0编辑  收藏  举报