how to send simple raw array in android volley - android

Anyone know how to send post request with raw data in android volley ..?
I want to post this array list with headers.
[{
"Name": "qwertytestinggfgfgf"
}]
Here is my code:
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> headers = new HashMap<String, String>();
headers.put("Content-Type", "application/json");
headers.put("Authorization", "my Authorization code is here ");
return headers;
}
#Override
protected Map<String, String> getParams() {
HashMap<String, String> params = new HashMap<String, String>();
params.put("name", "rahatamjid");
return params;
}
Here is a screen shot.
headesr section is working good.

You better send request with json like this:
JsonRequest<JSONObject> jsonRequest = new JsonObjectRequest(Method.POST,httpurl, jsonObject,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d(TAG, "response -> " + response.toString());
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, error.getMessage(), error);
}
})
{
#Override
public Map<String,String> getHeaders() throws AuthFailureError {
Map<String,String> headers = new HashMap<String, String>();
headers.put("Content-Type", "application/json");
headers.put("Authorization", "my Authorization code is here ");
return headers;
}
};

please try this and let me know:
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> params = new HashMap<String, String>();
String creds = String.format("%s:%s","USERNAME","PASSWORD"); //please adapt this to your auth type
String auth = "Basic " + Base64.encodeToString(creds.getBytes(), Base64.DEFAULT);
params.put("Authorization", auth);
params.put("Content-Type", "application/json");//
return params;
}

Override getBodyContentType to jsonBody in jsonObjectRequest method
#Override
public String getBodyContentType() {
return "application/json;charset=UTF-8";
}
then put your raw data in json object with key.
the root object should be jsonObject to post.It should not be json array
JSONObject jsonObject = new JSONObject();
jsonObject.put("yourKey",value);

Add more to Hashmap
Try like this,
#Override
protected Map<String, String> getParams() {
HashMap<String, String> params = new HashMap<String, String>();
params.put("name1", "rahatamjid1");
params.put("name2", "rahatamjid2");
params.put("name3", "rahatamjid3");
params.put("name4", "rahatamjid4");
Log.i("request","" + params);
return params;
}
This may helps you.

Related

Volley is not working with SOAP api in Android

Hi All I am using Volley and trying to parse data from SOAP api. Following is my snippet code, when I try to parse data it is giving error. Can any one help me with this? I am getting following error every time.
E/Volley: [7440] BasicNetwork.performRequest: Unexpected response
code 400 for
public void HttpPOSTRequestWithParam() {
RequestQueue queue = Volley.newRequestQueue(this);
String url = "https://www.myweb.co.ke/Wt/webtask.asmx?op=GetProductListing";
StringRequest postRequest = new StringRequest(Request.Method.POST, url,
new Response.Listener<String>()
{
#Override
public void onResponse(String response) {
Log.e("Response", response);
}
},
new Response.ErrorListener()
{
#Override
public void onErrorResponse(VolleyError error) {
Log.e("ERROR","error => "+error.toString());
}
}
) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("UserName", "John");
return params;
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("User Name", "1234");
params.put("Password", "4321");
return params;
}
};
queue.add(postRequest);}
You may need to tell it how the Content-Type and Accept headers are encoded. Here the parameter string should look like:
'grant_type=password&username=apikey&password=apipassword'
#Override
protected Map<String, String> getParams()
{
Map<String, String> params = new HashMap<String, String>();
params.put("grant_type", "password");
params.put("username", "apikey");
params.put("password", "apipassword");
return params;
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<String, String>();
headers.put("Accept", "application/x-www-form-urlencoded; charset=UTF-8");
headers.put("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
return headers;
}

Volley Post Request not working to the API

I used Volley to POST name, password and email of a user for registration purpose. I took reference from This tutorial. And worked same as defined in this tutorial.
Here is my code:
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST,
URL_string.api_url,null
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.i("Result", "Success");
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.i("Result", "UnSuccess");
}
}){
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
Log.i("Result_Params",emailValue + passwordValue + nameValue);
params.put("email", emailValue);
params.put("password", passwordValue);
params.put("name", nameValue);
return super.getParams();
}
#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 super.getHeaders();
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
jsonObjectRequest.setRetryPolicy(new DefaultRetryPolicy(DefaultRetryPolicy.DEFAULT_TIMEOUT_MS * 2, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
requestQueue.add(jsonObjectRequest);
But my code shows this error:
[368] BasicNetwork.performRequest: Unexpected response code 422 for http://myapi.com/api/register
Error 422 is defined on the API as:
{
"message": "422 Unprocessable Entity",
"errors": {
"email": [
"The email field is required."
],
"password": [
"The password field is required."
],
"name": [
"The password field is required."
]
},
"status_code": 422
}
I tried:
changing JsonObjectRequest to StringRequest,
the original URL at the place of URL_string.api_url,
But the response is still same. Is this because of I didn't make any class for Volley library? I did that too from Androidhive.info, but failed!
I don't know how to go ahead from this step now, while Log in getParams logs the correct value of name, email, and pw entered by the user, but still POST operation is not working. Please help!
Thanks in advance!
You need to return the params object you create, not returning the parent's method (which is empty).
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
Log.i("Result_Params",emailValue + passwordValue + nameValue);
params.put("email", emailValue);
params.put("password", passwordValue);
params.put("name", nameValue);
return params; //not super.getParams();
}
As pointed out by pablobu, this also applies to your getHeaders():
#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; //not super.getHeaders();
}

How to make volley post string request with attaching headers?

I google and I tried to post string request by attaching headers. But I always get auth failure error.It seems my header is not setting properly. Here is my code
StringRequest stringRequest = new StringRequest(Request.Method.POST, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d("response",response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
if (error!=null){
error.printStackTrace();
}
}
}){
#Override
protected Map<String,String> getParams(){
Map<String,String> params = new HashMap<String, String>();
params.put("client_id=",getString(R.string.client_id));
params.put("&client_secret=",getString(R.string.client_secret));
params.put("&grant_type=","authorization_code");
params.put("&code=",accessToken);
return params;
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> params = new HashMap<String, String>();
params.put("Authorization", "Basic " + base64);
params.put("Content-Type", "application/x-www-form-urlencoded");
params.put("Accept", "*/*" );
return super.getHeaders();
}
};
RequestQueue requestQueue = Volley.newRequestQueue(getActivity());
requestQueue.add(stringRequest);
I attached headers in getHeaders() and stream writer in getParams().Can somebody help me to resolve this.Thanks in advance.
Dont put params like this
params.put("&grant_type=","authorization_code");
replace like this
params.put("grant_type", authorization_code);
Dont add & and = sign it will automatically included.
#Override
protected Map<String,String> getParams(){
Map<String,String> params = new HashMap<String, String>();
params.put("client_id",getString(R.string.client_id));
params.put("client_secret",getString(R.string.client_secret));
params.put("grant_type","authorization_code");
params.put("code",accessToken);
return params;
}
try header like this
#Override
public Map getHeaders() throws AuthFailureError {
Map headers = new HashMap();
headers.put("appId", "MYAPP_ID_HERE");
return headers;
}

Is it possible to send JSON Object instead of HASH MAP <String, String> using Volley?

I can POST Map <String, String> to my server but it comes in & separated form.
I have used code from Send post request using Volley and receive in PHP
getParams() just doesn't work with JSONObject return type. Is it possible to send JSONObject as JSON only?
I want to send data as JSON that I will get using file_get_contents(php://input).
For this I have changed Content-Type to application/json; charset=utf-8.
The problem is using this way I get data in format of x=abc&y=def as it's Map<String, String> type and I want data in JSON format of {"x":"abc", "y":"def"}
It's different from above question because I want to POST data in JSON ONLY and not in MAP of String
Try this :
private void jsonObjReq() {
showProcessDialog();
Map<String, String> postParam= new HashMap<String, String>();
postParam.put("un", "xyz#gmail.com");
postParam.put("p", "somepasswordhere");
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Method.POST,
Const.URL_LOGIN, new JsonObject(postParam),
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d(TAG, response.toString());
msgResponse.setText(response.toString());
hideProgressDialog();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
hideProgressDialog();
}
}) {
/**
* Passing some request headers
* */
#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;
}
};
change header in your php too.
the easy way is this
final RequestQueue requestQueue = Volley.newRequestQueue(this);
final String url ="http://mykulwstc000006.kul/Services/Customer/Register";
Map<String, String> params = new HashMap<String, String>();
params.put("MobileNumber", "+97333765439");
params.put("EmailAddress", "danish.hussain4#das.com");
params.put("FirstName", "Danish2");
params.put("LastName", "Hussain2");
params.put("Country", "BH");
params.put("Language", "EN");
JsonObjectRequest req = new JsonObjectRequest(url, new JSONObject(params),
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
VolleyLog.v("Response:%n %s", response.toString(4));
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.e("Error: ", error.getMessage());
}
}){
#Override
public String getBodyContentType() {
return "application/json; charset=utf-8";
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
String username ="eli#gmail.com";
String password = "elie73";
String auth =new String(username + ":" + password);
byte[] data = auth.getBytes();
String base64 = Base64.encodeToString(data, Base64.NO_WRAP);
HashMap<String, String> headers = new HashMap<String, String>();
headers.put("Authorization","Basic "+base64);
return headers;
}
};
requestQueue.add(req);
}

Pass a JsonObject in Volley as POST parameter

I have an API endpoint which needs parameters to be sent as JsonObject in a POST request.
The response which I will get is not Json, but rather a small CSV string.
The Code is
stringRequest = new StringRequest(Request.Method.GET, "http://apitest.eezyrent.com/api/userauthentication/SignUp",
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
// Display the first 500 characters of the response string.
Toast.makeText(getApplication(), response.toString(), Toast.LENGTH_SHORT).show();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplication(), error.getMessage(), Toast.LENGTH_SHORT).show();
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> jsonParams2 = new HashMap<String, String>();
jsonParams2.put("vcFName", firstname.getText().toString());
jsonParams2.put("vcLname", lastname.getText().toString());
jsonParams2.put("vcMobileNo", phone_no.getText().toString());
jsonParams2.put("vcGender", gender_short);
jsonParams2.put("vcEmailAddress", email.getText().toString());
jsonParams2.put("vcPassword", password.getText().toString());
jsonParams2.put("vcFBID", "");
jsonParams2.put("intLoginUserID", "");
jsonParams2.put("SignUpFrom", "Web");
jsonParams2.put("intloginid", "");
jsonParams2.put("AlreadyRegister", "");
return jsonParams2;
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<String, String>();
headers.put("Content-Type", "application/json");
headers.put( "charset", "utf-8");
return headers;
}
};
The above code is heavily inspired by using answers from this community, but this does not seem to solve the problem for me.
I get Volley Error 405.
E/Volley﹕ [112549] BasicNetwork.performRequest: Unexpected response code 405 for http://myurl
Infact If I used AsyncTask instead of Volley, With the same json as parameters and the same endpoint url. It works!! The AsyncTask code was found from this question. Java HttpClient changing content-type?
But I want to use Volley, What could be the solution to this?
Sample JSON Object
{"vcFName":"Ron","vcLname":"Weasley","vcMobileNo":"555888999","vcGender":"M","vcEmailAddress":"someone#somewhere.com","vcPassword":"123456","vcFBID":"","intLoginUserID":'',"SignUpFrom":"Web","intloginid":"","AlreadyRegister":""}
You need to use JsonObjectRequest class. Pass your params as json object in the 3rd parameter of the JsonObjectRequest class. Below is a small snippet:
Map<String, String> jsonParams2 = new HashMap<String, String>();
jsonParams2.put("vcFName", firstname.getText().toString());
jsonParams2.put("vcLname", lastname.getText().toString());
jsonParams2.put("vcMobileNo", phone_no.getText().toString());
jsonParams2.put("vcGender", gender_short);
jsonParams2.put("vcEmailAddress", email.getText().toString());
jsonParams2.put("vcPassword", password.getText().toString());
jsonParams2.put("vcFBID", "");
jsonParams2.put("intLoginUserID", "");
jsonParams2.put("SignUpFrom", "Web");
jsonParams2.put("intloginid", "");
jsonParams2.put("AlreadyRegister", "");
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Method.POST,
YourUrl, new JsonObject(jsonParams2),
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<String, String>();
headers.put("Content-Type", "application/json");
headers.put( "charset", "utf-8");
return headers;
}
};
Step 1: Make model class parsable/Serializable.
Step 2: Override toString() in model class.
Step 3:
Map<String,JSONObject> params = new HashMap<>();
JSONObject object = null;
try{
object = new JSONObject(classObject.toString());
}catch (Exception e){
}
params.put("key", object);
JSONObject objectParams = new JSONObject(params);
Step 4: Send objectParams with volley JSONObject request.
Done!!!

Categories

Resources