【发布时间】:2020-07-20 01:24:41
【问题描述】:
这是我应该调用的请求: listing library contents
获取https://photoslibrary.googleapis.com/v1/mediaItems 内容类型:应用程序/json 授权:Bearer oauth2-token { "pageSize": "100", }
这是我尝试过的:
public String getJSON(String url, int timeout) {
String body1 = "{pageSize: 100,}";
String body2 = "{\"pageSize\": \"100\",}";
HttpURLConnection request = null;
try {
URL u = new URL(url);
request = (HttpURLConnection) u.openConnection();
request.setRequestMethod("GET");
request.setRequestProperty("Authorization", "Bearer " + token);
request.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
request.setUseCaches(false);
request.setAllowUserInteraction(false);
request.setConnectTimeout(timeout);
request.setReadTimeout(timeout);
request.setRequestProperty("Content-Length", String.format(Locale.ENGLISH, "%d", body2.getBytes().length));
OutputStream outputStream = request.getOutputStream();
outputStream.write(body2.getBytes());
outputStream.close();
request.connect();
int status = request.getResponseCode();
switch (status) {
case 200:
case 201:
BufferedReader br = new BufferedReader(new InputStreamReader(request.getInputStream()));
StringBuilder sb = new StringBuilder();
String line;
while ((line = br.readLine()) != null) {
sb.append(line+"\n");
}
br.close();
return sb.toString();
}
} catch (MalformedURLException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
} finally {
if (request != null) {
try {
request.disconnect();
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
return null;
}
如果我使用 GET 方法,我会收到错误:
java.net.ProtocolException:方法不支持请求正文:GET
我尝试使用 POST 但没有成功。
感谢您的帮助。
【问题讨论】:
-
带有请求正文的 GET 非常不寻常,许多 HTTP 客户端都不支持。这听起来像一个文档错误,并且您实际上打算使用 POST 而不是 GET。当您尝试 POST 时发生了什么?
-
响应码 = 404
-
404 = 找不到资源。您确定您的网址正确吗?
-
是的,因为如果我不指定 {"pageSize": "100",} 没关系...除了我只得到 GET 指定的前 25 个项目
-
@Joni 如果我使用 OkHttp3 ...我该如何提出请求?与 {"pageSize": "100",}
标签: java android json httpurlconnection