http版本在4.4以下的
String uriAPI = "http://api.map.baidu.com/geocoder/v2/?callback=renderReverse&location=38.107464,106.33148&output=json&pois=1&ak=cDhHNKOl0chemjlvUxjjf3bMgLMGqUBh";
String result= "";
// HttpGet httpRequst = new HttpGet(URI uri);
// HttpGet httpRequst = new HttpGet(String uri);
// 创建HttpGet或HttpPost对象,将要请求的URL通过构造方法传入HttpGet或HttpPost对象。
HttpGet httpRequst = new HttpGet(uriAPI);
// new DefaultHttpClient().execute(HttpUriRequst requst);
try {
//使用DefaultHttpClient类的execute方法发送HTTP GET请求,并返回HttpResponse对象。
HttpResponse httpResponse = new DefaultHttpClient().execute(httpRequst);//其中HttpGet是HttpUriRequst的子类
if(httpResponse.getStatusLine().getStatusCode() == 200)
{
HttpEntity httpEntity = httpResponse.getEntity();
result = EntityUtils.toString(httpEntity);//取出应答字符串
// 一般来说都要删除多余的字符
result.replaceAll("
", "");//去掉返回结果中的"
"字符,否则会在结果字符串后面显示一个小方格
}
else
httpRequst.abort();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
result = e.getMessage().toString();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
result = e.getMessage().toString();
}
return result;
http版本在4.4以上的
String res = "0";
// //创建默认的httpClient实例
// CloseableHttpClient httpClient = getHttpClient();
// try {
// //用get方法发送http请求
// HttpGet get = new HttpGet(url);
// System.out.println("执行get请求:...."+get.getURI());
// CloseableHttpResponse httpResponse = null;
// //发送get请求
// httpResponse = httpClient.execute(get);
// try{
// //response实体
// HttpEntity entity = httpResponse.getEntity();
// if (null != entity){
// System.out.println("响应状态码:"+ httpResponse.getStatusLine());
// System.out.println("-------------------------------------------------");
//// System.out.println("响应内容:" + EntityUtils.toString(entity));
//// System.out.println("-------------------------------------------------");
// res = EntityUtils.toString(entity);
// res =res.replaceAll("
", "");
// }
//
// }
// finally{
// httpResponse.close();
// }
// } catch (Exception e) {
// e.printStackTrace();
// }
// finally{
// try{
// closeHttpClient(httpClient);
// } catch (IOException e){
// e.printStackTrace();
// }
// }
// return res;
//
// }
sendpost
public static String sendPost(String url)throws IOException {
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(url);
post.addHeader(HTTP.CONTENT_TYPE, "application/json; charset=UTF-8");
post.addHeader("Client-info", "7a70c7d702d57cee5125ee35f2970f89");
StringEntity entity = new StringEntity(mockData(), "UTF-8");
post.setEntity(entity);
HttpResponse response = client.execute(post);
System.out.println(response.getStatusLine().getStatusCode());
String result = EntityUtils.toString(response.getEntity(), "UTF-8");
System.out.println(result);
return result;
}
static String mockData() {
JSONObject news = new JSONObject();
news.put("cityCode", "640100");
return news.toString();
}