我是Android Studio,Java和Stack Overflow的完整入门者。我的应用程序使用Volley执行了许多HTTP Post请求,因此,我用代码执行了独立的Java类来执行Post请求。
public class HTTPReq
{
public String postRequest(final HashMap<String,String> params, final Context context)
{
RequestQueue requestQueue=Volley.newRequestQueue(context);
String url="<my_url>";
StringRequest stringRequest=new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
@Override
public void onResponse(String response)
{
Toast.makeText(context, response, Toast.LENGTH_LONG).show();
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(context, "Response Failed", Toast.LENGTH_LONG).show();
}
}){
@Override
protected Map<String,String> getParams(){
return params;
}
@Override
public Map<String,String> getHeaders() throws AuthFailureError{
Map<String,String> params=new HashMap<String, String>();
params.put("Content-Type","application/x-www-form-urlencoded");
return params;
}
};
requestQueue.add(stringRequest);
}
}
我试图实现的是使用return返回http请求对函数调用的响应。函数调用如下:
public void login(String phno, String password,Context context)
{
HashMap<String,String> credentials = new HashMap<String, String>();
credentials.put("pass","pwd");
credentials.put("phno","132");
HTTPReq httpReq = new HTTPReq();
String response = httpReq.postRequest(credentials,context);
Toast.makeText(context, response, Toast.LENGTH_LONG).show();
}
我希望很清楚我要实现的目标。请帮助我。
测试
public class HTTPReq {
public void postRequest(final String pass, final String phno, final Context context) {
RequestQueue requestQueue = Volley.newRequestQueue(context);
String url = "<my_url>";
StringRequest stringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
Toast.makeText(context, response, Toast.LENGTH_LONG).show();
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(context, "Response Failed", Toast.LENGTH_LONG).show();
}
}) {
@Override
protected Map<String, String> getParams() {
HashMap<String,String> params = new HashMap<>();
params.put("user", pass);
params.put("phno", phno);
return params;
}
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("Content-Type", "application/x-www-form-urlencoded");
return params;
}
};
requestQueue.add(stringRequest);
}
}