如果在Android Studro 中使用 需要 在build.gradle 中android { 下 添加 这一行useLibrary 'org.apache.http.legacy'
/**
* GET方式请求网络
*/
private void httpGet(String name) {
// HttpClient得到HttpClient对象
HttpClient httpClient = new DefaultHttpClient();
// 以get方式请求.并设置接口地址
HttpGet httpGet = new HttpGet("url字符串");
try {
// 连接网络请求数据,请求到的数据在httpResponse对象里
HttpResponse httpResponse = httpClient.execute(httpGet);
// 服务器返回的内容在HttpEntity
HttpEntity entity = httpResponse.getEntity();
// 把entity转成String
String string = EntityUtils.toString(entity);
//可以做一些操作 例如 解析Gson串
//Gson gson = new Gson();
//Bean bean = gson.fromJson(string, Bean.class);
//传给Handler 处理
//Message msg = Message.obtain();
//msg.obj = bean;
//handler.sendMessage(msg);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* POST方式请求
*
* @param name
*/
protected void httpPost(String name) {
//创建HttpClient对象
HttpClient httpclient=new DefaultHttpClient();
//通过POST方式请求 path同样是url字符串
HttpPost httpPost=new HttpPost(path);
//得到一个集合,这个集合里添加的是要传递给服务器的参数
List<NameValuePair> parameters=new ArrayList<NameValuePair>();
//consName=狮子座
//type=today
//以键值对的形式添加参数
parameters.add(new BasicNameValuePair("consName", name));
parameters.add(new BasicNameValuePair("type", "year"));
parameters.add(new BasicNameValuePair("key", key));
try {
//设置实体内容和编码格式
UrlEncodedFormEntity encodedFormEntity=new UrlEncodedFormEntity(parameters, "UTF-8");
//设置实体,用于传递给服务器参数
httpPost.setEntity(encodedFormEntity);
//请求网络
HttpResponse httpResponse = httpclient.execute(httpPost);
//先得到状态行,从状态行里得到状态码
if( httpResponse.getStatusLine().getStatusCode()==200){
//得到实体
HttpEntity entity = httpResponse.getEntity();
//请求到的json
String string = EntityUtils.toString(entity);
//同样可做解析 操作 传值给Handler处理
}
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
其实 不建议Android Studio 使用 HttpClient 感觉 OkHttp 挺好用 大家可以看一看 了解下