E/Volley: [217] BasicNetwork.performRequest: Unexpected response code 415 [duplicate] - java

Server side:
import flask
import flask.ext.sqlalchemy
import flask.ext.restless
app = flask.Flask(__name__)
app.config['DEBUG'] = True
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:////tmp/test.db'
SQLALCHEMY_TRACK_MODIFICATIONS=True
db = flask.ext.sqlalchemy.SQLAlchemy(app)
class Person(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.Unicode, unique=True)
birth_date = db.Column(db.Date)
class Computer(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.Unicode, unique=True)
vendor = db.Column(db.Unicode)
purchase_time = db.Column(db.DateTime)
owner_id = db.Column(db.Integer, db.ForeignKey('person.id'))
owner = db.relationship('Person', backref=db.backref('computers',
lazy='dynamic'))
db.create_all()
manager = flask.ext.restless.APIManager(app, flask_sqlalchemy_db=db)
manager.create_api(Person, methods=['GET', 'POST', 'DELETE'])
manager.create_api(Computer, methods=['GET'])
app.run(host='0.0.0.0', port=5000, debug=True)
Client Side :
Using volley post
RequestQueue queue = Volley.newRequestQueue(this);
StringRequest postRequest = new StringRequest(Request.Method.POST, url,
new Response.Listener<String>()
{
#Override
public void onResponse(String response) {
// response
Log.d("Response", response);
}
},
new Response.ErrorListener()
{
#Override
public void onErrorResponse(VolleyError error) {
// error
Log.d("Error.Response", String.valueOf(error));
}
}
) {
#Override
protected Map<String, String> getParams()
{
Map<String, String> params = new HashMap<String, String>();
params.put("name", "Anything");
return params;
}
};
queue.add( postRequest );
}
Output from log:
04-29 11:42:24.556 1890-1946/? I/Icing: Indexing done F3642025687382E430F3465743F12480D56AAC66
04-29 11:43:32.123 3147-3196/? E/Volley: [157] BasicNetwork.
performRequest: Unexpected response code 415 for http://IP:5000/api/person
04-29 11:43:32.132 3147-3147/? D/Error.Response: com.android.volley.ServerError
04-29 11:45:19.365 1298-1311/? I/UsageStatsService: User[0] Flushing usage stats to disk

provide the right content type as follows
// Optional Parameters to pass as POST request
JSONObject js = new JSONObject();
try {
js.put("name","anything");
} catch (JSONException e) {
e.printStackTrace();
}
// Make request for JSONObject
JsonObjectRequest jsonObjReq = new JsonObjectRequest(
Request.Method.POST, url, js,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d(TAG, response.toString() + " i am queen");
}
}, 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>();
headers.put("Content-Type", "application/json; charset=utf-8");
return headers;
}
};
// Adding request to request queue
Volley.newRequestQueue(this).add(jsonObjReq);
}

415 is the error code for wrong media type. You are sending the body or your post request in plain text when the server expects json. Find out what type of content you should send and make the post body to that type.
#Override
public byte[] getBody() {
return 'your json string'.getBytes();
}
#Override
public String getBodyContentType() {
return "application/json; charset=utf-8";
}

if you are using Kotlin, here is the snippet I implemented
val jsonBody = JSONObject()
jsonBody.put("email", email)
jsonBody.put("password", password)
val requestBody = jsonBody.toString()
val registerRequest =
object : StringRequest(Method.POST, URL_REGISTER, Response.Listener { response ->
print(response)
complete(true)
}, Response.ErrorListener { error ->
Log.d("Error", "not possible to register at this time . $error")
complete(false)
}) {
override fun getBodyContentType(): String {
return "application/json; charset=utf-8";
}
override fun getBody(): ByteArray {
return requestBody.toByteArray()
}
}
Volley.newRequestQueue(context).add(registerRequest)
}

Related

Issue in Http PUT method using Asp.net WebAPI And Android Java

I want to update the "Pass" field using WebAPI, I have created an HTTP PUT Request using Asp.Net WEB API and Android Java with Volley.
through Postman it's updating field value but when I test through my App it's updating the blank value in DB.
Thanks in advance.
private void callPUTDataMethod(String name, String job) {
loadingPB.setVisibility(View.VISIBLE);
String url = URL;
RequestQueue queue = Volley.newRequestQueue(PassUpdt.this);
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.PUT, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
loadingPB.setVisibility(View.GONE);
jobEdt.setText("");
userNameEdt.setText("");
// on below line we are displaying a toast message as data updated.
Toast.makeText(PassUpdt.this, "Data Updated..", Toast.LENGTH_SHORT).show();
try {
JSONObject jsonObject = new JSONObject("Pass");
String output = "Password Updated";
responseTV.setText(output);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(PassUpdt.this, "Fail to update data..", Toast.LENGTH_SHORT).show();
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("EmpCd", "P010");
params.put("Pass", "12345");
params.put("Content-Type", "application/json; charset=utf-8");
return params;
}
};
queue.add(jsonObjectRequest);
}
}

put not working on android Volley org.json.JSONException: End of input at character 0 of

I sent request with postman its working, but volley doesn't work. I always get error! I searched stackoverflow volley returns error when response is empty but i added CustomJsonObjectRequest still the issue remains.
Error message
Volley org.json.JSONException: End of input at character 0 of
CustomJsonObjectRequest
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
protected Response<JSONObject> parseNetworkResponse(NetworkResponse response) {
try {
if (response.data.length == 0) {
byte[] responseData = "{}".getBytes("UTF8");
response = new NetworkResponse(response.statusCode, responseData, response.headers, response.notModified);
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return super.parseNetworkResponse(response);
}
}
Volley request
EcoElement ecoElement = ecoElementArrayList.get(position);
Map<String, String> params = new HashMap<String, String>();
params.put("Id", ecoElement.getId().toString());
params.put("Checked", ecoElement.getChecked().toString());
JSONObject ObjParams = new JSONObject(params);
try {
CustomJsonObjectRequest getRequest = new CustomJsonObjectRequest(Request.Method.PUT, "https://ourwebsite.sslbeta.de/api/gardenapi/updateecoelements", ObjParams,
response -> {
Toast.makeText(getContext(), ""+response, Toast.LENGTH_SHORT).show();
progressBar.setVisibility(View.GONE);
},
error -> {
Toast.makeText(getContext(), ""+error.toString(), Toast.LENGTH_SHORT).show();
progressBar.setVisibility(View.GONE);
}
);
RequestQueueSingleton.getInstance(getContext()).addToRequestQueue(getRequest);
} catch (Exception e) {
Toast.makeText(getContext(), e.toString(), Toast.LENGTH_LONG).show();
}
Finally i was able to fix the issues after hours of searching. There were two reasons to this, first is that api was returning null/empty so CustomJsonObjectRequest fixed that, and then another issue is that i forgot to add authentication headers. that was a silly mistake i know!
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<String, String>();
headers.put("Content-Type", "application/json");
headers.put("Authorization", "Bearer "+access_token);
return headers;
}
};
Here is the solution, just create this method and pass your value.
private void CustomJsonObjectRequest() {
String tag_string_req = "req__details";
StringRequest strReq = new StringRequest(Request.Method.POST, <API URL>, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
getPerspective().showErrorLogs(TAG, "Response Invest : " + response);
try {
// Parse your response here
} catch (Exception e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("Id", <ID VALUE HERE>);
params.put("Checked", <TRUE or FALSE>);
return params;
}
};
strReq.setRetryPolicy(new RetryPolicy() {
#Override
public void retry(VolleyError arg0) throws VolleyError {
}
#Override
public int getCurrentTimeout() {
return 0;
}
#Override
public int getCurrentRetryCount() {
return 0;
}
});
strReq.setShouldCache(false);
addToRequestQueue(strReq, tag_string_req);
}
Both ID and Checked must have String type.And create below methods in MainActivity:
private RequestQueue mRequestQueue;
public RequestQueue getRequestQueue() {
if (mRequestQueue == null) {
mRequestQueue = Volley.newRequestQueue(getApplicationContext());
}
return mRequestQueue;
}
public <T> void addToRequestQueue(Request<T> req, String tag) {
req.setTag(TextUtils.isEmpty(tag) ? TAG : tag);
getRequestQueue().add(req);
}
public <T> void addToRequestQueue(Request<T> req) {
req.setTag(TAG);
getRequestQueue().add(req);
}

JSON parse error in Spring rest controller taking post request from android volley

Getting following exception in Spring boot server:
JSON parse error: Unrecognized token was expecting ('true', 'false' or 'null'); nested exception is com.fasterxml.jackson.core.JsonParseException
while receiving POST request from Volley-android into Spring Rest Controller
public class RegistrationCredential {
#NotEmpty(message = "MacId is mandatory")
#JsonProperty("macId")
private String macId;
#NotEmpty(message = "Mobile number is mandatory")
#JsonProperty("mobileNo")
private String mobileNo;
....
}
Added #JsonProperty("name") tag in model
#PostMapping(consumes = {MediaType.APPLICATION_JSON_VALUE, MediaType.APPLICATION_XML_VALUE},
produces = {MediaType.APPLICATION_JSON_VALUE, MediaType.APPLICATION_XML_VALUE})
public ResponseEntity<String> vendorMobileRegistration(#Valid #RequestBody final RegistrationCredential credential) {}
Excerpt From Volley implemenettaion:
StringRequest stringRequest = new StringRequest(Request.Method.POST, SpotPollingURLs.REGISTRATION_URL, new Response.Listener <String>() {
#Override
public void onResponse(String response) {
System.out.println("Getting response frome url --- "+response);
try {
JSONObject jsonObject = new JSONObject(response);
String status = jsonObject.getString("status");
String messageCode = jsonObject.getString("MessageCode");
String message = jsonObject.getString("message");
if (status.equals("success") && messageCode.equals("MOBILE_REGISTERED_SUCCESSFULLY")) {
sendOTP(mobile, "send");
customDalog(mobile);
} else if (status.equals("success") && messageCode.equals("MOBILE_NUMBER_ALREADY_REGISTERED")) {
new CustomToast().showToast(getContext(), view, message);
} else if (status.equals("error")) {
new CustomToast().showToast(getContext(), view, message);
} else {
new CustomToast().showToast(getContext(), view, "Something went wrong check your connection");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
System.out.println("Getting error -- "+error);
progressBar.setVisibility(View.GONE);
}
}){
#Override
public Map <String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<>();
headers.put("Content-Type", "application/json");
return headers;
}
#Override
protected Map <String, String> getParams() throws AuthFailureError {
HashMap<String, String> params = new HashMap<>();
params.put("mobileNo", mobile);
params.put("macId", uniqueId);
return params;
}
};

Volley returns null on first call from method

I am trying to retrieve data from server using volley, but when I call this method the first time, I get the response from server, but null is returned by the method. If I call it the second time I get the last response.
public String retrieveDataFromServer(String url, String param, final String token){
StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try{
data = new JSONObject(response).toString();
}catch (Exception e){}
//Toast.makeText(getApplicationContext(), "wow" + data, Toast.LENGTH_SHORT).show();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
try{
data = new JSONObject(error.toString()).toString();
}catch (Exception e){}
//Toast.makeText(getApplicationContext(), "" +data, Toast.LENGTH_SHORT).show();
}
}) {
/**
* Passing some request headers
*/
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
String bearer = "Bearer ".concat(token);
Map<String, String> headersSys = super.getHeaders();
HashMap<String, String> headers = new HashMap<String, String>();
headers.put("Content-Type", "application/json; charset=utf-8");
//headers.put("token", token);
headersSys.remove("Authorization");
headers.put("Authorization", bearer);
headers.putAll(headersSys);
return headers;
}
};
// Adding request to request queue
addToRequestQueue(stringRequest);
//Toast.makeText(getApplicationContext(), "wow" + data, Toast.LENGTH_SHORT).show();
return data;
}
How do I get the response on first call of method?
You can use call back to return Volley response:
public void retrieveDataFromServer(final VolleyCallback callback) {
StringRequest strReq = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
callback.onSuccess(response);
}
}
}}
Create interface:
public interface VolleyCallback{
void onSuccess(String response);
}
And get result from activity:
String yourString = "";
#override
public void onResume() {
super.onResume();
retrieveDataFromServer(new VolleyCallback(){
#Override
public void onSuccess(String response){
//Get result from here
yourString = response;
}
});
}

Get Auth AcessToken from Paypal Android sdk

I have tried to get auth Access token using below code.and based on this code ,we will get Full transaction detail of Paypal.
Below code is working fine in Lollipop and above, but when we run my app in lolipop below version then not getting any response from Paypal SDK.I did lot of R&D for this issue.Please give me solution of this.
My Working Code in Lollipop and above:
public void getAcessToken(final String PayID) {
base64 = "Basic " + Base64.encodeToString((URLs.PAYPAL_CLIENTID + ":" + URLs.PAYPAL_SECRET_KEY).getBytes(), Base64.NO_WRAP);
Log.i("TAG", "Base64=" + base64);
if (!CM.isInternetAvailable(this)) {
CM.showPopupCommonValidation(this, getResources().getString(R.string.internet_unavailable_msg), false);
return;
}
showDialog();
String url = "https://api.sandbox.paypal.com/v1/oauth2/token";
Log.i("WebCalls", url);
StringRequest stringRequest = new StringRequest(Request.Method.POST,
url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
KcsLog.i("WebCalls", response.toString());
String AccessToken = CM.getValueFromJson("access_token", response);
String token_type = CM.getValueFromJson("token_type", response);
GetTransactionID(token_type + " " + AccessToken, PayID);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
dismissDialog();
CM.showVolleyErrorMessage(error, ViewGiftCode.this, "", false);
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> post = new HashMap<String, String>();
post.put("grant_type", "client_credentials");
return post;
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> post = new HashMap<String, String>();
post.put("Accept", "application/json");
post.put("Accept-Language", "en_US");
post.put("Content-Type", "application/x-www-form-urlencoded");
post.put("Authorization", base64);
return post;
}
};
((MainApplications) getApplicationContext()).volley.addToRequestQueue(stringRequest);
}
Please give me solution for below lollipop.

Categories

Resources