HTTP POST Request as a different Java Class - Android Studio - java

I am a complete noob to Android Studio, Java and Stack Overflow. My app performs a lot of HTTP Post requests using Volley and hence I've made an independent Java class with the code to perform the post request.
public class HTTPReq {
String[] finalResponse = new String[1];
public String postRequest(final HashMap<String,String> params, final Context context) {
RequestQueue requestQueue = Volley.newRequestQueue(context);
String url = "https://reqres.in/api/login";
StringRequest stringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
finalResponse[0] = response;
Toast.makeText(context, "2" + finalResponse[0], Toast.LENGTH_LONG).show();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
finalResponse[1] = error.getMessage();
//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);
Toast.makeText(context, "3" + finalResponse[0], Toast.LENGTH_LONG).show();
return finalResponse[0];
}
}
What I'm trying to achieve is to get the response of the http request to the function call using return.
The function call is as follows:
public void login(String phno, String password,Context context)
{
HashMap<String,String> credentials = new HashMap<String, String>();
credentials.put("email","eve.holt#reqres.in");
credentials.put("password","cityslicka");
HTTPReq httpReq = new HTTPReq();
String response = httpReq.postRequest(credentials,context);
Toast.makeText(context, "1" + response, Toast.LENGTH_LONG).show();
}
I hope it's clear what I'm trying to achieve. Please help me with this.

your con use feature interface
public class HTTPReq {
public void postRequest(final HashMap<String, String> params, final Context context, final ResponseCallBack callBack) {
RequestQueue requestQueue = Volley.newRequestQueue(context);
String url = "https://reqres.in/api/login";
StringRequest stringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
callBack.onResponse(response);
Toast.makeText(context, response, Toast.LENGTH_LONG).show();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
callBack.onError(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);
}
}
calss interface :
import com.android.volley.VolleyError;
public interface ResponseCallBack<T> {
public void onResponse(T response);
public void onError(VolleyError error_response);
}
MainActivity:
public class MainActivity extends AppCompatActivity implements ResponseCallBack {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
HTTPReq httpReq = new HTTPReq();
HashMap<String, String> credentials = new HashMap<String, String>();
credentials.put("email", "eve.holt#reqres.in");
credentials.put("password", "cityslicka");
httpReq.postRequest(credentials, this, this);
}
#Override
public void onResponse(Object response) {
Log.e("TAG", "onResponse: " + response);
}
#Override
public void onError(VolleyError error_response) {
Log.e("TAG", "onError: " + error_response);
}

Related

Send Header And Data(Body) as String in Volley

I am trying to send a post request to my server
my server read Headers of the request in String Format but getHeaders() in Volley return : Map< String, String >
Is there any way to send headers of request in string Format ?!
this is my Code Request :
Map<String, String> params = new HashMap<String, String>();
params.put("MY_FIRST_DATA_KEY", "MY_FIRST_DATA_VALUE");
params.put("MY_SECOND_DATA_KEY", "MY_SECOND_DATA_VALUE");
String url = "http://MY_URL.com";
JsonObjectRequest request = new JsonObjectRequest(Request.Method.POST, url, new JSONObject(params), new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.e(TAG, "onResponse: " + response.toString() );
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "onErrorResponse: " + error.toString() );
error.printStackTrace();
}
})
{
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String,String> headers = new HashMap<String, String>();
headers.put("Content-Type", "application/json");
headers.put("MY_KEY","MY_VALUE");
/* HERE i need to return a String Value */
return headers;
}
};
request.setRetryPolicy(new DefaultRetryPolicy(20000 , 3 , 3));
Volley.newRequestQueue(context).add(request);
try overriding getParams()
#Override
protected Map<String,String> getParams(){
Map<String, String> params = new HashMap<String, String>();
params.put("MY_FIRST_DATA_KEY", "MY_FIRST_DATA_VALUE");
params.put("MY_SECOND_DATA_KEY", "MY_SECOND_DATA_VALUE");
return params;
}
You can add getParams() in the JsonObjectRequest()
#Override
public Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("Parameter1", "value");
params.put("Parameter2", "value");
return params;
}
Hope it helps.
This is how I made a volley POST request adding headers and body
private void call_api(final String url){
if(!this.isFinishing() && getApplicationContext() != null){
new Handler(Looper.getMainLooper()).post(new Runnable() {
#Override
public void run() {
resultsTextView.setVisibility(View.INVISIBLE);
loader.setVisibility(View.VISIBLE);
}
});
Log.e("APICALL", "\n token: " + url);
StringRequest stringRequest = new StringRequest(Request.Method.POST, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.e("APICALL", "\n response: " + response);
if(!FinalActivity.this.isFinishing()){
try {
JSONObject response_json_object = new JSONObject(response);
JSONArray linkupsSuggestionsArray = response_json_object.getJSONObject("data").getJSONArray("package");
final JSONObject k = linkupsSuggestionsArray.getJSONObject(0);
final String result = k.getJSONArray("action").getJSONObject(0).getString("url");
last_results = result;
last_results_type = k.getString("type");
new Handler(Looper.getMainLooper()).post(new Runnable() {
#Override
public void run() {
loader.setVisibility(View.INVISIBLE);
resultsTextView.setText(result);
resultsTextView.setVisibility(View.VISIBLE);
}
});
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(), "An unexpected error occurred.", Toast.LENGTH_LONG).show();
finish();
}
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("APICALL", "\n error: " + error.getMessage());
Toast.makeText(getApplicationContext(), "Check your internet connection and try again", Toast.LENGTH_LONG).show();
finish();
}
}) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> headers = new HashMap<>();
headers.put("apiUser", "user");
headers.put("apiKey", "key");
headers.put("Accept", "application/json");
//headers.put("Contenttype", "application/json");
return headers;
}
#Override
protected Map<String, String> getParams() {
Map<String, String> map = new HashMap<>();
map.put("location", "10.12 12.32");
return map;
}
};
stringRequest.setShouldCache(false);
stringRequest.setRetryPolicy(new DefaultRetryPolicy(
DefaultRetryPolicy.DEFAULT_TIMEOUT_MS * 2,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());
requestQueue.add(stringRequest);
}
}

Android: How to call put method in Volley?

When i call URL on postman, it returns expected result. I use PUT method using Volley, but it does not work.
StringRequest reg=new StringRequest(Request.Method.PUT, AppConfig.Registration, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d("USER_REG",response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("USER_REG","-------------"+error);
}
}){
#Override
protected Map<String,String> getParams(){
Map<String,String> params = new HashMap<String, String>();
params.put(name1,Name);
params.put(client_id1,CID);
params.put(email1,Email);
params.put(mobile1,Mobile);
params.put(password1,Password);
params.put(device_id1,"123456");
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(reg);
Here's the postman output.
Currently you are sending the data from your Android using Volley as path parameters which should be sent as JSON like the following.
RequestQueue queue = Volley.newRequestQueue(this);
private void makeJsonObjReq() {
Map<String, String> postParam= new HashMap<String, String>();
postParam.put(name1,Name);
postParam.put(client_id1,CID);
postParam.put(email1,Email);
postParam.put(mobile1,Mobile);
postParam.put(password1,Password);
postParam.put(device_id1,"123456");
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Method.PUT,
Const.YOUR_URL, new JSONObject(postParam),
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d(TAG, response.toString());
msgResponse.setText(response.toString());
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
}
}) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<String, String>();
headers.put("Content-Type", "application/json; charset=utf-8");
return headers;
}
};
jsonObjReq.setTag(TAG);
queue.add(jsonObjReq);
You need to add the Content-Type as application/json in the header as well.

HTTPPOST Android with Body

I was looking for an easy way to make an HTTP post in Android with body, my api call should be like :
https:url/api/message?token=myToken&channel=Pew&text=someText&username=User
What I did is this, I created this class
Public class ApiCalls {
private static PostCommentResponseListener mPostCommentResponse;
private static Context mContext;
public ApiCalls(){
}
public static void postNewComment(Context context, final String message){
mContext = context;
String apiUrl = context.getResources().getString(R.string.api_url);
mPostCommentResponse.requestStarted();
RequestQueue queue = Volley.newRequestQueue(context);
StringRequest sr = new StringRequest(Request.Method.POST,apiUrl, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
mPostCommentResponse.requestCompleted();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
mPostCommentResponse.requestEndedWithError(error);
}
}){
#Override
protected Map<String,String> getParams(){
Map<String,String> params = new HashMap<String, String>();
params.put("token",mContext.getResources().getString(R.string.access_token));
params.put("channel","pew");
params.put("text", message);
params.put("username","User");
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;
}
};
queue.add(sr);
}
public interface PostCommentResponseListener {
public void requestStarted();
public void requestCompleted();
public void requestEndedWithError(VolleyError error);
}
}
But it doesn't work, it only shows app has stopped.
Is good to use Volley? Or you recommend to me to use other way? I used to use HttpClient but it's deprecated now...
What I'm missing?
Log error
java.lang.NullPointerException: Attempt to invoke interface method 'void com.package.ApiCalls$PostCommentResponseListener.requestStarted()' on a null object reference
You can send json body using volly as below two ways.
1. Using JsonObjectRequest
Map<String,String> params = new HashMap<String, String>();
params.put("token",mContext.getResources().getString(R.string.access_token));
params.put("channel","pew");
params.put("text", message);
params.put("username","User");
JsonObjectRequest request_json = new JsonObjectRequest(URL, new JSONObject(params),
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
//Process success response
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// handle error
}
});
// add the request object to the queue to be executed
queue.add(request_json);
2. Using JSON directly in request body
JSONObject jsonBody = new JSONObject();
jsonBody.put("token",mContext.getResources().getString(R.string.access_token));
jsonBody.put("channel","pew");
jsonBody.put("text", message);
jsonBody.put("username","User");
final String mRequestBody = jsonBody.toString();
StringRequest sr = new StringRequest(Request.Method.POST,apiUrl, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
// Process success response
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// handle error
}
}){
#Override
public String getBodyContentType() {
return "application/json; charset=utf-8";
}
#Override
public byte[] getBody() throws AuthFailureError {
try {
return mRequestBody.getBytes("utf-8");
} catch (Exception e) {
return null;
}
}
#Override
protected Response<String> parseNetworkResponse(NetworkResponse response) {
String responseString = "";
if (response != null) {
responseString = String.valueOf(response.statusCode);
}
return Response.success(responseString, HttpHeaderParser.parseCacheHeaders(response));
}
};
// add the request object to the queue to be executed
queue.add((sr);
Initialise your mPostCommentResponse like this:
public ApiCalls(){
mPostCommmentResponse = (PostCommentResponseListener)mContext;
}
it will do you work and rest is fine. Thanks.
EDITED:
In Another Activity from where you want to call "ApiCall" class, do code like that:
new ApiCalls().postNewComment(AnotherActivity.this,"Your Messsage here");
and in method "postNewComment" do like this:
mContext = context;
mPostCommmentResponse = (PostCommentResponseListener)mContext;
Is it ok and understable??

How to send Post request using Volley in Android?

I am sending a volley request like this
btnSignUp.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//submitForm();
JsonObjectRequest jsonobjectRequest = new JsonObjectRequest(Request.Method.POST, URL, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
//errorlabel.setText(response.toString());
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
errorlabel.setText("Invalid username / password");
}
}){
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("email", "asd#asd.com");
params.put("password", "asd");
return params;
}
};
errorlabel.setText(jsonobjectRequest.toString());
requestQueue.add(jsonobjectRequest);
}
});
}
But I get an error message from the server saying invalid email/password.
I have set up the correct params. I tested it out on Postman and it works in there. Here is a screenshot.
Screenshot
I had same problem and i tried with String request, its working
StringRequest jsonObjRequest = new StringRequest(Request.Method.POST,
URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}) {
#Override
public String getBodyContentType() {
return "application/x-www-form-urlencoded; charset=UTF-8";
}
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> postParam = new HashMap<String, String>();
postParam.put("email", "asd#asd.com");
postParam.put("password", "asd");
return postParam;
}
};
requestQueue.add(jsonObjRequest);

How to send request Header is "Content-Type":"application/json" when GET on Volley

I try to use GET on Volley , but i need send request to application/json .
I take a look for some answers , i try to use jsonBody , but it shows error:
null com.android.volley.ServerError
Here is my code:
public class MainActivity extends AppCompatActivity {
String url = "http://114.35.246.42:2212/MobileApp/DEST_WebService.asmx/GetNews";
JSONObject jsonBody;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
try {
//I try to use this for send Header is application/json
jsonBody = new JSONObject("{\"type\":\"example\"}");
} catch (JSONException ex) {
ex.printStackTrace();
}
RequestQueue mQueue = Volley.newRequestQueue(getApplicationContext());
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(url, jsonBody,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d("TAG", response.toString());
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("TAG", error.getMessage(), error);
}
});
mQueue.add(jsonObjectRequest);
}
}
Is any one can teach me how to fix this , any help would be appreciated.
Here is my url:
String url = "http://114.35.246.42:2212/MobileApp/DEST_WebService.asmx/GetNews";
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("Content-Type", "application/json");
return params;
}
Implementation in your's
public class MainActivity extends AppCompatActivity {
String url = "http://114.35.246.42:2212/MobileApp/DEST_WebService.asmx/GetNews";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
RequestQueue mQueue = Volley.newRequestQueue(getApplicationContext());
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(url, jsonBody,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d("TAG", response.toString());
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("TAG", error.getMessage(), error);
}
}) { //no semicolon or coma
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("Content-Type", "application/json");
return params;
}
};
mQueue.add(jsonObjectRequest);
}
}
In general for setting a custom header you need to override getHeaders and set the custom header manually. However, volley handles content type headers differently and getHeaders way does not always work.
So for your case you need to override getBodyContentType. So your code will look like
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(url, jsonBody,new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d("TAG", response.toString());
}, new Response.ErrorListener(){
#Override
public void onErrorResponse(VolleyError error) {
Log.e("TAG", error.getMessage(), error);
}
}){
#Override
public String getBodyContentType(){
return "application/json";
}
};
I try to use GET on Volley
The docs for the method you are calling says this
Constructor which defaults to GET if jsonRequest is null, POST otherwise
You can't GET with an HTTP JSON body. Maybe that's the error.
//I try to use this for send Header is application/json
jsonBody = new JSONObject("{\"type\":\"example\"}");
That's not the header, so pass in null here to do GET
new JsonObjectRequest(url, null,
And towards the end of your request, override a method to request JSON
...
#Override
public void onErrorResponse(VolleyError error) {
Log.e("TAG", error.getMessage(), error);
}
}) { // Notice no semi-colon here
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("Content-Type", "application/json");
return params;
}
};
Use String request instead of jsonrequest like this
StringRequest loginMe = new StringRequest(Request.Method.GET, "http://114.35.246.42:2212/MobileApp/DEST_WebService.asmx/GetNews", new Response.Listener<String>() {
#Override
public void onResponse(String response) {
System.out.println("LoginActivity -- onResponse --> " + response);
if (progressDialog != null) {
progressDialog.dismiss();
}
try {
JSONObject jsonObject = new JSONObject(response);
} catch (Exception e) {
CommonUtility.somethingWentWrongDialog(activity,
"LoginActivity -- onResponse-- Exception --> ".concat(e.getMessage()));
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
if (progressDialog != null) {
progressDialog.dismiss();
}
CommonUtility.somethingWentWrongDialog(activity,
"LoginActivity -- onErrorResponse --> ".concat(error.getMessage()));
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<>();
System.out.println("LoginActivity -- LoginParams --> " + params.toString());
return params;
}
};
loginMe.setRetryPolicy(new DefaultRetryPolicy(60000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
Volley.newRequestQueue(activity).add(loginMe);

Categories