您的位置:首页 > 理论基础 > 计算机网络

HttpClient的使用

2015-09-14 08:20 519 查看
HttpClientActivity

布局

HttpClient是Apache提供的HTTP网络访问接口,从一开始 的时候就被引入到了AndroidAPI中,它可以完成和HttpURLConnection几乎一模一样的效果,但两者之间的用法却有较大的差别。

1、首先我们要知道HttpClient是一个接口,因此无法创建它的实例,通常情况下都会创建一个DefaultHttpClient的实例,如下所示:

[code]HttpClient httpClient=new DefaultHttapClient();


2、如果想要发起一条GET请求,就可以创建一个HttpGet对象,并传入目标网络地址,然后调用HttpClient的execute()方法即可:

[code]HttpGet httpGet=new HttpGet("http://www.baidu.com");
httpClient.execute(httpGet);


3、如果发起一条POST请求会GET稍微复杂一点,我们需要创建一个HttpPost对象,并传入目标的网络地址,如下所示:

[code]HttpPost httpPOst=new HttpPost("http://www.baidu.com");


4、然后通过NameValuePair集合来存放待提交的参数,并将这个参数集合传入到一个UrlEncodedFormEntity中,然后调用HttpPost的setEntity()方法构建好的UrlEncodedFormEntity传入,如下所示:

[code]List<NameValuePair> params=new ArrayList<NameValuePair>();
List<NameValuePair> params=new ArrayList<NameValuePair>();
                params.add(new BasicNameValuePair("username","admin"));
                params.add(new BasicNameValuePair("password","123456"));
                UrlEncodedFormEntity entity=new UrlEncodedFormEntity(params,"utf_8");
                httpPost.setEntity(entity);


5、接下来的操作就和HttpGet一样了,调用HttpClient的execute()方法,并将HttpPost对象传入即可:

[code]httpClient.execute(httpPost);


6、执行execute()方法之后会返回一个HttpResponse对象,服务器所返回的所用信息就会包含在里面。通常情况下我们会先取出服务器返回的状态码,如果等于200就说明请求和响应都成功了,如下所示:

[code]if(httpResponse.getStatusLine.getStatusCode()==200){
//请求和响应都成功了
}


7、接下来在这个if判断的内部取出服务返回的具体内容,可以调用getEntity()方法获取到一个HttpEntity实例,然后在调用EntityUtils.toString()这个静态 方法将HttpEntity转换成字符串即可,如下所示:

[code]HttpEntity entity=httpResponse.getEntity();
String response=EntityUtils.toString(entity);


注意:如果服务器返回的数据是带有中文的,直接调用EntityUtils.toString()方法进行转换会有乱码的情况出现,这个时候只需要在转换的时候将字符集指定成utf-8就可以了,如下所示:

[code]String response=EntityUtils.toString(entity,"utf-8");


9、要取出服务器返回的内容,在调用getEntity()方法取得HttpEntity实例后,也可以用得到输入流的方法,从输入流中在返回的数据。如下所示:

[code]InputStream is=entity.getContent();//得到输入流
                    BufferedReader br=new BufferedReader(new InputStreamReader(is));
                    String line=br.readLine();
                    while (line!=null){
                    System.out.println(line);
                       line=br.readLine();
                    }
                }


HttpClientActivity

[code]public class HttpClientActivity extends AppCompatActivity implements View.OnClickListener {
    private Button mButtonDoGet;
    private Button mButtonDoPost;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_httpclient);
        mButtonDoGet= (Button) findViewById(R.id.button_doget);
        mButtonDoGet.setOnClickListener(this);
        mButtonDoPost= (Button) findViewById(R.id.button_dopost);
        mButtonDoPost.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
switch (v.getId()){
    case R.id.button_doget:
        MyAsyncTask task=new MyAsyncTask();
        task.execute();
        break;
    case R.id.button_dopost:
        break;
}

    }
    class MyAsyncTask extends AsyncTask<String ,Integer,String>{
        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
        }

        @Override
        protected void onProgressUpdate(Integer... values) {
            super.onProgressUpdate(values);
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }

        @Override
        protected String doInBackground(String... params) {
            HttpClient client=new DefaultHttpClient();
            //"http://192.168.0.198:8080/MyAndroidServlet/MyServlet?name=kangsang&password=123"
            String urlString="http://192.168.0.43:8080/www/MyserverTest?name=liujiaorui&password=123456";
            HttpGet get=new HttpGet(urlString);//设置为get方法
            //设置服务器接收后的数据以utf-8的方式读取
            get.setHeader("Content_Type","application/x-www-form-urlencoded;charset=UTF-8");

            try {
                HttpResponse response=client.execute(get);//执行get方法得到服务器的返回的所有数据都在response中
                StatusLine statusLine=response.getStatusLine();//httpClient访问服务器返回的表头,包含http状态码
                int code=statusLine.getStatusCode();//得到状态码
                if (code== HttpURLConnection.HTTP_OK){
                    HttpEntity entity=response.getEntity();//得到数据的实体
                    InputStream is=entity.getContent();//得到输入流
                    BufferedReader br=new BufferedReader(new InputStreamReader(is));
                    String line=br.readLine();
                    while (line!=null){
                    System.out.println(line);
                       line=br.readLine();
                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            return "连接成功";
        }
    }
}


布局

[code]<Button
    android:id="@+id/button_doget"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="GET"/>
    <Button
        android:id="@+id/button_dopost"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="POST"/>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: