1. 程式人生 > >Java程式碼訪問url,並返回json串之實現方法

Java程式碼訪問url,並返回json串之實現方法

在專案開發中,需要在控制器中訪問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;
}