检查 API 请求正文

Check API Request body

我正在 API 端点上执行 HTTP Post 请求。是OAuth2协议的密码授权授权。

我得到了一个 400 代码,"bad request"..为了前进,我想得到我在 Log.d 语句中进行的确切调用。我的问题是我如何才能准确记录我提出的 POST 请求中有什么?我不清楚该怎么做。这样我就可以开始调试了。

我想找回类似

的东西

API 呼叫 = "https://api.allthingstalk.io/login/parameters"..

现在很难调试..

    // This method gets the AccessToken from the API EndPoint, this token is encoded in a class Token with all its parameters..
@RequiresApi(api = Build.VERSION_CODES.KITKAT)
public static Token getAccessToken () {

    Token accessToken = null;
    String urlParameters  = "param1=a&param2=b&param3=c";
    @SuppressLint({"NewApi", "LocalSuppress"}) byte[] postData = urlParameters.getBytes( StandardCharsets.UTF_8 );

    try {
        URL url = new URL("https://api.allthingstalk.io/login");
        HttpURLConnection client = null;

        client = (HttpURLConnection) url.openConnection();
        client.setRequestMethod("POST");
        client.setRequestProperty("grant_type", "password");
        client.setRequestProperty("username", username);
        client.setRequestProperty("password", password);
        client.setRequestProperty("client_id", "com.example.gebruiker.internetofthingsattplatform");
        client.setRequestProperty("Content-Type:", "application/x-www-form-urlencoded");
        client.setUseCaches(false);
        client.setDoOutput(true);

        int status = client.getResponseCode();
        String status_String = Integer.toString(status);
        Log.d(TAG, status_String);

        OutputStream outputStream = new BufferedOutputStream(client.getOutputStream());
        outputStream.write(postData);
        String postData_String = postData.toString();
        Log.d(TAG, postData_String);
        outputStream.flush();
        outputStream.close();


        if (client != null) // Make sure the connection is not null.
            client.disconnect();
    }
    catch(MalformedURLException error) {
    }
    catch(SocketTimeoutException error) {
    }
    catch (IOException error) {
    }

    return accessToken;
}

首先,我强烈建议使用像@Luis Henriques 提到的Retrofit 这样的库。 Retrofit 简化了构建手册中的许多复杂性 URLConnections。

也就是说,您几乎完全按照发送时的样子查看您的请求。如果您想要更精细的视图,我建议将您的 URL 更改为您控制的主机(即 home/office 设置中的本地主机)并通过 Wireshark 监控连接(使确保您将其作为 HTTP 而不是 HTTPS 请求发送。

作为一个潜在的错误,您将 urlParameters 作为 post body 传递。您不想将 URL 参数作为 URL 的一部分吗?还要查看 API documentationgrant_typepasswordusernameclient_id,应该在您的 post body 中而不是设置为请求 属性。 setRequestProperty 设置 header 属性。