i should to send image in request body, how can I make it?
RequestQueue requestQueue = Volley.newRequestQueue(getActivity());
String url = getString(R.string.url) + "auth/avatar?token="+ Utils.getToken(getActivity());
JsonObjectRequest request = new JsonObjectRequest(Request.Method.POST, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject jsonObject) {
Log.d("myLogs", jsonObject.toString());
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("avatar", encodedImage);
return params;
}
};
requestQueue.add(request);
I have read this article, but it doesn't help me.
Related
I am trying to send json data to a url in the format below.
{
“amount”:500,
“merchant_id”:”104”,
“narrative”:”John”,
“reference”:”Steven”
}
To send data to the url, one needs an authorization key as the header, I have already figured out how to set the authorization key as the header in Params, as shown below
#Override
public Map<String,String >getHeaders()throws AuthFailureError{
Map<String,String >params=new HashMap<String,String>();
params.put(“Content-Type”, “text/jsom;);
params.put(“AuthKey”, Auth);
return params;
but I do not know how to send the data in the particular format shown in the first instance to the url using params with volley. Please help, I am quite new to using Volley library .
This is the rest of code I am currently using it however does not return any response except for an invalid json error. Meaning the format sent is not corresponding to the one desired.
StringRequest stringRequest=new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Toast.makeText(Main9Activity.this, response, Toast.LENGTH_LONG).show();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(Main9Activity.this, error.toString(), Toast.LENGTH_LONG).show();
}
}){
#Override
protected Map<String, String> getParams() {
HashMap<String, String> params = new HashMap<String, String>();
params.put("amount","500");
params.put("merchant_id", "104");
params.put("narrative","John");
params.put("reference", "Steven");
return params;
}
#Override public Map<String,String>getHeaders()throws AuthFailureError{
Map<String,String>headers=new HashMap<>();
params.put("Content-Type","text/json");
params.put("Authorization",Auth);
return params;
}
};
RequestQueue requestQueue=Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
You can refer below code snipet to post data with custom header in volley.
JSONObject jsonobject = new JSONObject();
jsonobject.put("amount", "500");
jsonobject.put("merchant_id", "104");
jsonobject.put("narrative", "John");
jsonobject.put("reference", "Steven");
JsonObjectRequest jsonObjReq = new JsonObjectRequest(
Request.Method.POST,url, jsonobject,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d(TAG, response.toString());
Toast.makeText(Main9Activity.this, response.toString(), Toast.LENGTH_SHORT).show();
hideProgressDialog();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
Toast.makeText(Main9Activity.this, error.getMessage(), Toast.LENGTH_SHORT).show();
hideProgressDialog();
}
}) {
/**
* Passing some request headers
* */
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String,String >headers=new HashMap<String,String>();
headers.put(“Content-Type”, “application/json“);
headers.put(“AuthKey”, Auth);
return headers;
}
You can send as below:
The data you want to send:
Hashmap<String, Object> data = new HashMap<>();
data.put("amount", "500");
data.put("merchant_id", "104");
data.put("narrative", "John");
data.put("reference", "Steven");
RequestQueue request = Volley.newRequestQueue(context);
JsonObjectRequest jsonobj = new JsonObjectRequest(Request.Method.POST, "your url",new JSONObject(data),
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}
){
};
request.add(jsonobj);
Volley request showing com.android.volley.ServerError also it is neccessary to implement getHeaders() method? What is exact use of this method?
send.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest
(Request.Method.POST, URL, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Toast.makeText(getApplicationContext(),response.toString(),Toast.LENGTH_LONG).show();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
}){
#Override
protected Map<String,String> getParams(){
Map<String,String> params = new HashMap<String, String>();
params.put("username","Admin");
params.put("password", "123456789");
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 requestQueue = Volley.newRequestQueue(getApplicationContext());
requestQueue.add(jsonObjectRequest);
}
});
Generally this type of error occurs when you are using poor internet connection or else your server goes down. There is no need to implement getHeaders() method. Try to just check your connection or server connection.
Use the android volley library,
compile 'com.android.volley:volley:1.0.0'
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Method.POST,
url, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d(TAG, response.toString());
Toast.makeText(getApplicationContext(),response.toString(),Toast.LENGTH_LONG).show();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d(TAG, "Error: " + error.getMessage());
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("username","Admin");
params.put("password", "123456789");
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());
requestQueue.add(jsonObjectRequest);
Hope this will help you (Happy Coding !).
I've created an API in NodeJS that contains headers (which are the tokens).
The volley library (ANDROID) post goes like this:
RequestQueue queue = MyVolley.getRequestQueue();
JsonObjectRequest jsObjRequest = new JsonObjectRequest(Request.Method.POST,REGISTERUSERURL,null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
System.out.println(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
hideProgressDialog();
}
}) {
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("email","myname#gmail.com");
params.put("password", "myname");
return params;
};
};
queue.add(jsObjRequest);
But this doesnt register from the server-side. Whats the issue?
In my application I have to send POST request with JSON req param, I tried to create request with Postman Rest Client and it is working fine but not working with below code.
In Postman req parameter sent as raw data, But I am not sure how to send it with Volley request.
public Request getHTTPPostReqResponse(String URL, Class mClass, final Map<String, String> params, final String contentType, final String body) {
mResponseListener.requestStarted();
Request mRequest = new GsonRequest(Request.Method.POST, URL, mClass, new Response.Listener<Object>() {
#Override
public void onResponse(Object response) {
mResponseListener.requestCompleted(response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
mResponseListener.requestEndedWithError(error);
}
}) {
#Override
protected Map<String, String> getParams() {
return params;
}
#Override
public byte[] getBody() throws AuthFailureError {
if (TextUtils.isEmpty(body)){
return super.getBody();
}else {
return body.getBytes();
}
}
#Override
public String getBodyContentType() {
return contentType;
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("Content-Type", contentType);
return params;
}
};
mRequest.setRetryPolicy(new DefaultRetryPolicy(
MY_SOCKET_TIMEOUT_MS,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
return mRequest;
}
Request Parameter:
{
"nodeId": null,
"userId": null,
"mobileNumber": "993000008",
"emailId": "sharma#gmail.com",
"userProfile": null,
"region": null,
"countryCode": "91",
"password": "pass#123",
"places": [],
"trustedNetwork": [],
"profilePic": null,
"fullName": null,
"longitude": 0.0,
"latitude": 0.0
}
hope this isn't too late.
Have you tried a different type of request, like String or JsonObject?
And a different syntax for the params?
e.g.
Map<String, Object> jsonParams = new ArrayMap<>();
jsonParams.put("nodeId", null);
jsonParams.put("userId", null);
jsonParams.put("mobileNumber", "sharma#gmail.com");
jsonParams.put("userProfile", null);
jsonParams.put("region", null);
jsonParams.put("countryCode", 91);
jsonParams.put("password", pass#123);
jsonParams.put("places", new ArrayList());
jsonParams.put("trustedNetwork", new ArrayList());
jsonParams.put("profilePic", null);
jsonParams.put("fullName", null);
jsonParams.put("longitude", 0.0);
jsonParams.put("latitude", 0.0);
JsonObjectRequest request = new JsonObjectRequest(Request.Method.POST, url, new JSONObject(jsonParams),
new Response.Listener<JSONObject>()
{
#Override
public void onResponse(JSONObject response)
{
mResponseListener.requestCompleted(response);
}
},
new Response.ErrorListener()
{
#Override
public void onErrorResponse(VolleyError error)
{
if (null != error.networkResponse)
{
mResponseListener.requestEndedWithError(error);
}
}
});
Also, have a look at this SO question.
Hope any of this helps.
This is the working code, you can try. we can use JsonObjectRequest for raw data. Here i have just showing how to make requestObject that is added in queue
String url = MConstant.API_END+"/userLogin";
Map<String, String> params = new HashMap<String, String>();
params.put("email",mEmailView.getText().toString());
params.put("password",mPasswordView.getText().toString());
params.put("api",MConstant.API);
JSONObject objRegData = new JSONObject(params);
JsonObjectRequest jsObjRequest = new JsonObjectRequest
(Request.Method.POST, url, objRegData, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
// handle response data
} catch (JSONException e) {
e.printStackTrace();
//pDialog.show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
pDialog.hide();
}
})
{
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("Content-Type", "application/json");
return params;
}
};
in server side PHP we can get data using
$json = file_get_contents('php://input');
$myPostData = json_decode($json, true);
I am sending POST query along with String data from android device using Volley library.
The server however, is receiving only null values for the params. My code goes like this:
final String param1 = "one";
final String param2 = "124843";
final String param3 = "878942";
final String param4 = "885942";
String url = getIPAddr()+":"+getPort()+"/com.va.jersey.helloworld/hello";
RequestQueue queue = Volley.newRequestQueue(getBaseContext());
StringRequest stringRequest = new StringRequest(Request.Method.POST,url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
showOutput(response);
}
},new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
showOutput(error.toString());
}
}){
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("param1", param1);
params.put("param2", param2);
params.put("param3", param3);
params.put("param3", param4);
return params;
} //attaching POST params
};
queue.add(stringRequest);
I believe there is some error in StringRequest, please correct...
Use the code given below and let me know if you are facing any issue
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Method.POST,
url, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d(TAG, response.toString());
pDialog.hide();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
pDialog.hide();
}
}) {
/**
* 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");
headers.put("apiKey", "xxxxxxxxxxxxxxx");
return headers;
}
};
// Adding request to request queue
AppController.getInstance().addToRequestQueue(jsonObjReq, tag_json_obj);