后台要求在body里面上传参数 并且修改ContentType,用之前框架自带的上传失败 下面看我修改并成功传成功的代码
private JSONObject parameters;
public void onLogin() {
parameters = new JSONObject();
String phone = mLoginAccountEt.getText().toString();
String pwd = mLoginPwdEt.getText().toString();
//网络请求封装
mOkHttpClent = new OkHttpClient.Builder()
.addInterceptor(new Interceptor() {
public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
Response response = chain.proceed(request);
return response;
}
})
.connectTimeout(4000, TimeUnit.MILLISECONDS)
.readTimeout(4000, TimeUnit.MILLISECONDS)
.writeTimeout(4000, TimeUnit.MILLISECONDS)
.build();
//添加参数
try {
parameters.put("phone", phone);
parameters.put("password", pwd);
} catch (JSONException e) {
e.printStackTrace();
}
//修改样式
MediaType JSON = MediaType.parse("application/json; charset=utf-8");
//修改样式和上传json参数
RequestBody requestBody = RequestBody.create(JSON, parameters.toString());
//请求封装
request = new okhttp3.Request.Builder()
.url(“”)
.post(requestBody)
.build();
//发送网络请求
mOkHttpClent.newCall(request).enqueue(new okhttp3.Callback() {
@Override
public void onFailure(Call call, IOException e) {
KLog.e("TAG", "onFailure: " + e);
}
@Override
public void onResponse(Call call, okhttp3.Response response) throws IOException {
String result = response.body().string();
KLog.e("TAG", result);
KLog.e("TAG", "成功" + response);
}
});
}
帮助到的小伙伴请下方留言~