標籤:
需要的第三方庫: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;
}
}
};
android 使用第三方okhttp進行登入請求