OKHttp3学习之五:POST请求(JSON参数形式)
需求:实现用户登陆,登录信息以JSON参数的形式发送
在app模块的build.gradle配置
compile 'com.squareup.okhttp3:okhttp:3.4.2'
实现源码
public void postRequest(View view) {
String username = mEtUserName.getText().toString().trim();
String password = mEtPassWord.getText().toString().trim();
loginWithJson(username, password);
}
private void loginWithJson(String username, String password) {
OkHttpClient client = new OkHttpClient();
String url = SERVER_ADDRESS + "/login/json";
//构建JSON参数
JSONObject json = new JSONObject();
try {
json.put("username", username);
json.put("password", password);
} catch (JSONException e) {
e.printStackTrace();
}
String jsonParams = json.toString();
Log.i(TAG, "json params: " + jsonParams);
//设置 Content-Type为 application/json
RequestBody body = RequestBody.create(MediaType.parse("application/json"), jsonParams);
Request request = new Request.Builder().url(url).post(body).build();
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
Log.i(TAG, "请求失败: " + e.getLocalizedMessage());
}
@Override
public void onResponse(Call call, Response response) throws IOException {
if (response.isSuccessful()) {
ResponseBody body = response.body();
if (body != null) {
String result = body.string();
Log.i(TAG, "返回成功: " + result);
body.close();
JSONObject json = null;
try {
json = new JSONObject(result);
final int code = json.optInt("code");
final String message = json.optString("message");
runOnUiThread(new Runnable() {
@Override
public void run() {
if (code == 1) {
Log.i(TAG, "登录成功");
} else {
Log.i(TAG, "登录失败");
}
Toast.makeText(MainActivity.this, message, Toast.LENGTH_SHORT).show();
}
});
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
});
}
请求JSON参数
json params: {"username":"Joe.Ye","password":"123456"}
服务器返回数据
{
"code": 1,
"message": "登陆成功"
}
版权声明:
作者:Joe.Ye
链接:https://www.appblog.cn/index.php/2023/02/25/okhttp3-learning-5-post-request-json/
来源:APP全栈技术分享
文章版权归作者所有,未经允许请勿转载。
THE END
0
二维码
打赏
海报
OKHttp3学习之五:POST请求(JSON参数形式)
需求:实现用户登陆,登录信息以JSON参数的形式发送
在app模块的build.gradle配置
compile 'com.squareup.okhttp3:okhttp:3.4.2'
实现源码
public ……
文章目录
关闭
共有 0 条评论