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

How to build the body of a request in json format

这是我应该调用的请求: 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 但没有成功。

感谢您的帮助。

我认为文档有误,您应该使用 POST 请求而不是 GET。

记录的 JSON 请求正文中也存在错误:尾随逗号不应存在。使用以下内容:

String body2 = "{\"pageSize\": \"100\"}";

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

您可以使用此查询在邮递员中尝试此请求

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

并在身份验证部分传递令牌。

在这里你可以做一些事情 -

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

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