private void phoneLogin() {
OkHttpClient okHttpClient = new OkHttpClient.Builder()
.connectTimeout(10, TimeUnit.SECONDS)
.writeTimeout(10, TimeUnit.SECONDS)
.readTimeout(20, TimeUnit.SECONDS)
.build();
//使用Gson 添加 依赖 compile 'com.google.code.gson:gson:2.8.1'
Gson gson = new Gson();
//使用Gson将对象转换为json字符串
String json = gson.toJson(loginRequest);
//MediaType 设置Content-Type 标头中包含的媒体类型值
RequestBody requestBody = FormBody.create(MediaType.parse("application/json; charset=utf-8")
, json);
Request request = new Request.Builder()
.url(tvIp.getText().toString() + APIUtils.LoginAPI.PHONE_LOGIN)//请求的url
.post(requestBody)
.build();
//创建/Call
Call call = okHttpClient.newCall(request);
//加入队列 异步操作
call.enqueue(new Callback() {
//请求错误回调方法
@Override
public void onFailure(Call call, IOException e) {
System.out.println("连接失败");
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(MainActivity.this, e.getMessage().toString(), Toast.LENGTH_LONG).show();
}
});
}
@Override
public void onResponse(Call call, Response response) throws IOException {
String result = response.body().string();
Gson gson1 = new Gson();
java.lang.reflect.Type type1 = new TypeToken<LoginResponse>() {}.getType();
LoginResponse loginResponse = gson1.fromJson(((JsonObject)new JsonParser().parse(result)).get("content"), type1);
runOnUiThread(new Runnable() {
@Override
public void run() {
tvToken.setText(loginResponse.getSuposToken());
}
});
}
});
}
一個简单的okhttp访问网络的例子
最新推荐文章于 2025-02-27 16:21:47 发布
这段代码展示了如何使用OkHttpClient进行网络请求。配置了超时时间,并通过Gson将对象转换为JSON字符串,设置请求头及Content-Type,然后发送POST请求到指定URL。请求成功后,解析响应并更新UI。
1207

被折叠的 条评论
为什么被折叠?



