【发布时间】:2016-10-29 09:44:45
【问题描述】:
我在在线服务器上托管了我的 API。当我使用适用于 chrome 的 Postman 应用程序对其进行测试时,它返回了正确的结果(即数据库中用户的详细信息)但下面的 Volley 请求得到了错误的结果(即缺少必需的参数);
邮递员请求的屏幕截图
截击请求
private void loginUser(final String username, final String password){
String URL_REGISTER = "http://www.h8pathak.orgfree.com/jobs/login.php";
pDialog.setMessage("Logging in...");
showDialog();
StringRequest strReq = new StringRequest(Request.Method.POST,
URL_REGISTER, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
hideDialog();
try {
JSONObject jObj = new JSONObject(response);
int result = jObj.getInt("result");
if(result==1){
session.setLogin(true);
JSONObject jObj2 = jObj.getJSONObject("user");
Intent i = new Intent(LoginActivity.this, EmployerActivity.class);
i.putExtra("username", jObj2.getString("username"));
i.putExtra("email", jObj2.getString("email"));
startActivity(i);
finish();
Toast.makeText(LoginActivity.this, jObj.getString("message"), Toast.LENGTH_SHORT).show();
}
else{
Toast.makeText(LoginActivity.this, jObj.getString("message"),Toast.LENGTH_SHORT).show();
}
}
catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError volleyError) {
Toast.makeText(LoginActivity.this, volleyError.getMessage(), Toast.LENGTH_SHORT).show();
hideDialog();
}
}){
@Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<>();
params.put("username", username);
params.put("password", password);
return params;
}
};
AppController.getInstance().addToRequestQueue(strReq);
}
PHP 代码,用于接收请求参数并返回适当的响应。
if(isset($_POST['username']) && isset($_POST['password'])) {
$username = $_POST['username'];
$password = $_POST['password'];
//Get the details from the database and echo in a json response
}
else{
$message = "Required parameters missing!";
$response['result']=0;
$response['message']=$message;
echo json_encode($response);
}
可能的错误是什么?
【问题讨论】:
-
您是否将用户名和密码作为参数添加到请求中?此外,您应该使用 JSONObjectRequest 而不是 StringRequest 来响应此响应。
-
你收到的结果是什么??分享你的logcat
-
除了 url 本身之外,您在邮递员中传递的其他数据是什么?
-
请提供问题的完整描述。到底出了什么问题?你读过this吗?
-
@Artjom 我已经为问题添加了更多细节。
标签: android api rest android-volley postman