I try to open a new activity on a onResponse of Volley. But I have no idea of what parameters I can use.
Indeed my Volley request is on another class and, I think I need to pass the context of my first class on the second. But I have no idea of how I can do.
public class ConnexionActivity extends Activity{
EditText textlogin;
EditText textpassword;
Button btnConnexion;
String login;
String password;
private AllRequest req;
private PrefManager pref;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.connexion);
this.req = new AllRequest(getApplicationContext());
this.pref = new PrefManager(getApplicationContext());
textlogin = (EditText) findViewById(R.id.editText_login_connexion);
textpassword = (EditText) findViewById(R.id.editText_mdp_connexion);
btnConnexion = (Button) findViewById(R.id.btn_Connexion);
btnConnexion.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
login = textlogin.getText().toString();
password = textpassword.getText().toString();
req.TokenRequest(login, password);
}
});
}
}
And that is a part of my function that do the request Volley:
public void TokenRequest(final String login, final String password){
final StringRequest stringRequest = new StringRequest(com.android.volley.Request.Method.POST, ressources.urlToken,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.e("onResponse", response);
pref = new PrefManager(context);
pref.storeIsConnect(true);
try{
JSONObject rep = new JSONObject(response);
//stockage des données
pref.storeScope(rep.getString("scope"));
pref.storeTokenType(rep.getString("token_type"));
pref.storeAccessToken(rep.getString("access_token"));
pref.storeRefreshToken(rep.getString("refresh_token"));
pref.storeExpiresIn(rep.getString("expires_in"));
}catch (JSONException e) {
e.printStackTrace();
Log.e("erreurJSON", e.getMessage());
}
//I don't know how do this part
Intent intent = new Intent(ConnexionActivity.getContext(), listMirorActivity.class);
startActivity(intent);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("onErrorResponse", error.toString());
}
}){
#Override
public Map<String, String> getParams() throws AuthFailureError {
HashMap<String, String> params = new HashMap<String, String>();
params.put("grant_type", "password");
params.put("username", login);
params.put("password", password);
return params;
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String,String> headers = new HashMap<String, String>();
// add headers <key,value>
String credentials = ressources.client_id + ":" + ressources.client_secret;
String auth = "Basic "
+ Base64.encodeToString(credentials.getBytes(),
Base64.NO_WRAP);
headers.put("Authorization", auth);
return headers;
}
};
queue.add(stringRequest);
}
public void TokenRequest(final Context context,final String login, final String password){
final StringRequest stringRequest = new StringRequest(com.android.volley.Request.Method.POST, ressources.urlToken,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.e("onResponse", response);
pref = new PrefManager(context);
pref.storeIsConnect(true);
try{
JSONObject rep = new JSONObject(response);
//stockage des données
pref.storeScope(rep.getString("scope"));
pref.storeTokenType(rep.getString("token_type"));
pref.storeAccessToken(rep.getString("access_token"));
pref.storeRefreshToken(rep.getString("refresh_token"));
pref.storeExpiresIn(rep.getString("expires_in"));
}catch (JSONException e) {
e.printStackTrace();
Log.e("erreurJSON", e.getMessage());
}
//I don't know how do this part
Intent intent = new Intent(context, listMirorActivity.class);
startActivity(intent);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("onErrorResponse", error.toString());
}
}){
#Override
public Map<String, String> getParams() throws AuthFailureError {
HashMap<String, String> params = new HashMap<String, String>();
params.put("grant_type", "password");
params.put("username", login);
params.put("password", password);
return params;
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String,String> headers = new HashMap<String, String>();
// add headers <key,value>
String credentials = ressources.client_id + ":" + ressources.client_secret;
String auth = "Basic "
+ Base64.encodeToString(credentials.getBytes(),
Base64.NO_WRAP);
headers.put("Authorization", auth);
return headers;
}
};
queue.add(stringRequest);
}
and in your activity change req.TokenRequest(login, password);
with req.TokenRequest(ConnexionActivity.this,login, password);
You can also create a Context variable Context context;
and then initialized it when OnCreate() is called
context=this;
So the, when the intent is being made, do this
Intent intent = new Intent(context, listMirorActivity.class);
startActivity(intent);
Related
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.
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
I am using POST method and trying to Send Object as data using Android Volley Library to change the Current Password to New One but I am not Able to do it.
SettingFragment
public class SettingFragment extends Fragment implements View.OnClickListener {
EditText userName, oldPassword, newPassword;
String Navigation_URL_SettingRequest = "http://192.168.100.5:84/api/usersApi/updateByMasterID";
String username, oldpassword, newpassword;
String master_id, Name, access_token;
Button save, reset;
public static final String KEY_Name = "NAME";
public static final String KEY_USERNAME = "UserName";
public static final String KEY_OldPASSWORD = "oldPassword";
public static final String KEY_UserPassword = "UserPassword";
public static final String KEY_MasterID = "MasterID";
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_setting, container, false);
setHasOptionsMenu(true);
userName = (EditText) view.findViewById(R.id.setting_username);
oldPassword = (EditText) view.findViewById(R.id.setting_oldpassword);
newPassword = (EditText) view.findViewById(R.id.setting_newpassword);
save = (Button) view.findViewById(R.id.setting_save);
reset = (Button) view.findViewById(R.id.setting_reset);
SessionManagement session = new SessionManagement(getContext());
session.checkLogin();
access_token = session.getAccesstToken();
master_id = session.getMasterId1();
System.out.println(master_id);
Name = session.getKeyName();
save.setOnClickListener(this);
return view;
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
// TODO Auto-generated method stub
super.onCreateOptionsMenu(menu, inflater);
inflater.inflate(R.menu.dashboard, menu);
}
private void makeJsonSettingRequest() throws JSONException {
username = userName.getText().toString().trim();
oldpassword = oldPassword.getText().toString().trim();
newpassword = newPassword.getText().toString().trim();
/*
// JSONObject js = new JSONObject();
try {
RequestQueue requestQueue = Volley.newRequestQueue(getActivity());
String URL = "http://192.168.100.5:84/api/usersApi/updateByMasterID";
JSONObject jsonBody = new JSONObject();
jsonBody.put(KEY_USERNAME, username);
jsonBody.put(KEY_OldPASSWORD, oldpassword);
jsonBody.put(KEY_UserPassword, newpassword);
jsonBody.put(KEY_MasterID, master_id);
jsonBody.put(KEY_Name, Name);
final String requestBody = jsonBody.toString();
StringRequest stringRequest = new StringRequest(Request.Method.POST, URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.i("VOLLEY", response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("VOLLEY", error.toString());
// error.getMessage();
}
}) {
#Override
public String getBodyContentType() {
return "Content-Type;application/x-www-form-urlencoded";
}
#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
protected Response<String> parseNetworkResponse(NetworkResponse response) {
String responseString = "";
if (response != null) {
responseString = String.valueOf(response.statusCode);
// can get more details such as response.headers
}
return Response.success(responseString, HttpHeaderParser.parseCacheHeaders(response));
}
};
requestQueue.add(stringRequest);
} catch (JSONException e) {
e.printStackTrace();
}
*/
// JSONObject params = new JSONObject();
// params.put(KEY_Name, Name);
// params.put(KEY_MasterID, master_id);
// params.put(KEY_USERNAME, username);
// params.put(KEY_OldPASSWORD, oldpassword);
// params.put(KEY_UserPassword, newpassword);
StringRequest stringRequest = new StringRequest(Request.Method.POST, Navigation_URL_SettingRequest,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.i("VOLLEY", response);
// VolleyLog.v("Response:%n %s", response.toString(4));
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
System.out.println("This is an Error mate");
}
}) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> headers = new HashMap<String, String>();
// headers.put("Authorization", "Bearer " + access_token);
// headers.put("Authorization", access_token);
// headers.put("Content-Type", "application/x-www-form-urlencoded");
// headers.put("Content-Type", "application/json");
// headers.put(KEY_Name, Name);
// headers.put(KEY_MasterID, master_id);
// headers.put(KEY_USERNAME, username);
// headers.put(KEY_OldPASSWORD, oldpassword);
// headers.put(KEY_UserPassword, newpassword);
return headers;
}
#Override
protected Map<String, String> getParams() {
Map<String, String> map = new HashMap<String, String>();
//JSONObject content = new JSONObject();
try {
map.put(KEY_USERNAME, username);
map.put(KEY_OldPASSWORD, oldpassword);
map.put(KEY_UserPassword, newpassword);
map.put(KEY_MasterID, master_id);
map.put(KEY_Name, Name);
Log.d("Success", map.put(KEY_USERNAME, username));
} catch (Exception e) {
e.printStackTrace();
}
//map.put("access_token", accesstoken);
// map.put("grant_type", "password");
return map;
}
};
stringRequest.setRetryPolicy(new DefaultRetryPolicy(
60000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
RequestQueue requestQueue = Volley.newRequestQueue(getContext());
requestQueue.add(stringRequest);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// handle item selection
switch (item.getItemId()) {
case R.id.action_settings:
// do s.th.
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#Override
public void onClick(View v) {
try {
makeJsonSettingRequest();
} catch (JSONException e) {
e.printStackTrace();
}
}
}
Backend object looks like
Users = {
NAME: vm.name,
UserName: vm.currentUserName,
oldPassword:vm.oldPassword,
UserPassword: vm.UserPassword
Users.MasterID = vm.masterID;
}
I am able to send through the POSTMan but through Code i am not able to do it.
logcat
05-29 16:16:49.764 1114-2077/com.example.user.mis E/Volley: [651] BasicNetwork.performRequest: Unexpected response code 404 for http://192.168.100.5:84/api/usersApi/updateByMasterID
How can this issue be Solved?
You may try this code, I have implemented the same thing as you do ... it might work for you
private void makeJsonSettingRequest() throws JSONException {
username = userName.getText().toString().trim();
oldpassword = oldPassword.getText().toString().trim();
newpassword = newPassword.getText().toString().trim();
StringRequest stringRequest = new StringRequest(Request.Method.POST, Navigation_URL_SettingRequest,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.i("VOLLEY", response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
System.out.println("This is an Error mate");
}
}) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> headers = new HashMap<String, String>();
headers.put(KEY_Name, Name);
headers.put(KEY_MasterID, master_id);
headers.put(KEY_USERNAME, username);
headers.put(KEY_OldPASSWORD, oldpassword);
headers.put(KEY_UserPassword, newpassword);
return headers;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(getActivity());
requestQueue.add(stringRequest);
}
You can try this one
try {
RequestQueue requestQueue = Volley.newRequestQueue(this);
String URL = "http://...";
JSONObject jsonBody = new JSONObject();
jsonBody.put(KEY_USERNAME, username);
jsonBody.put(KEY_OldPASSWORD, oldpassword);
jsonBody.put(KEY_UserPassword, newpassword);
jsonBody.put(KEY_MasterID, master_id);
jsonBody.put(KEY_Name, Name);
final String requestBody = jsonBody.toString();
StringRequest stringRequest = new StringRequest(Request.Method.POST, URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.i("VOLLEY", response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("VOLLEY", error.toString());
}
}) {
#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
protected Response<String> parseNetworkResponse(NetworkResponse response) {
String responseString = "";
if (response != null) {
responseString = String.valueOf(response.statusCode);
// can get more details such as response.headers
}
return Response.success(responseString, HttpHeaderParser.parseCacheHeaders(response));
}
};
requestQueue.add(stringRequest);
} catch (JSONException e) {
e.printStackTrace();
}
You should change the StringRequest to JSONObjectRequest as you are working with a JSON object in the backend. So you should pass the strings as a JSON object and then it might work.
private void makeJsonObjectRequest() throws JSONException {
JSONObject cred = new JSONObject();
cred.put("username", username.getText().toString());
cred.put("password", password.getText().toString());
JsonObjectRequest jsonObjReq = new
JsonObjectRequest(Request.Method.POST,
urlJsonPost, cred, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d(TAG, response.toString());
//aftererror:
try {
// Parsing json object response
// response will be a json object
token = response.getString("token");
adminName = response.getString("adminName");
jsonResponse = "";
jsonResponse += "token:" + token ;
jsonResponse += "adminName:" + adminName;
txtResponse.setText(jsonResponse);
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(),
"Error: " + e.getMessage(),
Toast.LENGTH_LONG).show();
}
hidepDialog();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
Toast.makeText(getApplicationContext(),
error.getMessage(), Toast.LENGTH_SHORT).show();
}});AppController.getInstance().addToRequestQueue(jsonObjReq);
You would also need to create a class named AppController.java and punch in the below code
import android.app.Application;
import android.text.TextUtils;import com.android.volley.Request;import com.android.volley.RequestQueue;import com.android.volley.toolbox.Volley;public class AppController extends Application {
public static final String TAG = AppController.class.getSimpleName();
private RequestQueue mRequestQueue;
private static AppController mInstance;
#Override
public void onCreate() {
super.onCreate();
mInstance = this;
}
public static synchronized AppController getInstance() {
return mInstance;
}
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);
}
public void cancelPendingRequests(Object tag) {
if (mRequestQueue != null) {
mRequestQueue.cancelAll(tag);
}
}
}
You can also send POST parameters as JSONObject with the StringRequest.
Try this one:
private static final String KEY_Name = "NAME"
private static final String KEY_MasterID = "MasterID"
private static final String KEY_USERNAME = "UserName"
private static final String KEY_OldPASSWORD = "oldPassword"
private static final String KEY_UserPassword= "UserPassword"
..........
..................
JSONObject params = new JSONObject();
params.put(KEY_Name, Name);
params.put(KEY_MasterID, master_id);
params.put(KEY_USERNAME, username);
params.put(KEY_OldPASSWORD, oldpassword);
params.put(KEY_UserPassword, newpassword);
StringRequest stringRequest = new StringRequest(Request.Method.POST,
Navigation_URL_SettingRequest, params,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.i("VOLLEY", response);
// VolleyLog.v("Response:%n %s", response.toString(4));
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
System.out.println("This is an Error mate");
}
})
{
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> headers = new HashMap<String, String>();
// headers.put("Authorization", "Bearer " + access_token);
// headers.put("Authorization", access_token);
// headers.put("Content-Type", "application/x-www-form-urlencoded");
// headers.put("Content-Type", "application/json");
return headers;
}
};
stringRequest.setRetryPolicy(new DefaultRetryPolicy(
60000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
RequestQueue requestQueue = Volley.newRequestQueue(getContext());
requestQueue.add(stringRequest);
..............
...................
I have broken masterID and Send only the integer for the login, but in the changing password i want all the masterID without broken.Which is not added by me,thats the error and has to sent through the parameter section.
working code is shown below
public class SettingFragment extends Fragment implements View.OnClickListener {
EditText userName, oldPassword, newPassword;
String Navigation_URL_SettingRequest = "http://192.168.100.5:84/api/usersApi/updateByMasterID";
String username, oldpassword, newpassword;
String master_id, Name, access_token;
Button save, reset;
public static final String KEY_Name = "NAME";
public static final String KEY_USERNAME = "UserName";
public static final String KEY_OldPASSWORD = "oldPassword";
public static final String KEY_UserPassword = "UserPassword";
public static final String KEY_MasterID = "MasterID";
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_setting, container, false);
setHasOptionsMenu(true);
userName = (EditText) view.findViewById(R.id.setting_username);
oldPassword = (EditText) view.findViewById(R.id.setting_oldpassword);
newPassword = (EditText) view.findViewById(R.id.setting_newpassword);
save = (Button) view.findViewById(R.id.setting_save);
reset = (Button) view.findViewById(R.id.setting_reset);
SessionManagement session = new SessionManagement(getContext());
session.checkLogin();
access_token = session.getAccesstToken();
master_id = session.getMasterId1();
System.out.println(master_id);
Name = session.getKeyName();
save.setOnClickListener(this);
return view;
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
// TODO Auto-generated method stub
super.onCreateOptionsMenu(menu, inflater);
inflater.inflate(R.menu.dashboard, menu);
}
private void makeJsonSettingRequest() throws JSONException {
username = userName.getText().toString().trim();
oldpassword = oldPassword.getText().toString().trim();
newpassword = newPassword.getText().toString().trim();
StringRequest stringRequest = new StringRequest(Request.Method.POST, Navigation_URL_SettingRequest,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.i("VOLLEY", response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
System.out.println("This is an Error mate");
}
}) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> headers = new HashMap<String, String>();
// headers.put("Authorization", "Bearer " + access_token);
// headers.put("Authorization", access_token);
// headers.put("Content-Type", "application/x-www-form-urlencoded");
// headers.put("Content-Type", "application/json");
return headers;
}
#Override
protected Map<String, String> getParams() {
Map<String, String> map = new HashMap<String, String>();
//JSONObject content = new JSONObject();
try {
map.put(KEY_USERNAME, username);
map.put(KEY_OldPASSWORD, oldpassword);
map.put(KEY_UserPassword, newpassword);
map.put(KEY_MasterID, "s" + master_id);
map.put(KEY_Name, Name);
Log.d("Success", map.put(KEY_USERNAME, username));
Toast.makeText(getContext(), "", Toast.LENGTH_SHORT).show();
} catch (Exception e) {
e.printStackTrace();
}
//map.put("access_token", accesstoken);
// map.put("grant_type", "password");
return map;
}
};
stringRequest.setRetryPolicy(new DefaultRetryPolicy(
60000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
RequestQueue requestQueue = Volley.newRequestQueue(getContext());
requestQueue.add(stringRequest);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// handle item selection
switch (item.getItemId()) {
case R.id.action_settings:
// do s.th.
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#Override
public void onClick(View v) {
try {
makeJsonSettingRequest();
} catch (JSONException e) {
e.printStackTrace();
}
}
}
I'm trying to use KairosAPI's enroll POST request using Android Volley. However I keep getting Error 1002, image one or more required parameters are missing. I've tried two ways to add the parameters into the body of the JSON, which I've outlined in the code.
This is my code-
public class MainActivity extends AppCompatActivity {
RequestQueue requestQueue;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
postRequestToEnrollPersonInGallery();
}
public void postRequestToEnrollPersonInGallery() {
final String appId = "3e12****";
final String appKey = "156e06fd782a3304f085f***********";
String mainUrl = "https://api.kairos.com/";
String enrollRequestUrl = "enroll";
requestQueue = Volley.newRequestQueue(this);
StringRequest stringRequest = new StringRequest(Request.Method.POST, mainUrl + enrollRequestUrl, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d("Volley", response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("Volley", error.toString());
}
}) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("Content-Type", "application/json");
params.put("app_id", appId);
params.put("app_key", appKey);
return params;
}
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("image", "https://s-media-cache-ak0.pinimg.com/originals/c6/c0/04/c6c004ec669d92faa36d8ff447884293.jpg");
params.put("subject_id", "12345");
params.put("gallery_name", "FirstGallery");
/*params.put("image", "\"url\":\"https://s-media-cache-ak0.pinimg.com/originals/c6/c0/04/c6c004ec669d92faa36d8ff447884293.jpg\"");
params.put("subject_id", "\"subject_id\":\"12345\"");
params.put("gallery_name", "\"gallery_name\":\"FirstGallery\""); -- i tried this too*/
return params;
}
};
requestQueue.add(stringRequest);
}
}
You aren't posting JSON.
You can either
1) Learn to use JsonObjectRequest
final JSONObject body = new JSONObject();
body.put(... , ...);
Request request = new JsonObjectRequest(url, body, ...);
2) Actually post a JSON String.
StringRequest request = new StringRequest(...) {
#Override
public byte[] getBody() throws AuthFailureError {
JSONObject params = new JSONObject();
params.put("image", "https://s-media-cache-ak0.pinimg.com/originals/c6/c0/04/c6c004ec669d92faa36d8ff447884293.jpg");
params.put("subject_id", "12345");
params.put("gallery_name", "FirstGallery");
return params.toString().getBytes();
}
#Override
public String getBodyContentType() {
return "application/json";
}
};
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