gpt4 book ai didi

java - Java上最基本的HttpGet请求

转载 作者:太空宇宙 更新时间:2023-11-04 14:27:40 26 4
gpt4 key购买 nike

我需要帮助对返回 JSON 对象的网站执行 RESTful 调用。我坚持使用可用的选项,但我更喜欢使用开箱即用的东西,而不是安装任何第三方插件。

这是我目前所拥有的:

import java.io.*;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

HttpClient httpClient = new DefaultHttpClient();
HttpGet httpGetRequest = new HttpGet("http://search.twitter.com/search.json?q=%40apple");

HttpResponse httpResponse = httpClient.execute(httpGetRequest);

我知道此示例中使用的 URL 返回以下内容:

{"errors":[{"message":"The Twitter REST API v1 is no longer active. Please migrate to API v1.1. https://dev.twitter.com/docs/api/1.1/overview.","code":64}]}

这对我来说没问题,我只想至少将 JSON 响应转换为字符串,以便我可以从这里继续。我非常熟悉 REST 的工作原理,并且很容易让它在 Objective-C 和 Python 上工作,但出于某种原因,Java 有十几个实现让它正常工作,我只是在寻找最基本的方法可能,我没有做任何疯狂的事情,比如将图像上传到服务器。

所以我上面的代码的问题是我收到了 ClientProtocolException 错误,并且 httpClient.execute() 需要一个 try catch 语句,这是品牌的东西对我来说是个新手,我从来没有因为没有插入 try catch 语句而被编译器大喊大叫。

如何修复此问题以调用将非常基本的 JSON 对象转换为字符串的 url?

最佳答案

这段代码应该可以工作:

try {
HttpResponse response;
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet getConnection = new HttpGet(url);
try {
response = httpClient.execute(getConnection);
String JSONString = EntityUtils.toString(response.getEntity(),
"UTF-8");
JSONObject jsonObject = new JSONObject(JSONString); //Assuming it's a JSON Object

} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
}

关于java - Java上最基本的HttpGet请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26499828/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com