How to add Request Body? - android

How to add the request body to my code like using Postman's body tab. I figure it out only request header. 
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final TextView textView = findViewById(R.id.textView);
String url = "url";
RequestQueue requestQueue = Volley.newRequestQueue(this);
JsonObjectRequest objectRequest = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.e("Response : ",response.toString());
textView.setText("Success!");
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("Response error : ",error.toString());
error.printStackTrace();
textView.setText("Failed!");
}
})
{
#Override
public Map getHeaders() throws AuthFailureError {
HashMap headers = new HashMap();
headers.put("accept-language","EN");
headers.put("authorization","<autho>");
headers.put("requestUId","<requestID>");
headers.put("resourceOwnerId","<resorceOwnerID>");
return headers;
}
};
requestQueue.add(objectRequest);
}
}
Ref Postman's head tab :
https://s3.amazonaws.com/postman-static-getpostman-com/postman-docs/58960775.png
Thank you

Create your JSONObject request as below:
JSONObject jsonBody = new JSONObject();
try {
jsonBody.put("firstname", "asd");
jsonBody.put("lastname", "asd");
jsonBody.put("id", "1");
} catch (JSONException e) {
e.printStackTrace();
}
Then the third parameter in the JsonObjectRequest() constructor is the request, you are currently passing null. Replace it with jsonBody.
Edit
You also have to change your HTTP method to POST instead of GET if you want your parameters to be sent in the request body.

Related

Trying to send POST from android to node server using volly but the json body is empty on the server

private void postRequest() {
// Request a string response from the provided URL.
// Instantiate the RequestQueue.
String url = "http://10.0.0.9:3000/hello";
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest
(Request.Method.POST, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try{
Log.i("*********", "******");
response.put("Hello", "World");
}catch(JSONException e){
Log.i("JSONERROR", e.toString());
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// TODO: Handle error
Log.i("*********", error.toString());
}
});
jsonObjectRequest.setRetryPolicy(new RetryPolicy() {
#Override
public int getCurrentTimeout() {
return 1000;
}
#Override
public int getCurrentRetryCount() {
return 1000;
}
#Override
public void retry(VolleyError error) throws VolleyError {
}
});
This is the Android code
app.post('/hello', function(req,res){
console.log(JSON.stringify(req.body))
})
This is the node js code
So the problem im having is that im printing the body to the console but it keeps showing up empty. As you can see in the postRequest method ive put 'hello as key' and 'world as value' in the jsonobject. So it is calling the correct post request, the body is just empty and cant figure out why that is.
Edit-----
Ive checked the content with wireshark and content length is 0 so im not sending anything it seems. if im understanding this correctly
You are not sending anything inside of your POST body request, that's why you are getting an empty response at your server-side.
For sending POST parameters, you will need to override getParams() method:
#Override
protected Map<String, String> getParams() {
Map<String, String> map = new HashMap<String, String>();
map.put("param1", "hello");
map.put("param2", "This is a post request");
return map;
}
Here is the complete example:
private void postRequest() {
// Request a string response from the provided URL.
// Instantiate the RequestQueue.
String url = "http://10.0.0.9:3000/hello";
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest
(Request.Method.POST, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try{
Log.i("*********", "******");
response.put("Hello", "World");
}catch(JSONException e){
Log.i("JSONERROR", e.toString());
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// TODO: Handle error
Log.i("*********", error.toString());
}
}) { // HERE TO ADD POST PARAMETERS
#Override
protected Map<String, String> getParams() {
Map<String, String> map = new HashMap<String, String>();
map.put("param1", "hello");
map.put("param2", "This is a post request");
return map;
}
};
jsonObjectRequest.setRetryPolicy(new RetryPolicy() {
#Override
public int getCurrentTimeout() {
return 1000;
}
#Override
public int getCurrentRetryCount() {
return 1000;
}
#Override
public void retry(VolleyError error) throws VolleyError {
}
});

POST Request in Volley(using JSON instead of String)

I am developing an app in which i find the origin and destination of a car and send it to a server.
I know how to use volley to send an string however i am finding it hard to send data in JSON format.
Part of the code is given below:
b
tnFindPath.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
RequestQueue queue = Volley.newRequestQueue(MapsActivity.this);
String url = "http://192.168.43.162:8080/";
// Request a string response from the provided URL.
StringRequest stringRequest = 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) {
}
}) {
//adding parameters to the request
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("origin", etOrigin.getText().toString());
params.put("destination", etDestination.getText().toString());
return params;
}
};
// Add the request to the RequestQueue.
queue.add(stringRequest);
try this
final String httpUrl = //your url
try {
JSONArray parameters = new JSONArray();
JSONObject jsonObject = new JSONObject();
jsonObject.put(Key,value);
jsonObject.put(Key,value);
parameters.put(jsonObject);
Log.i(TAG,parameters.toString());
JsonArrayRequest arrayRequest = new JsonArrayRequest(Request.Method.POST, httpUrl, parametersForPhp,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG,response.toString());
try {
//your code
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
});
RequestQueueSingleton.getInstance(getApplicationContext()).addToRequestQueue(arrayRequest);
}catch (Exception e){
e.printStackTrace();
}
}

Volley GET with parameters

I have a web service which gives data in JSON array format. Right now the data is being fetched just by passing the URL. But now I want to pass a parameter to get the JSON response. This web service has GET & POST methods.
I tried with Volley - Sending a POST request using JSONArrayRequest answer, but I couldn't implement it in my code. It would be really helpful if somebody could explain, how to achieve this in my code.
This is how my code looks like
String HTTP_SERVER_URL = "https://192.168.1.7/STUDENTWS/Default.asmx/StudentDataJson?InFacultyID=string";
public void JSON_WEB_CALL(){
//mSwipeRefreshLayout.setRefreshing(true);
jsonArrayRequest = new JsonArrayRequest(HTTP_SERVER_URL,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
JSON_PARSE_DATA_AFTER_WEBCALL(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
requestQueue = Volley.newRequestQueue(this);
requestQueue.add(jsonArrayRequest);
}
public void JSON_PARSE_DATA_AFTER_WEBCALL(JSONArray array){
for(int i = 0; i<array.length(); i++) {
DataModel GetDataModel = new DataModel();
JSONObject json = null;
try {
json = array.getJSONObject(i);
GetDataModel.setId(json.getString("STUDENTID"));
GetDataModel.setPlateNo(json.getString("GRADE"));
GetDataModel.setPlateCode(json.getString("HOUSE"));
}
catch (JSONException e)
{
e.printStackTrace();
}
DataAdapterClassList.add(GetDataModel);
mSwipeRefreshLayout.setRefreshing(false);
}
recyclerViewadapter = new NewRecyclerViewAdapter(DataAdapterClassList, this);
recyclerView.setAdapter(recyclerViewadapter);
if (array.length()!=0) {
SHOW_ALERT(array);
sendNotification(recyclerView, array);
}
}
For get with params you should create StringRequest. For example:
RequestQueue queue = Volley.newRequestQueue(context);
StringRequest sr = new StringRequest(Request.Method.GET, "http://headers.jsontest.com/",
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.e("HttpClient", "success! response: " + response.toString());
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("HttpClient", "error: " + error.toString());
}
})
{
#Override
protected Map<String,String> getParams(){
Map<String,String> params = new HashMap<String, String>();
params.put("user","YOUR USERNAME");
params.put("pass","YOUR PASSWORD");
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;
}
};
// for json object
Map<String, String> jsonParams = new HashMap<String, String>();
jsonParams.put("fullname",fullName);
jsonParams.put("email",email);
jsonParams.put("password",password);
// for json array make any list.List will be converted to jsonArray
// example-----
// ArrayList<String> jsonParams =new ArrayList();
// jsonParams.add("Test1")
// jsonParams.add("Test2")
JsonObjectRequest objectRequest=new JsonObjectRequest(Request.Method.POST, url, new JSONObject(jsonParams), new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "onErrorResponse: ",error );
Toast.makeText(ActivitySignUp.this,error.getMessage(), Toast.LENGTH_LONG).show();
}
}){
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String,String> header=new HashMap<String, String>();
header.put("Content-Type","application/json");
return header;
}
};
If you want to pass a param to your server, then you might wanna do a POST method, else.. if you only wanted to get the data, then GET method is the best way... there's also header that you can use to pass data, but, I wouldn't recommend to use header for sending params... that's a sore eyes
Edit
//Set you method POST or GET
JsonObjectRequest(Request.Method.GET(/*here can set to POST too*/), url, null,
new Response.Listener<JSONObject>()
{
#Override
public void onResponse(JSONObject response) {
// display response
Log.d("Response", response.toString());
}
},
new Response.ErrorListener()
{
#Override
public void onErrorResponse(VolleyError error) {
Log.d("Error.Response", response);
}
}
);

Android volley post methode parameter missing

I am using android volley library to post data to back-end service. But I can't send any parameter with my request. I have done each and everything mentioned here . But none works for me. The post method that I am using is:
public static void post()
{
// Tag used to cancel the request
String tag_json_obj = "json_obj_req";
String url = "http://myUrl";
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.POST,
url, obj,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d("TAG", response.toString());
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d("TAG", "Error: " + error.getMessage());
}
}) {
/**
* Passing some request headers
* */
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<String, String>();
return headers;
}
#Override
public String getBodyContentType() {
return "application/x-www-form-urlencoded";
}
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("key", "value");
return params;
}
};
// Adding request to request queue
AppController.getInstance().addToRequestQueue(jsonObjReq, tag_json_obj);
}
Always the response is "parameter missing".
How could i resolve this issue?
If you're using JSONObjectRequest, you can try this.
String url = "http://myurl";
Map<String, String> params = new HashMap<String, String>();
params.put("key", value);
RequestQueue queue = Volley.newRequestQueue(getActivity());
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST,
url, new JSONObject(params),
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject jsonObject) {
try {
success = jsonObject.getInt("success");
message = jsonObject.getString("message");
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
Activity activity = getActivity();
if (volleyError instanceof NoConnectionError) {
String errormsg = "Check your internet connection";
Toast.makeText(activity, errormsg, Toast.LENGTH_LONG).show();
}
}
});
queue.add(jsonObjectRequest);
The codes are more likely the same as yours. Check on the lines where I put the data to be posted. I'm very sure this would work!
The problem is you are approaching the request as though you were making a stringRequest. The link you reference is talking specifically about making a stringRequest.
jsonObjectRequest actually lets you put the json object into the constructor itself, instead of using the override method getParams() like so:
String url = "some_url";
JSONObject jsonObject = new JSONObject();
try {
jsonObject.put(Constants.LOGIN_EMAIL_ID, email);
jsonObject.put(Constants.LOGIN_PASSWORD, password);
}catch(JSONException e){
Log.d("JSON error", e.getMessage(), e);
}
JsonObjectRequest jsObjRequest = new JsonObjectRequest(url, jsonObject, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d("RESPONSE", response.toString());
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
if(error.getMessage()!=null){
Log.d("RESPONSE", error.getMessage());
}
}
});
VolleySingleton.getInstance(activity).getRequestQueue().add(jsObjRequest);

Getting Instamojo link in android

I have been trying to get the Instamojo link in my android application for a transaction. For testing I have been trying to send the post request to generate the link but all the time I am getting AuthFailureError. I am posting my code below.I don't know if some error is there in my codes or I am following the wrong way to integrate Instamojo in my app. Please help.
MainActivity.java:
public class MainActivity extends AppCompatActivity {
private RequestQueue mQueue;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
mQueue = CustomVolleyRequestQueue.getInstance(this)
.getRequestQueue();
String url = "https://www.instamojo.com/api/1.1/payment-requests/";
JSONObject params = new JSONObject();
try {
params.put("purpose","selling");
params.put("amount","20");
} catch (JSONException e) {
e.printStackTrace();
}
final CustomJSONObjectRequest jsonRequest=new CustomJSONObjectRequest(Request.Method.POST, url,params, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response)
{
Log.d("animesh",response.toString());
}
},new Response.ErrorListener()
{
#Override
public void onErrorResponse(VolleyError error)
{
Toast.makeText(MainActivity.this, "no internet connection", Toast.LENGTH_SHORT).show();
Log.d("animesh", error.toString());
}
});
mQueue.add(jsonRequest);
}
}
CustomJSONObjectRequest.java:
public class CustomJSONObjectRequest extends JsonObjectRequest {
public CustomJSONObjectRequest(int method, String url, JSONObject jsonRequest,
Response.Listener<JSONObject> listener,
Response.ErrorListener errorListener) {
super(method, url, jsonRequest, listener, errorListener);
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<String, String>();
//String creds = String.format("%s:%s","archerpenny_glide","archer##62#glide*");
//String auth = "Basic " + Base64.encodeToString(creds.getBytes(), Base64.DEFAULT);
headers.put("api_key", "**********************************");
headers.put("auth_token", "*******************************");
return headers;
}
#Override
public RetryPolicy getRetryPolicy() {
// here you can write a custom retry policy
return super.getRetryPolicy();
}
}
To send the api_key and the auth_token you are doing:
headers.put("api_key", "**********************************");
headers.put("auth_token", "*******************************");
Instead, you need to do:
headers.put("X-Api-Key", "**********************************");
headers.put("X-Auth-Token", "*******************************");
You can refer to the REST API documentation here: https://www.instamojo.com/developers/rest/

Categories

Resources