使用Http协议访问网络的方式其一是HttpURLConnection,第二则是HttpClient(还有其它方式,只是目前还没有学习到,以后继续补充)。
HttpClient使用的步骤如下:(千万记得网络请求要在线程中发出,或者使用AsyncTask工具)
1.创建HttpClient实例,HttpClient接口不能被实例化,所以创建一个DefaultHttpClent实例
HttpClient httpClient = new DefaultHttpClient();
2.如果发起GET请求,则创建HttpGet对象,并且调用httpClient的execute方法传入HttpGet对象,并且返回服务器信息HttpResponse对象
HttpGet httpGet = new HttpGet("http://www.baidu.com");
HttpResponse httpResponse = httpClient.execute(httpGet);
3.取出服务器信息的状态吗,如果等于200则说明响应成功
if(httpResponse.getstatusLine.getStatusCode == 200){
}
4.在判断体内部调用getEntity()获得一个HttpEntity实例,并且调用EntityUtils.toString()静态方法把该实例转化为字符串对象
if(httpResponse.getstatusLine.getStatusCode == 200){
HttpEntity entity = httpResponse.getEntity();
String response = EntityUtils.toString(entity, "utf-8");//服务器返回的数据带有中文,所以要把字符集指定为utf-8
}
下面贴出完整代码:
private void sendRequestWithHttpClient(){ new Thread(new Runnable(){ @Override public void run(){ try{ HttpClient httpClient = new DefaultHttpClient(); //指定访问的服务器是本机 HttpGet httpGet = new HttpGet("http://10.0.2.2/get_data.json"); HttpResponse httpResponse = httpClient.execute(httpGet); if(httpResponse.getStatusLine().getStatusCode() == 200){ //请求和响应都成功了 HttpEntity httpEntity = httpResponse.getEntity(); String response = EntityUtils.toString(httpEntity, "utf-8"); parseJSONWithGSON(response); } }catch (Exception e){ e.printStackTrace(); } } }).start(); }
原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/7818.html