安卓基础总结 httpClient上传下载

1.httpClient

使用这个类代替httpURLConnector,减少参数的设置。

API

//获取一个HttpClient的默认实现类
HttpClient client = new DefaultHttpClient();

//建立一个httpGet对象 pathString为URL
HttpGet httpGet = new HttpGet(pathString);

//执行get方法,并获取返回信息
HttpResponse httpResponse = client.execute(httpGet);

例程

HttpClient使用get方法提交数据

public void click(View v)
{

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

    new Thread(){
        public void run() {
            //将数据直接写到url中
            String pathString = "http://192.168.1.101/web/LoginServlet?username="+username+"&password="+password;
            try {
                //获取一个HttpClient的默认实现类
                HttpClient client = new DefaultHttpClient();
                //建立一个httpGet对象
                HttpGet httpGet = new HttpGet(pathString);
                //执行get方法,并获取返回信息
                HttpResponse httpResponse = client.execute(httpGet);

                int code = httpResponse.getStatusLine().getStatusCode();
                if(code == 200)
                {
                    //从返回信息的entity中获取返回内容
                    InputStream in = httpResponse.getEntity().getContent();

                    String retStr = StreamUtils.ReadStream(in);

                    showToast(retStr);
                }

            } catch (Exception e) {
                e.printStackTrace();
            }
        };
    }.start();      

}

HttpClient使用post方法提交数据

public void click1(View v)
{

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

    new Thread(){
        public void run() {
            String pathString = "http://192.168.1.101/web/LoginServlet";
            try {

                HttpClient httpClient = new DefaultHttpClient();
                HttpPost httpPost = new HttpPost(pathString);

                //封装我们请求的实体 (用户名 和 密码 )
                List<NameValuePair> parameters = new ArrayList<NameValuePair>();
                NameValuePair nameValuePair = new BasicNameValuePair("username", username);
                NameValuePair pwdValuePair = new BasicNameValuePair("password", password);
                parameters.add(nameValuePair);
                parameters.add(pwdValuePair);
                UrlEncodedFormEntity entity = new UrlEncodedFormEntity(parameters);

                //封装请求体
                httpPost.setEntity(entity);
                //发送post请求
                HttpResponse httpResponse = httpClient.execute(httpPost);

                //获取返回码
                int code = httpResponse.getStatusLine().getStatusCode();
                if(code == 200)
                {
                    //获取响应信息流
                    InputStream in = httpResponse.getEntity().getContent();
                    String retStr = StreamUtils.ReadStream(in);

                    showToast(retStr);
                }

            } catch (Exception e) {
                e.printStackTrace();
            }
        };
    }.start();      

}

2.AsyncHttpClient 开源

这种方式在网络操作中,不需要人为开启子线程

API

使用get方法提交数据

public void click(View v)
{

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

            try {
                //将数据直接写到url中     可以将输入信息进行URI编码,这样可以避免一些字符出错
                String pathString = "http://192.168.1.101/web/LoginServlet?username="+URLEncoder.encode(username,"utf-8")+"&password="+password;

                //获取一个AsyncHttpClient
                AsyncHttpClient asyncHttpClient = new AsyncHttpClient(); 
                //使用get方式请求
                asyncHttpClient.get(pathString, new AsyncHttpResponseHandler() {

                    //请求成功
                    @Override
                    public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
                        if(statusCode == 200)
                        {
                            //从返回信息的entity中获取返回内容
                            String retStr = null;
                            try {
                                retStr = new String(responseBody, "gbk");
                            } catch (UnsupportedEncodingException e) {
                                e.printStackTrace();
                            }

                            showToast(retStr);
                        }

                    }

                    @Override
                    public void onFailure(int statusCode, Header[] headers,
                            byte[] responseBody, Throwable error) {

                    }
                });
            } catch (Exception e) {
                e.printStackTrace();
            }   

}

使用post方法提交数据

public void click1(View v)
{

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

            try {
                String pathString = "http://192.168.1.101/web/LoginServlet";

                AsyncHttpClient asyncHttpClient = new AsyncHttpClient();
                //Post请求的请求信息
                RequestParams params = new RequestParams();
                params.put("username", username);
                params.put("password", password);

                asyncHttpClient.post(pathString, params,new AsyncHttpResponseHandler() {

                    //请求成功
                    @Override
                    public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
                        //获取返回码
                        if(statusCode == 200)
                        {
                            //获取响应信息流
                            String retStr = null;
                            try {
                                retStr = new String(responseBody, "gbk");
                            } catch (UnsupportedEncodingException e) {
                                e.printStackTrace();
                            }

                            showToast(retStr);
                        }

                    }

                    @Override
                    public void onFailure(int statusCode, Header[] headers,
                            byte[] responseBody, Throwable error) {             
                    }
                });

            } catch (Exception e) {
                e.printStackTrace();
            }
}   

上传文件

AsyncHttpClient asyncHttpClient = new AsyncHttpClient();

RequestParams params = new RequestParams();

//params.add("file", file);
try {
        params.put("file", file);
        asyncHttpClient.post("http://192.168.1.101/img", params, new AsyncHttpResponseHandler() {

        @Override
        public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
            showToast("上传成功");
        }

        @Override
        public void onFailure(int statusCode, Header[] headers,
            byte[] responseBody, Throwable error) {
                }
            });

3.多线程下载

API

RandomAccessFile

conn.getContentLength();

Range请求头

  步骤:
1、在客户端创建一个与服务器端大小一样的空白文件     
    //创建空一个文件
    RandomAccessFile raf = new RandomAccessFile(getApplicationContext().getFilesDir().getPath()+"/demo.chm","rw");
    raf.seek(start_index);                                    //指定在空白文件处的写入位置

2、设置子线程的个数

3、计算每个子线程下载的数据块大小和下载起始位置、结束位置


    URL url = new URL(path);
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();

    //***************获取文件服务器上文件的大小****************************
    int contentLength = conn.getContentLength();

    //******Range请求头 限定下载的范围     限定了输入流的取值范围      相当于为流设定了范围*******
    conn.setRequestProperty("Range", "bytes="+start_index+"-"+end_index);

4、创建子线程开始下载数据

5、得到每个子线程都下载完成的标记
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值