400 Error when calling Sinch REST API - android

I am using Sinch to create an app in android and some of the functionalities that I need can only be implemented by calling their REST API. I want to mute a particular user, for that I have written the code like this
String userName = call.getCallId();
final String muteURL = URL+CallingUsersName+"/"+userName;
final String muteParticipant = "{ \"command\" : \"mute\" }";
JSONObject muteJSON;
try{
muteJSON = new JSONObject(muteParticipant);
Toast.makeText(getActivity(),muteJSON.toString(),Toast.LENGTH_SHORT).show();
}catch (JSONException e ) {
muteJSON = null;
Toast.makeText(getActivity(), e.toString(), Toast.LENGTH_SHORT).show();
}
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.PATCH, muteURL, muteJSON, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
mConferenceParticipants.setText(response.toString());
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
mConferenceParticipants.setText(error.toString());
}
}){
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> params = new HashMap<String, String>();
String creds = String.format("%s:%s",AppKey,AppSecretKey);
String auth = "Basic " + Base64.encodeToString(creds.getBytes(), Base64.NO_WRAP);
params.put("Authorization", auth);
params.put("Content-Type", "application/json");
// params.put("X-HTTP-Method-Override", "PATCH");
return params;
// return super.getHeaders();
}
};
// jsonObjectRequest.setRetryPolicy(new DefaultRetryPolicy(8000,DefaultRetryPolicy.DEFAULT_MAX_RETRIES,DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
rq.add(jsonObjectRequest);
When I call this request the meeting is actually going on but I am getting this error
BasicNetwork.performRequest: Unexpected response code 400 for https://callingapi.sinch.com/v1/conferences/id/Meeting/a291ba94-e430-454f-80a9-73013cd43451
I believe that 400 means Conference not found but the conference is established and in the same activity I am also calling the REST API that will tell me the no. of participants in the meeting and that is working correctly.
Any idea what is wrong in this?

I tried to solve this problem for a long time and finally got it working. Here is the code:
public void MuteTheParticipants(){
String userName = call.getCallId();
final String muteURL = URL+CallingUsersName+"/"+userName;
StringRequest sr = new StringRequest(Request.Method.PATCH, muteURL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
if(flag)
muteButton.setBackgroundResource(R.drawable.microphone);
else
muteButton.setBackgroundResource(R.drawable.microphone_off
);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getActivity(),error.toString(),Toast.LENGTH_SHORT).show();
}
}){
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> params = new HashMap<String, String>();
String creds = String.format("%s:%s",AppKey,AppSecretKey);
String auth = "Basic " + Base64.encodeToString(creds.getBytes(), Base64.NO_WRAP);
params.put("Authorization", auth);
return params;
// return super.getHeaders();
}
#Override
protected Map<String, String> getParams() throws AuthFailureError {
HashMap<String, String> params = new HashMap<String, String>();
if(!flag) {
params.put("command", "mute");
flag = true;
}else {
params.put("command", "unmute");
flag = false;
}
return params;
}
};
sr.setRetryPolicy(new DefaultRetryPolicy(8000,DefaultRetryPolicy.DEFAULT_MAX_RETRIES,DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
rq.add(sr);
}

your variable says username, it should be callid you mute not username

Related

Nested VOLLEY GET Request Method not giving correct results

I have two nested VOLLEY GET request. The first API request gives me id field which I am using to called another Web Service. The problem is the way I am getting the sequence of id from first request its not calling the same sequence for second request which uses id field return by first request.
This is my nested VOLLEY GET request.
private void getData() {
final JsonArrayRequest request = new JsonArrayRequest(Request.Method.GET, ApiUrls.RESERVATION, null, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
for (int i = 0; i < response.length(); i++) {
try {
JSONObject object = response.getJSONObject(i);
final Entry entry = newEntry();
String Id = object.getString("id");
entry.setId(Id);
ID_url = ApiUrls.DETAILS + Id + "/";
JsonObjectRequest foodieInfo = new JsonObjectRequest(Request.Method.GET, ID_url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
String firstName = response.getString("firstname");
entry.setName(firstName);
adapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> headers = new HashMap<>();
String auth = "JWT " + myToken;
headers.put("Authorization", auth);
headers.put("Content-Type", "application/json");
return headers;
}
};
AppController.getInstance().addToRequestQueue(foodieInfo);
current.add(entry);
adapter = new ReservationAdapter(current, getActivity().getApplicationContext());
recyclerView.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> headers = new HashMap<>();
String auth = "JWT " + myToken;
headers.put("Authorization", auth);
headers.put("Content-Type", "application/json");
return headers;
}
#Override
protected Response<JSONArray> parseNetworkResponse(NetworkResponse response) {
int status=response.statusCode;
if(status==200){
}
return super.parseNetworkResponse(response);
}
};
AppController.getInstance().addToRequestQueue(request);
}
The id which I get in first request same it should be only used in the Nested JSON GET request. But it take different id returned by first request and called the another request from using that sequence. How to resolve this ?

How to debug "Your User ID is invalid. Kindly use a valid API Key and User ID combination" in Android?

I am new to Android, I am getting this in my logcat:
"status":false,"msg":"Your User ID is invalid. Kindly use a valid API Key and User ID combination"
Code:
public class MainActivity extends AppCompatActivity {
String url = "https://json.astrologyapi.com/v1/monthly_panchang";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
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", error.toString());
}
}
){
#Override
protected Map<String,String> getParams(){
Map<String,String> params = new HashMap<String, String>();
params.put("Content-Type","application/x-www-form-urlencoded");
params.put("username","602845");
params.put("password","dea8c55922286904e4c34757ed1fcf09");
return params;
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String,String> params = new HashMap<String, String>();
params.put("Authorization", "Token <token>");
return params;
}
};
RequestQueue requestQueue= Volley.newRequestQueue(this);
requestQueue.add(postRequest);
}
}
You need to put your API auth token here:
params.put("Authorization", "Token <token>");
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> headers = new HashMap<>();
headers.put("Username", "602826");
headers.put("Password", "cb");
String credentials = "602826" + ":" + "cb";
String auth = "Basic "
+ Base64.encodeToString(credentials.getBytes(),
Base64.NO_WRAP);
headers.put("Authorization", auth);
// headers.put("Content-Type", "application/json");
return headers;
}
i have solved my problem.

WebAPI call using volley

I'm trying to get access tokens from the server using a volley String request. I have tried making a JsonObjectRequest also. Both are below.
public void getAuthenticationTokens(Object param1, final CustomListener<String> listener)
{
//String url = prefixURL + "this/request/suffix";
String url = "https://lw.xxx.co.uk/connect/token";
StringRequest request = new StringRequest(Request.Method.POST, url,
new Response.Listener<String>()
{
#Override
public void onResponse(String response) {
// response
Log.e("Response", response);
}
},
new Response.ErrorListener()
{
#Override
public void onErrorResponse(VolleyError error) {
// error
Log.e("Error.Response", error.networkResponse.toString());
}
}
) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String,String> params = new HashMap<>();
params.put("Content-Type","application/x-www-form-urlencoded");
//..add other headers
return params;
}
#Override
protected Map<String, String> getParams()
{
Map<String, String> params = new HashMap<String, String> ();
params.put("scope", "openid email phone profile offline_access roles");
params.put("resource", "window.location.origin");
params.put("grant_type", "password");
params.put("username", "support#xxx.com");
params.put("password", "tempPxxx");
return params;
}
};
requestQueue.add(request);
.
public void getAuthenticationTokens(Object param1, final CustomListener<String> listener)
{
//String url = prefixURL + "this/request/suffix";
String url = "https://lw.xxx.co.uk/connect/token";
Map<String, Object> jsonParams = new HashMap<>();
jsonParams.put("scope", "openid email phone profile offline_access roles");
jsonParams.put("resource", "window.location.origin");
jsonParams.put("grant_type", "password");
jsonParams.put("username", "support#xxx.com");
jsonParams.put("password", "tempPxxx");
JsonObjectRequest request = new JsonObjectRequest(Request.Method.POST, url, new JSONObject(jsonParams),
new Response.Listener<JSONObject>()
{
#Override
public void onResponse(JSONObject response)
{
Log.d(TAG + ": ", "somePostRequest Response : " + response.toString());
if(null != response.toString())
listener.getResult(response);
}
},
new Response.ErrorListener()
{
#Override
public void onErrorResponse(VolleyError error)
{
if (null != error.networkResponse)
{
Log.e(TAG + ": ", "Error Response code: " + error.networkResponse.statusCode);
listener.getResult(null);
}
}
}){
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
// Map<String,String> params = super.getHeaders();
// if(params==null)params = new HashMap<>();
Map<String,String> params = new HashMap<>();
params.put("Content-Type","application/x-www-form-urlencoded");
//..add other headers
return params;
}
};
requestQueue.add(request);
.
I get the following response from the server:
E/Volley: [31388] BasicNetwork.performRequest: Unexpected response code 400 for https://lw.xxx.co.uk/connect/token
.
My colleague who has written the server-side code has asked how to convert the following Angular code (his code that works with the API), to Android.
Can anyone help with this?
getLoginEndpoint(userName: string, password: string): Observable<Response> {
let header = new Headers();
header.append("Content-Type", "application/x-www-form-urlencoded");
let searchParams = new URLSearchParams();
searchParams.append('username', userName);
searchParams.append('password', password);
searchParams.append('grant_type', 'password');
searchParams.append('scope', 'openid email phone profile offline_access roles');
searchParams.append('resource', window.location.origin);
let requestBody = searchParams.toString();
return this.http.post(this.loginUrl, requestBody, { headers: header });
}
The problem was a couple of things.
I replaced "params.put("resource", "window.location.origin"); " with "params.put("resource", "https://lw.xxx.co.uk");"
Also, I found out that Volley ignore the getHeaders override, so I commented that method out and used the following to set the headers.
#Override
public String getBodyContentType() {
return "application/x-www-form-urlencoded";
}
public void getAuthenticationTokens(Object param1, final String userName, final String password, final CustomListener<JSONObject> listener)
{
String url = "https://lw.xxx.co.uk/connect/token";
StringRequest request = new StringRequest(Request.Method.POST, url,
new Response.Listener<String>()
{
#Override
public void onResponse(String response) {
// response
Log.e("Response", response);
}
},
new Response.ErrorListener()
{
#Override
public void onErrorResponse(VolleyError error) {
// error
Log.e("Error.Response", error.networkResponse.toString());
}
}
) {
/* #Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String,String> params = new HashMap<>();
params.put("Content-Type","application/x-www-form-urlencoded");
//..add other headers
return params;
}*/
#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("scope", "openid email phone profile offline_access roles");
params.put("resource", "https://lw.xxx.co.uk");
params.put("grant_type", "password");
params.put("username", userName);
params.put("password", password);
return params;
}
#Override
protected VolleyError parseNetworkError(VolleyError response) {
try {
String json = new String(response.networkResponse.data, HttpHeaderParser.parseCharset(response.networkResponse.headers));
Log.e(TAG, "reponse error = " + json);
}catch (Exception e){}
return super.parseNetworkError(response);
}
};
requestQueue.add(request);
}//end of getAuthenticationTokens

Volley return 403 error

From two days i am trying to solve this issue but still i have no any result,why each and every time volley returning me 403 error. where i m wrong? i am using postman to check same webservice, it returns success result. But same thing when i am using in Android via volley or httpurlconnection getting 403 error.kindly help me to find my error.
This is my code which i have tried:
StringRequest jsonObjectRequest = new StringRequest(Request.Method.POST, Constant.posturl, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
String result=response;
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
NetworkResponse response = error.networkResponse;
int status = response.statusCode;
}
}) {
#Override
public Map<String, String> getHeaders() {
try {
headers = new HashMap<String, String>();
headers.put("Content-Type", "application/json");
String credentials = Constant.USERNAME + ":" + Constant.PASSWORD;
String auth = "Basic " + Base64.encodeToString(credentials.getBytes(), Base64.DEFAULT);
headers.put("Authorization", auth);
return headers;
} catch (Exception e) {
e.printStackTrace();
return headers;
}
}
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("title", heading_edit_text.getText().toString());
params.put("content", body_edit_text.getText().toString());
params.put("Slug", heading_edit_text.getText().toString());
params.put("date", currentDate);
return params;
}
};
jsonObjectRequest.setRetryPolicy(new DefaultRetryPolicy(50000, 3, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
requestQueue.add(jsonObjectRequest);
Volley does provide a proper request for this which is called JsonObjectRequest.
String webAddress = "url here";
RequestQueue queue = Volley.newRequestQueue(this); // singletone here
JSONObject object = new JSONObject();
try {
object.put("title", heading_edit_text.getText().toString());
object.put("content", body_edit_text.getText().toString());
object.put("Slug", heading_edit_text.getText().toString());
object.put("date", currentDate);
} catch (JSONException e) {
}
JsonObjectRequest request = new JsonObjectRequest(Request.Method.POST, webAddress,object, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject object) {
Log.d("RESPONSE", object.toString());
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
Log.d("RESPONSE", "That didn't work!");
}
}) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> header = new HashMap<>();
// content type is not needed here
header.put("Authorization", "value here");
return header;
}
};
queue.add(request);
Change the "Content-Type" of your headers to "application/form-data"
ie,
headers.put("Content-Type", "application/form-data");
I was also face this issue in news api. But when I use Retrfit its work like a charm.

Not able to post params in form url-encoded through volley in android

I am trying hit an api(written in PHP) and posting params with it.
Here is my code:
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.POST,
url, null,
new com.android.volley.Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
System.out.println("prerna succes volley "+response.toString());
}
}, new com.android.volley.Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
System.out.println("prerna fail volley "+error.toString());
}
})
{
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> pars = new HashMap<String, String>();
pars.put("Content-Type", "application/x-www-form-urlencoded");
return pars;
}
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("action", "login");
params.put("username", "abc#xyz.com");
params.put("pass", "a");
return params;
}
};
I always get invalid username/password which has been handled in api in case there is invalid username and password.In this case api is not receiving the params.
I tried to do it with retrofit and its working fine with it that means there is no problem at API coding. What am I missing here in case of volley?
Thanks for the support. I am able to solve the problem by changing JsonObjectRequest to StringRequest. i found Volley JsonObjectRequest Post parameters no longer work where I got to know that JsonObjectRequest creates some unexpected problems.
There is my code:
StringRequest jsonObjReq = new StringRequest(Request.Method.POST,
url,
new com.android.volley.Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonObject = new JSONObject(response.toString());
String no = jsonObject.getString("$PhoneNo");
} catch (JSONException e) {
}
}
}, new com.android.volley.Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
System.out.println("prerna fail volley " + error.toString());
}
})
{
#Override
public String getBodyContentType() {
Map<String, String> pars = new HashMap<String, String>();
pars.put("Content-Type", "application/x-www-form-urlencoded");
//return pars;
return "application/x-www-form-urlencoded";
}
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("action", "login");
params.put("username", "abc#xyz.com");
params.put("pass", "a");
return params;
}
};
However I am still trying to figure out why JsonobjectRequest did not work.
As far as I can tell by looking at JsonObjectRequest your 3rd parameter is null, and it indicates the JsonObject request - by the documentation "jsonRequest - A JSONObject to post with the request. Null is allowed and indicates no parameters will be posted along with request."
And after searching again, I saw this thread.
if you are sending your data in raw format you need to try this,first of all make json of your data to be post.
final JSONObject jsonBody = new JSONObject();
jsonBody.put("mobile", phoneNumber);
jsonBody.put("otp", otp.trim());
and you have to override these methods
#Override
public byte[] getBody() throws AuthFailureError {
return jsonBody.toString().getBytes();
}
#Override
public String getBodyContentType() {
return "application/json";
}
if you also have header in your post request you also send that with by following type
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
String auth_token = "bearer" + prefs.getPreferencesString(context, "AuthToken").toString();
params.put("Authorization", auth_token);
return params;
}
Here is the whole code.
final JSONObject jsonBody = new JSONObject();
jsonBody.put("mobile", phoneNumber);
jsonBody.put("otp", otp.trim());
StringRequest sr = new StringRequest(Request.Method.POST, Constraints.Base_URL + "/api/v1/verifyotp", new com.android.volley.Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
progressDialog.dismiss();
JSONObject jsonObject = new JSONObject(response);
int status = jsonObject.getInt("status");
String token = jsonObject.getString("token");
prefs.setPreferencesString(OtpActivity.this, "AuthToken", token);
if (status == 1) {
startActivity(new Intent(getApplicationContext(), WelcomeScreenActivity.class));
overridePendingTransition(R.anim.right_in, R.anim.left_out);
} else if (status == 0) {
Toast.makeText(OtpActivity.this, "Please Enter Otp!", Toast.LENGTH_SHORT).show();
}
} catch (Exception e) {
}
}
}, new com.android.volley.Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(OtpActivity.this, "Invalid otp please try again!!", Toast.LENGTH_SHORT).show();
progressDialog.dismiss();
}
}) {
#Override
public byte[] getBody() throws AuthFailureError {
return jsonBody.toString().getBytes();
}
#Override
public String getBodyContentType() {
return "application/json";
}
};
MyApplication.getInstance().addToReqQueue(sr, "jreq");
}
} catch (Exception e) {
}
Try migrating to getHeaders and remove getParams
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("action", "login");
params.put("username", "abc#xyz.com");
params.put("pass", "a");
return pars;
}
Or - Reuse the getParams method
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> params = getParams();
params.put("Content-Type", "application/x-www-form-urlencoded");
return params;
}
If it is a body request all you need to do is add the extra parameter.
JSONObject body = new JSONObject();
body.put("action", "login");
body.put("username", "abc#xyz.com");
body.put("pass", "a");
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.POST,
url, body,
new com.android.volley.Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
System.out.println("prerna succes volley "+response.toString());
}
},
new com.android.volley.Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
System.out.println("prerna fail volley "+error.toString());
}
});

Categories

Resources