Send Basic Autherization in vollery request - android

Hello I am trying to send Basic Authorization in volley request. I tried this almost 7-8 months ago and it was working fine..
but I don't know what goes wrong now when I try to send request with authorization header and I always get 403 error. and when I tried to hit the url from hurl.it the it works fine.. can someone tell what is wrong with my request.
This is how I am adding Authorization header in volley request
public class VolleyRequest extends JsonObjectRequest {
String email, pass;
boolean saveCookeis;
public VolleyRequest(int method, String url, JSONObject jsonRequest,
Listener<JSONObject> listener, ErrorListener errorListener,
String email, String pass, boolean saveCookie) {
super(method, url, jsonRequest, listener, errorListener);
// TODO Auto-generated constructor stub
this.email = email;
this.pass = pass;
this.saveCookeis = saveCookie;
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
// TODO Auto-generated method stub
HashMap<String, String> params = new HashMap<String, String>();
String auth = "";
try {
auth = android.util.Base64.encodeToString(
(this.email + ":" + this.pass).getBytes("UTF-8"),
android.util.Base64.DEFAULT);
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
params.put("Authorization", auth);
return params;
}
#Override
protected Response<JSONObject> parseNetworkResponse(NetworkResponse response) {
// TODO Auto-generated method stub
if (saveCookeis) {
try {
String jsonString = new String(response.data,
HttpHeaderParser.parseCharset(response.headers));
ApplicationController.getInstance().checkSessionCookie(
response.headers);
return Response.success(new JSONObject(jsonString),
HttpHeaderParser.parseCacheHeaders(response));
} catch (UnsupportedEncodingException e) {
return Response.error(new ParseError(e));
} catch (JSONException je) {
return Response.error(new ParseError(je));
}
}
return super.parseNetworkResponse(response);
}
}
Screenshots From post man
Sample data can found here
Now this code is not working. Can anyone tell me what I am doing wrong. Thanks.

Try this:
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, URL, new JSONObject(), new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
//Handle response
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//Handle Error
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
return super.getParams();
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put(
"Authorization",
String.format("Basic %s", Base64.encodeToString(
String.format("%s:%s", username, password).getBytes(), Base64.DEFAULT)));
return params;
}
};
jsonObjectRequest.setShouldCache(false);
requestQueue.add(jsonObjectRequest);

Related

App crashing when load sql data with json from website

i have an app and my app connected to my website api.php . When activity open and start to load data with json from site, frame increase to 192+. After some seconds app crashing. There is my codes.
public void check_spinner() {
JsonRequest stringRequest = new JsonRequest(Request.Method.POST, Base_Url, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
// Toast.makeText(Spinner_Activity.this, response.toString(), Toast.LENGTH_SHORT).show();
if (response.getString("error").equalsIgnoreCase("false")) {
int daily = response.getInt("daily");
int left = response.getInt("left");
int leftt = daily-left;
spins.setText(leftt+" spin mövcuddur");
if (left>=daily)
{ spin_btn.setEnabled(false); }else { spin_btn.setEnabled(true); }
} else {
Toast.makeText(VideoActivity.this, response.getString("message"), Toast.LENGTH_SHORT).show();
}
} catch (Exception e) {
Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_SHORT).show();
}
}
},
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(ACCESS_KEY, ACCESS_Value);
params.put("usernamee", AppController.getInstance().getUsername());
params.put("spinner", "spinner");
return params;
}
};
AppController.getInstance().addToRequestQueue(stringRequest);
}
JsonRequest
public class JsonRequest extends Request<JSONObject> {
private Listener<JSONObject> listener;
private Map<String, String> params;
public JsonRequest(int method, String url, Map<String, String> params, Listener<JSONObject> reponseListener, ErrorListener errorListener) {
super(method, url, errorListener);
this.listener = reponseListener;
this.params = params;
}
protected Map<String, String> getParams()
throws com.android.volley.AuthFailureError {
return params;
};
#Override
protected Response<JSONObject> parseNetworkResponse(NetworkResponse response) {
try {
String jsonString = new String(response.data, HttpHeaderParser.parseCharset(response.headers));
return Response.success(new JSONObject(jsonString), HttpHeaderParser.parseCacheHeaders(response));
} catch (UnsupportedEncodingException e) {
return Response.error(new ParseError(e));
} catch (JSONException je) {
return Response.error(new ParseError(je));
}
}
#Override
protected void deliverResponse(JSONObject response) {
// TODO Auto-generated method stub
listener.onResponse(response);
}
}
I'm trying to replace json object with json array but i'm beginner and i can't do this. When i change it, getting errors.

Volley POST Request with headers and raw json body

I am trying to make Post request from Android App that takes username and password in request body with content-type application/json in headers.
I tried changing content-type and how i send username passoword in body, but still no luck
public class MainActivity extends AppCompatActivity {
private Button Login;
private EditText loginEmail, loginPassword;
String URL = "https://localhost:8080/api/v1/auth";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
loginEmail = (EditText)findViewById(R.id.etUsername);
loginPassword = (EditText)findViewById(R.id.etPassword);
Login = (Button)findViewById(R.id.btnLogin);
JSONObject jsonObject = new JSONObject();
try {
jsonObject.put("username", loginEmail.getText().toString());
} catch (JSONException e) {
e.printStackTrace();
}
try {
jsonObject.put("password", loginPassword.getText().toString());
} catch (JSONException e) {
e.printStackTrace();
}
final String requestBody = jsonObject.toString();
Login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
StringRequest request = new StringRequest(Request.Method.POST, URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Toast.makeText(MainActivity.this, response, Toast.LENGTH_LONG).show();
startActivity(new Intent(MainActivity.this, LandingPage.class));
finish();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(MainActivity.this, "Error", Toast.LENGTH_LONG).show();
NetworkResponse response = error.networkResponse;
if (error instanceof ServerError && response != null) {
try {
String res = new String(response.data,
HttpHeaderParser.parseCharset(response.headers, "utf-8"));
// Now you can use any deserializer to make sense of data
JSONObject obj = new JSONObject(res);
Toast.makeText(MainActivity.this, res, Toast.LENGTH_LONG).show();
Log.i("MainActivity", res);
//use this json as you want
} catch (UnsupportedEncodingException e1) {
// Couldn't properly decode data to string
e1.printStackTrace();
} catch (JSONException e2) {
// returned data is not JSONObject?
e2.printStackTrace();
}
}
}
})
{
#Override
public String getBodyContentType() {
return "application/json; charset=utf-8";
}
#Override
public byte[] getBody() throws AuthFailureError {
try {
return requestBody == null ? null : requestBody.getBytes("utf-8");
} catch (UnsupportedEncodingException uee) {
VolleyLog.wtf("Unsupported Encoding while trying to get the bytes of %s using %s", requestBody, "utf-8");
return null;
}
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("Content-Type", "application/json");
return params;
}
};
RequestQueue rQueue = Volley.newRequestQueue(MainActivity.this);
rQueue.add(request);
}
});
}
}
Post Request from Postman works perfectly fine but it throws Error 400 with Volley.
Below is the error I get in console
"errorSummary":"Bad request. Accept and/or Content-Type headers likely do not match supported values."
Try using a custom request and extending Request<JSONObject>:
CustomRequest class:
public class CustomRequest extends Request<JSONObject> {
private final Map<String, String> mHeaders;
private final JSONObject mBody;
private final Response.Listener<JSONObject> mResponseListener;
public CustomRequest(int method, String url, Map<String, String> headers, JSONObject body, Response.Listener<JSONObject> responseListener, Response.ErrorListener errorListener) {
super(method, url, errorListener);
this.mHeaders = headers;
this.mBody = body;
this.mResponseListener = responseListener;
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
return mHeaders != null ? mHeaders : super.getHeaders();
}
#Override
public String getBodyContentType() {
return "application/json; charset=UTF-8";
}
#Override
public byte[] getBody() throws AuthFailureError {
return mBody != null ? mBody.toString().getBytes(Charset.forName("UTF-8")) : super.getBody();
}
#Override
protected Response<JSONObject> parseNetworkResponse(NetworkResponse response) {
try {
String jsonString = new String(response.data, HttpHeaderParser.parseCharset(response.headers));
return Response.success(new JSONObject(jsonString), HttpHeaderParser.parseCacheHeaders(response));
} catch (UnsupportedEncodingException | JSONException e) {
return Response.error(new ParseError(e));
}
}
#Override
protected void deliverResponse(JSONObject response) {
mResponseListener.onResponse(response);
}
}
Usage:
String url = "https://localhost:8080/api/v1/auth";
Map<String, String> headers = new HashMap<>();
headers.put("Content-Type", "application/json");
JSONObject jsonObject = new JSONObject();
try {
jsonObject.put("username", loginEmail.getText().toString());
jsonObject.put("password", loginPassword.getText().toString());
} catch (JSONException e) {
e.printStackTrace();
}
CustomRequest customRequest = new CustomRequest(Request.Method.POST, url, headers, jsonObject, response -> {
// put your reponse listener code here
}, error -> {
// put your error listener code here
});
RequestQueue queue = Volley.newRequestQueue(context);
queue.add(customRequest);

Volley JsonObjectRequest with Basic Auth headers didn't work

I'm trying to send username and password as basic authorization with JsonObjectRequest. I've tried to Override getHeaders() method but it didn't work. Here is my code:
public class NewPostRequest extends JsonObjectRequest {
public NewPostRequest(JSONObject requestBody) {
super(Method.POST, APIConstants.CREATE_POST_URL, requestBody, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
long postId = response.getLong("id");
NewPostResponse newPostResponse = new NewPostResponse(postId);
EventBus.getDefault().post(newPostResponse);
} catch (JSONException e) {
e.printStackTrace();
EventBus.getDefault().post(new NewPostResponse(-1));
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
EventBus.getDefault().post(new NewPostResponse(-1));
}
});
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> headers = new HashMap<>();
String credentials = "****:***********************";
String auth = "Basic "
+ Base64.encodeToString(credentials.getBytes(), Base64.NO_WRAP);
headers.put("Content-Type", "application/json; charset=utf-8");
headers.put("Authorization", auth);
return headers;
}
#Override
protected Response<JSONObject> parseNetworkResponse(NetworkResponse response) {
JSONObject jsonObject = null;
try {
String data = new String(response.data,
HttpHeaderParser.parseCharset(response.headers));
jsonObject = new JSONObject(data);
} catch (UnsupportedEncodingException | JSONException e) {
e.printStackTrace();
}
return Response.success(jsonObject, HttpHeaderParser.parseCacheHeaders(response));
}
}
Error when i used Base64.NO_WRAP:
com.android.volley.AuthFailureError
And when i used Base64.DEFAULT:
java.lang.IllegalArgumentException: Unexpected char 0x0a at 46 in header value: Basic *************************
Note: This web service is working on Google Postman tool.
Check my answer its working fine for me.
Check this one

Basic Authentication not working in Volley in android

I am using volley library but when I use basic authentication then I do not got any response and also volley is not showing any error. I am also try HttpUrlConnection with Asyntask but I face same problem. Please provide solution this problem.
I also hit my api via Postman client, ARC and my api is working fine with these client.
MyJsonObjectRequest.java
public class MyJsonObjectRequest extends JsonRequest<JSONObject> {
private Priority priority = null;
//private Map<String, String> headers = new HashMap<String, String>();
public MyJsonObjectRequest(int method, String url, JSONObject jsonRequest, Listener<JSONObject> listener, ErrorListener errorListener) {
super(method, url, (jsonRequest == null) ? null : jsonRequest.toString(), listener, errorListener);
}
public MyJsonObjectRequest(String url, JSONObject jsonRequest, Listener<JSONObject> listener,
ErrorListener errorListener) {
this(jsonRequest == null ? Method.GET : Method.POST, url, jsonRequest,
listener, errorListener);
}
#Override
public Priority getPriority() {
if (this.priority != null) {
return priority;
} else {
return Priority.NORMAL;
}
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
//Log.e("JSON"," AUTH CODE "+createBasicAuthHeader("MaS", "123456"));
return createBasicAuthHeader("username", "123456");
}
Map<String, String> createBasicAuthHeader(String username, String password) {
Map<String, String> headerMap = new HashMap<String, String>();
String credentials = username + ":" + password;
String encodedCredentials = Base64.encodeToString(credentials.getBytes(), Base64.NO_WRAP);
headerMap.put("Content-Type", "application/json; charset=utf-8");
headerMap.put("Authorization", "Basic " + encodedCredentials);
return headerMap;
}
public void setHeader(String title, String content) {
// headers.put(title, content);
}
public void setPriority(Priority priority) {
this.priority = priority;
}
#Override
protected Response<JSONObject> parseNetworkResponse(NetworkResponse response) {
try {
String jsonString = new String(response.data, HttpHeaderParser.parseCharset(response.headers));
return Response.success(new JSONObject(jsonString),HttpHeaderParser.parseCacheHeaders(response));
} catch (UnsupportedEncodingException e) {
return Response.error(new ParseError(e));
} catch (JSONException je) {
return Response.error(new ParseError(je));
}
}
#Override
protected VolleyError parseNetworkError(VolleyError volleyError){
NetworkResponse response = volleyError.networkResponse;
if (response!=null)
{
Log.e("TAG"," VOLLEY ERROR1 "+response.statusCode);
}
if(volleyError.networkResponse != null && volleyError.networkResponse.data != null){
VolleyError error = new VolleyError(new String(volleyError.networkResponse.data));
Log.e("TAG"," VOLLEY ERROR "+error.toString());
volleyError = error;
}
return volleyError;
}
}
My MainActvity
public class JsonObjectActivity extends AppCompatActivity {
JsonObjectRequest gsonRequest;
private TextView textView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_json_object);
textView = (TextView) findViewById(R.id.tv2);
try {
doingProcessJsonArray();
} catch (JSONException e) {
e.printStackTrace();
}
}
public void doingProcessJsonArray() throws JSONException {
// i am use local server like
String newUrl="http://myserver:8023/Users.svc/password_encrypt";
JSONObject params = new JSONObject();
params.put("PASSWORD", "12345655");
//params.put("domain", "http://samset.info");
gsonRequest =new JsonObjectRequest(Request.Method.POST,newUrl, params, successListener(), errorListener());
Constants.showProgressDialog(this, "Loading..");
//gsonRequest.setRetryPolicy(new DefaultRetryPolicy(6000,DefaultRetryPolicy.DEFAULT_MAX_RETRIES,DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
// Start progressbar
// gsonRequest.setPriority(Request.Priority.IMMEDIATE);
Log.e("TAG"," request "+gsonRequest.toString());
VolleySingleton.getInstance(this).addToRequestQueue(gsonRequest, "volleyrequest");
}
private Response.ErrorListener errorListener() {
return new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("Volley","Error "+error.toString());
}
};
}
public Response.Listener successListener()
{
return new Response.Listener<JSONObject>()
{
#Override
public void onResponse(JSONObject response) {
Constants.dismissDialog();
Log.e("Volley","Responce "+response.toString());
textView.setText("JSONObject RESPONCE > "+response.toString());
}
};
}
}
postman screen shot

Getting 500 error for Volley PUT request android

CustomRequest.java
public class CustomRequest extends Request<JSONObject> {
private Listener<JSONObject> listener;
private Map<String, String> params;
private Map<String, String> headers;
public CustomRequest(String url,
Map<String, String> params,
Map<String, String> headers,
Listener<JSONObject> reponseListener,
ErrorListener errorListener) {
super(Method.GET, url, errorListener);
this.listener = reponseListener;
this.params = params;
this.headers = headers;
}
public CustomRequest(int method,
String url,
Map<String, String> params,
Map<String, String> headers,
Listener<JSONObject> reponseListener,
ErrorListener errorListener) {
super(method, url, errorListener);
this.listener = reponseListener;
this.params = params;
this.headers = headers;
}
protected Map<String, String> getParams()
throws com.android.volley.AuthFailureError {
return params;
};
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
return headers != null ? headers : super.getHeaders();
}
#Override
protected Response<JSONObject> parseNetworkResponse(NetworkResponse response) {
try {
String jsonString = new String(response.data,
HttpHeaderParser.parseCharset(response.headers));
return Response.success(new JSONObject(jsonString),
HttpHeaderParser.parseCacheHeaders(response));
} catch (UnsupportedEncodingException e) {
return Response.error(new ParseError(e));
} catch (JSONException je) {
return Response.error(new ParseError(je));
}
}
#Override
protected void deliverResponse(JSONObject response) {
// TODO Auto-generated method stub
listener.onResponse(response);
}
I am using request like this in my class:
Map<String, String> params = new HashMap<>();
Map<String, String> headers = new HashMap<String, String>();
headers.put("Content-Type", "application/json");
Iterator it = params.entrySet().iterator();
while (it.hasNext()) {
Map.Entry pairs = (Map.Entry) it.next();
Log.d(context.getClass().getCanonicalName(), "params - " + pairs.getKey() + ", " + pairs.getValue());
}
String url = AppConstants.SERVER_URL + mApi + "/" + mType+ "/" +mWord.getID();
Log.d("FinalUrl:->", url);
RequestQueue requestQueue = Volley.newRequestQueue(ActDrawAreaTwo.this);
CustomRequest jsObjRequest = new CustomRequest(Request.Method.PUT,
url,
params,
headers,
this.createRequestSuccessListener(),
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
progress.dismiss();
}
});
RequestQueueHelper.addToRequestQueue(jsObjRequest, "");
I am getting error:
11-22 10:28:01.605 17921-18491/com.app.admin E/Volley: [3516] BasicNetwork.performRequest: Unexpected response code 500
Its a put request, its working in postman
According to your Postman screenshot, I suggest you use the following sample code:
String url = "http://...";
JSONObject jsonBody;
try {
jsonBody = new JSONObject();
jsonBody.put("ID", 1);
jsonBody.put("Name", "Word1");
jsonBody.put("ArabicName", "Arabic Word1");
// other key-value pairs...
JsonObjectRequest request = new JsonObjectRequest(Request.Method.PUT, url, jsonBody, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
// do something
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// do something
}
});
queue.add(request);
} catch (JSONException e) {
e.printStackTrace();
}
Hope this helps!

Categories

Resources