在项目开发中,需要在控制器中访问url接口,并得到json串,将得到的json串用于jsp页面。这里总结一下在java代码中分别进行get和post的url访问。
需要准备一下jar包:
org.apache.http.HttpEntity;
org.apache.http.HttpResponse;
org.apache.http.client.ClientProtocolException;
org.apache.http.client.methods.HttpGet;
org.apache.http.impl.client.DefaultHttpClient;
org.apache.http.util.EntityUtils;
Get:
public JSONObject doGetStr(String url) {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
JSONObject jsonObject = null;
try {
HttpResponse response = httpClient.execute(httpGet);
HttpEntity entity = response.getEntity();
if(entity != null) {
String result = EntityUtils.toString(entity,"UTF-8");
jsonObject = JSONObject.fromObject(result);
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return jsonObject;
}
POST:
public static JSONObject doPostStr(String url,String outStr) {//outStr,是出口url
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
JSONObject jsonObject = null;
try {
httpPost.setEntity(new StringEntity(outStr,"UTF-8"));
HttpResponse response = httpClient.execute(httpPost);
String result = EntityUtils.toString(response.getEntity(),"UTF-8");
jsonObject = JSONObject.fromObject(result);
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
return jsonObject;
}