我正在为公司开发Android应用。在使用API时,公司人员给了我一个像这样的登录API
"app.abc.com/Login?data={"email":"abc","pwd":"123"} "
我正在使用凌空图书馆但我不知道如何发布这样的数据,因为我之前没有这样做过。
我需要建议并想知道这是否正确。
答案 0 :(得分:0)
而不是凌空..使用android网络库
- 要这样做:添加
--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());
}
});
答案 1 :(得分:0)
使用Volley - 创建请求队列
RequestQueue queue = Volley.newRequestQueue(this); // this = context
然后创建postRequest,应该看起来像(使用Volley):
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);
我还建议使用Retrofit和GSON库(这里有一点学习曲线,但它是值得的,因为它们是非常强大的库)