1.通过FormBody做post请求
OkHttpClient client = new OkHttpClient();
FormBody formBody = new FormBody
.Builder()
.add("username", username)
.add("password", password)
.add("age", "12")
.add("sex", "man")
.add("email", "123@qq.com")
.build();
final Request request = new Request.Builder()
.url(UrlPool.HOST + "oauth/thirdUid.do?") //请求地址
.post(formBody)
.build();
Call call = client.newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
Toast.makeText(StartActivity.this,"失败",Toast.LENGTH_LONG).show();
}
@Override
public void onResponse(Call call, Response response) throws IOException {
final String responseStr = response.body().string();
System.out.println("-------成功"+responseStr);
ATOK atok1 = new Gson().fromJson(responseStr,ATOK.class);
atok = atok1.getDATA().getATOK();
// username = userInfo.getT_loginID();
System.out.println("******"+atok);
runOnUiThread(new Runnable() {
@Override
public void run() {
//做耗时操作
}
});
}
});
2.通过json数据请求
OkHttpClient okHttpClient = new OkHttpClient(); String jsonParms ; String url = "你的url"; String loginPassword = MD5AESEncryption.getMd5AESEncrption(password); JSONObject jsonObject = new JSONObject(); try { jsonObject.put("loginName",userName); jsonObject.put("passWord",loginPassword); } catch (JSONException e) { e.printStackTrace(); } jsonParms = jsonObject.toString(); RequestBody body = RequestBody.create(MediaType.parse("application/json"),jsonParms); Request request = new Request.Builder().post(body).url(url).build(); okHttpClient.newCall(request).enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { } @Override public void onResponse(Call call, Response response) throws IOException { String str = response.body().string(); try { JSONObject object = new JSONObject(str); String code = (String) object.get("CODE"); if(code.equals("0")){ runOnUiThread(new Runnable() { @Override public void run() { getATOK_2(login_user.getText().toString()); } }); } } catch (JSONException e) { e.printStackTrace(); } } });