我正在爲公司開發Android應用程序。而在API的工作,公司的傢伙給了我一個登錄API像這樣具有不同格式的網址的HTTP POST請求
"app.abc.com/Login?data={"email":"abc","pwd":"123"} "
我使用抽射庫,但我不知道如何,因爲我沒有做之前發佈這樣的數據。
我需要建議,並想知道這是否正確。
我正在爲公司開發Android應用程序。而在API的工作,公司的傢伙給了我一個登錄API像這樣具有不同格式的網址的HTTP POST請求
"app.abc.com/Login?data={"email":"abc","pwd":"123"} "
我使用抽射庫,但我不知道如何,因爲我沒有做之前發佈這樣的數據。
我需要建議,並想知道這是否正確。
相反凌空..try的使用Android的網絡庫
--to做到這一點:--compile 'com.amitshekhar.android:android-networking:0.4.0' 添加 您gradle這個文件。 enter code here
AndroidNetworking.post("your login URL")
.setTag("Login")
.addBodyParameter("email", "abc")
.addBodyParameter("pwd", "123")
.setPriority(Priority.IMMEDIATE)
.build()
.getAsJSONObject(new JSONObjectRequestListener() {
@Override
public void onResponse(JSONObject response) {
try {
JSONObject dataJson = response.getJSONObject("data");
boolean status = dataJson.getBoolean("success");
} else {
JSONArray errorJsonArray = dataJson.getJSONArray("errors");
String errorMsg;
for (int i = 0; i < errorJsonArray.length(); i++) {
errorMsg = errorJsonArray.get(i).toString();
Toast.makeText(LoginActivity.this, errorMsg, Toast.LENGTH_SHORT).show();
}
Log.e("Error", response.toString());
}
} catch (JSONException je) {
je.printStackTrace();
}
}
@Override
public void onError(ANError anError) {
try {
if (anError.getErrorBody() != null) {
JSONObject jsonObject = new JSONObject(anError.getErrorBody());
JSONObject dataJsonObject = jsonObject.getJSONObject("data");
Toast.makeText(getApplicationContext(), dataJsonObject.getString("message"), Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplicationContext(), anError.getErrorDetail(), Toast.LENGTH_SHORT).show();
}
} catch (Exception e) {
e.printStackTrace();
}
Log.e("Error", anError.getErrorDetail());
}
});
使用排球 - 創建請求隊列
RequestQueue queue = Volley.newRequestQueue(this); // this = context
然後創建postRequest,應該是財產以後像(用亂射):
url = "app.abc.com/Login";
StringRequest postRequest = new StringRequest(Request.Method.POST, url,
new Response.Listener<String>()
{
@Override
public void onResponse(String response) {
// response
Log.d("Response", response);
}
},
new Response.ErrorListener()
{
@Override
public void onErrorResponse(VolleyError error) {
// error
Log.d("Error.Response", response);
}
}
) {
@Override
protected Map<String, String> getParams()
{
Map<String, String> params = new HashMap<String, String>();
params.put("data", "{\"email\":\"abc\",\"pwd\":\"123\"}");
return params;
}
};
queue.add(postRequest);
我還建議使用改造和GSON庫(這裏有點學習曲線,但它是值得的,因爲它們是非常強大的庫)
這是一個帶查詢參數的網址。所以你應該執行一個GET請求。不是POST。 – greenapps