从 OkHttp 到 HttpURLConnection

Go from OkHttp to HttpURLConnection

出于库兼容性问题的原因,我想使用 HttpURLConnection 来调用 API 上的请求。 这是我使用 OkHttp 获取令牌访问的代码:

private void getAccessToken(){

        OkHttpClient okHttpClient = new OkHttpClient();
        RequestBody requestBody = new FormEncodingBuilder().add("grant_type", "authorization_code")
                .add("client_id", "1568xxxxxxxxxxxxxxxxxjro.apps.googleusercontent.com")
                .add("client_secret", "AMe0xxxxxxxxxxxx")
                .add("redirect_uri", "")
                .add("code", serverCode)
                .build();
        Request request = new Request.Builder()
                .url("https://www.googleapis.com/oauth2/v4/token")
                .post(requestBody)
                .build();
        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Request request, IOException e) {
                Log.i("severcode","failure");
            }

            @Override
            public void onResponse(Response response) throws IOException {
                try {
                    JSONObject jsonObject = new JSONObject(response.body().string());
                    token = jsonObject.optString("access_token");
                    tokenExpired = SystemClock.elapsedRealtime() + jsonObject.optLong("expires_in") * 1000;
                    Log.i("severcode",String.valueOf(token));
                    createGooglePhotosClient();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });

    }

所以我想知道如何在setRequestProperty()中获取requestbody的等价物来传递它?

感谢您的帮助

请求正文不是请求属性(header),它是请求的正文,没有OkHttp或其他支持库你必须自己格式化,编码任何需要的特殊字符编码等

String requestBody = "grant_type=authorization_code&client_id=1568xxxxxxxxxxxxxxxxxjro.apps.googleusercontent.com&" 
      + "client_secret=AMe0xxxxxxxxxxxx&redirect_uri=&code=" + serverCode + "\n\n";
byte[] requestBodyBytes = requestBody.getBytes("UTF-8");

获得请求正文后,将其写入连接的输出流。例如:

connection.setRequestProperty("content-type", "application/x-www-form-urlencoded");
connection.setDoOutput(true);
out = connection.getOutputStream();
out.write(requestBodyBytes)
out.flush();