java使用httpclient请求

java的okhttp3.OkHttpClient的使用发送请求和获取请求

OkHttpClient client = new OkHttpClient();
// 构建请求体,请求参数放在里面
FormBody.Builder builder = new FormBody.Builder();
builder.add("username", "xxx");
builder.add("password", "xxxxxx");
RequestBody requestBody = builder.build();
Request request = new Request.Builder()
    .addHeader("Content-Type", "application/x-www-form-urlencoded")
    .post(requestBody)
    .url("https://127.0.0.1/login")
    .build();
try (Response response = client.newCall(request).execute()) {
    if (response.isSuccessful()) {
        // 获取请求结果
        String body = response.body().string();
        JSONObject JSONBody = JSONUtil.parseObj(body);
        JSONObject data = JSONUtil.parseObj(JSONBody.getStr("data"));
        String accessToken = data.getStr("accessToken");
        setCacheObject("playAccessToken", accessToken);
    }

} catch (Exception e) {
    e.printStackTrace();
}

你可能感兴趣的:(其他,java,java,网络,开发语言)