gpt4 book ai didi

java - 如何构建 json 格式的请求正文

转载 作者:行者123 更新时间:2023-12-02 08:45:59 26 4
gpt4 key购买 nike

这是我应该调用的请求: listing library contents

GET https://photoslibrary.googleapis.com/v1/mediaItems Content-type: application/json Authorization: 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: method does not support a request body: GET

我尝试过 POST 但没有成功。

感谢您的帮助。

最佳答案

我认为您需要随此请求发送一个参数

您可以使用此查询在 postman 中尝试此请求

https://photoslibrary.googleapis.com/v1/mediaItems?pageSize=100

并在身份验证部分传递 token 。

在这里你可以做类似的事情 -

eg 
URI uri = new URIBuilder("https://photoslibrary.googleapis.com/v1/mediaItems")
.addParameter("pageSize", 100)
.build();

建议 - 对网络请求使用改造,对 JSON 转换使用 jackson-databind 项目。

关于java - 如何构建 json 格式的请求正文,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61087034/

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