gpt4 book ai didi

java - 从 OkHttp 到 HttpURLConnection

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

出于库兼容性问题的原因,我想使用 HttpURLConnection 来调用 API 上的请求。以下是我与 OkHttp 一起使用来获取 token 访问的代码:

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();
}
}
});

}

所以我想知道如何获得requestbody的等价物并将其传递到setRequestProperty()中?

感谢您的帮助

最佳答案

请求正文不是请求属性( 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();

关于java - 从 OkHttp 到 HttpURLConnection,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61086555/

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