需要的第三方库:https://yun.baidu.com/share/link?shareid=3540318765&uk=1697368809
POST请求的结构体:
//创建OkHttpClient的对象
OkHttpClient client=new OkHttpClient();
//url地址
String url="http://10.200.20.164:8080/OrderManager/login";
//携带参数
FormEncodingBuilder builder=new FormEncodingBuilder();
Request request = new Request.Builder().url(url).post(builder.build())
.build();
client.newCall(request).enqueue(new Callback(){
/接口调用成功
public void onResponse(Response arg0) throws IOException {}
//接口调用失败
public void onFailure(Request arg0, IOException arg1) {}
});
登录POST请求关键代码:
//创建okHttpClient对象
OkHttpClient client = new OkHttpClient();
//url地址
String url = "url地址";
//post添加参数
FormEncodingBuilder builder = new FormEncodingBuilder();
builder.add("loginName", name);
builder.add("loginPasswd",psword);
builder.add("deptNo", "001");
Request request = new Request.Builder().url(url).post(builder.build())
.build();
client.newCall(request).enqueue(new Callback() {
@Override
//接口调用成功
public void onResponse(Response arg0) throws IOException {
// 0--成功,1--失败,2--异常
try {
JSONObject jo = new JSONObject(arg0.body().string());
int ret = jo.getInt("ret");// 判断返回字段是否成功或失败
if (ret == 1) {
handler.sendEmptyMessage(0);
} else if(ret==-1) {
handler.sendEmptyMessage(1);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
@Override
//接口调用失败
public void onFailure(Request arg0, IOException arg1) {
handler.sendEmptyMessage(2);
}
});
Handler handler = new Handler() {
public void handleMessage(android.os.Message msg) {
switch (msg.what) {
case 0:
Intent intent = new Intent(LoginActivity.this,
MainActivity.class);
Toast.makeText(getApplicationContext(), "登录成功",Toast.LENGTH_SHORT).show();
startActivity(intent);
finish();
break;
case 1:
Toast.makeText(getApplicationContext(), "登录失败",Toast.LENGTH_SHORT).show();
break;
case 2:
Toast.makeText(getApplicationContext(), "网络异常,请检查网络",Toast.LENGTH_SHORT).show();
break;
default:
break;
}
}
};