如何用Java实现获取get请求的返回值

AKHYui2020-03-10 02:44:00编程
## 需要引用的包

import java.io.IOException;

import org.apache.http.HttpEntity;

import org.apache.http.HttpResponse;

import org.apache.http.client.ClientProtocolException;

import org.apache.http.client.methods.HttpGet;

import org.apache.http.impl.client.DefaultHttpClient;

import org.apache.http.util.EntityUtils;

import net.sf.json.JSONObject;

jar包下载地址open in new window

编写代码


	public static JSONObject doGetJson(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;

		

	}

Last Updated 9/17/2025, 7:13:55 AM
ON THIS PAGE