gpt4 book ai didi

Android - 发送 HTTPS 获取请求

转载 作者:IT老高 更新时间:2023-10-28 23:27:18 25 4
gpt4 key购买 nike

我想向谷歌购物 api 发送一个 HTTPS 获取请求,但是没有什么对我有用,例如,这是我目前正在尝试的:

try {        
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet();
request.setURI(new URI("https://www.googleapis.com/shopping/search/v1/public/products/?key={my_key}&country=&q=t-shirts&alt=json&rankByrelevancy="));
HttpResponse response = client.execute(request);
} catch (URISyntaxException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return response;

如果有人对如何改进或替换它有任何建议,请告诉我,提前谢谢。

最佳答案

你应该得到一个编译错误。

这是正确的版本:

HttpResponse response = null;
try {
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet();
request.setURI(new URI("https://www.googleapis.com/shopping/search/v1/public/products/?key={my_key}&country=&q=t-shirts&alt=json&rankByrelevancy="));
response = client.execute(request);
} catch (URISyntaxException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return response;

因此,现在如果您遇到错误,您的响应将返回为 null。

一旦您获得响应并检查它是否为空,您就会想要获取内容(即您的 JSON)。

http://developer.android.com/reference/org/apache/http/HttpResponse.html http://developer.android.com/reference/org/apache/http/HttpEntity.html http://developer.android.com/reference/java/io/InputStream.html

response.getEntity().getContent();

这为您提供了一个可以使用的 InputStream。如果要将其转换为字符串,请执行以下操作或等效操作:

http://www.mkyong.com/java/how-to-convert-inputstream-to-string-in-java/

public static String convertStreamToString(InputStream inputStream) throws IOException {
if (inputStream != null) {
Writer writer = new StringWriter();

char[] buffer = new char[1024];
try {
Reader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"),1024);
int n;
while ((n = reader.read(buffer)) != -1) {
writer.write(buffer, 0, n);
}
} finally {
inputStream.close();
}
return writer.toString();
} else {
return "";
}
}

当你有这个字符串时,你需要从它创建一个 JSONObject:

http://developer.android.com/reference/org/json/JSONObject.html

JSONObject json = new JSONObject(inputStreamAsString);

完成!

关于Android - 发送 HTTPS 获取请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9968114/

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