I have been trying to get the Instamojo link in my android application for a transaction. For testing I have been trying to send the post request to generate the link but all the time I am getting AuthFailureError. I am posting my code below.I don't know if some error is there in my codes or I am following the wrong way to integrate Instamojo in my app. Please help.
MainActivity.java:
public class MainActivity extends AppCompatActivity {
private RequestQueue mQueue;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
mQueue = CustomVolleyRequestQueue.getInstance(this)
.getRequestQueue();
String url = "https://www.instamojo.com/api/1.1/payment-requests/";
JSONObject params = new JSONObject();
try {
params.put("purpose","selling");
params.put("amount","20");
} catch (JSONException e) {
e.printStackTrace();
}
final CustomJSONObjectRequest jsonRequest=new CustomJSONObjectRequest(Request.Method.POST, url,params, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response)
{
Log.d("animesh",response.toString());
}
},new Response.ErrorListener()
{
#Override
public void onErrorResponse(VolleyError error)
{
Toast.makeText(MainActivity.this, "no internet connection", Toast.LENGTH_SHORT).show();
Log.d("animesh", error.toString());
}
});
mQueue.add(jsonRequest);
}
}
CustomJSONObjectRequest.java:
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
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<String, String>();
//String creds = String.format("%s:%s","archerpenny_glide","archer##62#glide*");
//String auth = "Basic " + Base64.encodeToString(creds.getBytes(), Base64.DEFAULT);
headers.put("api_key", "**********************************");
headers.put("auth_token", "*******************************");
return headers;
}
#Override
public RetryPolicy getRetryPolicy() {
// here you can write a custom retry policy
return super.getRetryPolicy();
}
}
To send the api_key and the auth_token you are doing:
headers.put("api_key", "**********************************");
headers.put("auth_token", "*******************************");
Instead, you need to do:
headers.put("X-Api-Key", "**********************************");
headers.put("X-Auth-Token", "*******************************");
You can refer to the REST API documentation here: https://www.instamojo.com/developers/rest/
Related
How to add the request body to my code like using Postman's body tab. I figure it out only request header. 
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final TextView textView = findViewById(R.id.textView);
String url = "url";
RequestQueue requestQueue = Volley.newRequestQueue(this);
JsonObjectRequest objectRequest = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.e("Response : ",response.toString());
textView.setText("Success!");
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("Response error : ",error.toString());
error.printStackTrace();
textView.setText("Failed!");
}
})
{
#Override
public Map getHeaders() throws AuthFailureError {
HashMap headers = new HashMap();
headers.put("accept-language","EN");
headers.put("authorization","<autho>");
headers.put("requestUId","<requestID>");
headers.put("resourceOwnerId","<resorceOwnerID>");
return headers;
}
};
requestQueue.add(objectRequest);
}
}
Ref Postman's head tab :
https://s3.amazonaws.com/postman-static-getpostman-com/postman-docs/58960775.png
Thank you
Create your JSONObject request as below:
JSONObject jsonBody = new JSONObject();
try {
jsonBody.put("firstname", "asd");
jsonBody.put("lastname", "asd");
jsonBody.put("id", "1");
} catch (JSONException e) {
e.printStackTrace();
}
Then the third parameter in the JsonObjectRequest() constructor is the request, you are currently passing null. Replace it with jsonBody.
Edit
You also have to change your HTTP method to POST instead of GET if you want your parameters to be sent in the request body.
i trying to connect my project in android studio to Asp.net API
and i'm using Volley Lib to Get Json Request but he did'nt read the response
and I getting this massage in Log
((( E/Volley: [352] BasicNetwork.performRequest:
Unexpected response code 400 for http://10.10.4.150:61511/api/Feedback/30)))
-Api work correctly i`m test with postman
enter image description here
public static final String GET_BY_ID = "http://10.10.4.150:61511/api/Feedback/30";
EditText id;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
id = (EditText) findViewById(R.id.idtxt);
}
public void click(View v) {
if (v.getId() == R.id.btnget) {
insertData (id.getText().toString()) ;
}
}
public void insertData (String value){
HashMap<String,String> param = new HashMap<String, String>();
param.put("id",value);
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, GET_BY_ID,null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d("Response", response.toString());
try {
JSONObject ob = response.getJSONObject("userId") ;
int name = ob.getInt("userId");
Toast.makeText(getBaseContext(),name,Toast.LENGTH_LONG).show();
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(getBaseContext(),e.getMessage(),Toast.LENGTH_LONG).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getBaseContext(),error.getMessage(),Toast.LENGTH_LONG).show();
}
}) {
#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");
headers.put("User-agent", "My useragent");
return headers;
}};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(request);
}
}
I want to send three parameters "guestEmail", "latitude" and "longitude" to backend and get a message of success from backend if it is successful.
I have tried doing this:
public void myGetFunc()
{
final String url = "....";
// prepare the Request
JsonObjectRequest getRequest = new JsonObjectRequest(Request.Method.GET, url, null,
new Response.Listener<JSONObject>()
{
#Override
public void onResponse(JSONObject response) {
// display response
Log.d("Response", response.toString());
Toast.makeText(getApplicationContext(), response.toString(), Toast.LENGTH_SHORT).show();
}
},
new Response.ErrorListener()
{
#Override
public void onErrorResponse(VolleyError error) {
Log.d("Error.Response", response);
}
}
)
{
#Override
protected Map<String, String> getParams()
{
Map<String, String> params = new HashMap<String, String> ();
params.put("guestEmail", "abc#xyz.com");
params.put("latitude", "12");
params.put("longitude", "12");
return params;
}
};
// add it to the RequestQueue
queue.add(getRequest);
}
This method is invoked when the 'SOS' button is clicked.
But right now, nothing happens on clicking the 'SOS' button.
Please help!
If you are going to use GET you query parameters and build the string yourself
private static final String URL = "http://www.test.com?value1={val1}&value2={val2}";
String requestString = URL;
requestString.replace("{val1}", "1");
requestString.replace("{val2}", "Bob");
StringRequest strreq = new StringRequest(Request.Method.GET,
requestString,
new Response.Listener<String>() {
#Override
public void onResponse(String Response) {
// get response
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError e) {
e.printStackTrace();
}
});
Volley.getInstance(this).addToRequestQueue(strreq);
If you are going to use POST us a body
public class LoginRequest extends Request<String> {
// ... other methods go here
private Map<String, String> mParams;
public LoginRequest(String param1, String param2, Listener<String> listener, ErrorListener errorListener) {
super(Method.POST, "http://test.url", errorListener);
mListener = listener;
mParams = new HashMap<String, String>();
mParams.put("paramOne", param1);
mParams.put("paramTwo", param2);
}
#Override
public Map<String, String> getParams() {
return mParams;
}
}
If you want to pass parameters than you need to use POST method otherwise for GET , just pass values in URL itself.
So I have this customer, and I want to update the fcm_token value in the customer object via post request using volley, but It's not working..!
See the json link >> http://www.mocky.io/v2/5911638a1200001e020fb5d2
My attempt so far..
public class MyFirebaseInstanceIDService extends FirebaseInstanceIdService {
private static final String TAG = "MyFirebaseIIDService";
#Override
public void onTokenRefresh() {
String refreshedToken = FirebaseInstanceId.getInstance().getToken();
sendRegistrationToServer(refreshedToken);
}
private void sendRegistrationToServer(String token) {
RequestQueue requestQueue = Volley.newRequestQueue(this);
HashMap<String, String> params = new HashMap<String, String>();
params.put("fcm_token", token);
Customer me = Hawk.get("user");
String URL = API_URLs.TokenURL(me.getID());
JsonObjectRequest jsObjRequest = new JsonObjectRequest(Request.Method
.POST, URL, new JSONObject(params),
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
//Log
}
},
new Response.ErrorListener()
{
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
//Log
}
}
);
requestQueue.add(jsObjRequest);
UPDATE
I change request to this and still didn't change..!?
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.POST,
URL, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d(TAG, response.toString());
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("fcm_token", token);
return params;
}
};
requestQueue.add(jsonObjReq);
UPDATE 2
so after a lot of attempts still not solved, but I'm gonna explain what I want to do exactly maybe you will get what I want to accomplish, I wanna send my device fcm token to server based on the user id when login, so I have a Customer model class that has the value of fcm_token it must after the request is made it must be set as my token, the process happens in web server btw.
Here's my code so far..
MyFirebaseInstanceIDService Class
public class MyFirebaseInstanceIDService extends FirebaseInstanceIdService {
private static final String TAG = "MyFirebaseIIDService";
String refreshedToken;
#Override
public void onTokenRefresh() {
refreshedToken = FirebaseInstanceId.getInstance().getToken();
Hawk.put("token", refreshedToken);
}
public static void sendRegistrationToServer(Context context) {
}
}
Customer Model Class
public class Customer {
#SerializedName("avatar_url")
#Expose
private String cusPicURL;
#SerializedName("first_name")
#Expose
private String firstName;
#SerializedName("last_name")
#Expose
private String lastName;
#SerializedName("fcm_token")
#Expose
private String token;
public String getToken() {
return token;
}
public void setToken(String token) {
this.token = token;
}
// ..... more variables & setters and getters
My Request Code inside a repository class (all request are here..)
public static void UpdateFCM_Token(final Context context, final String token) {
RequestQueue requestQueue = Volley.newRequestQueue(context);
Customer me = Hawk.get("user");
Log.i("USER ID: ", "" + me.getID());
String URL = API_URLs.TokenURL(me.getID());
JsonObjectRequest req = new JsonObjectRequest(Request.Method.POST,
URL, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONObject o = response.getJSONObject("customer");
Gson gson = new Gson();
Customer customer = gson.fromJson(o.toString(), Customer.class);
} catch (JSONException e) {
e.printStackTrace();
}
Log.d("FCM OnResponse", response.toString());
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d("FCM Error: ", "" + error.getMessage());
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("fcm_token", token);
return params;
}
};
requestQueue.add(req);
}
The fragment in MainActivity
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// code..
String token = Hawk.get("token");
Log.i("TOKEN", token);
DriverRepository.UpdateFCM_Token(getActivity(), token);
return rootView;
}
The Logs
Hey you suppose to add Map + remove null from new JsonObjectRequest(.......null,listener....):
private void sendRegistrationToServer(String token) {
RequestQueue requestQueue = Volley.newRequestQueue(this);
HashMap<String, String> params = new HashMap<String, String>();
params.put("fcm_token", token);
Customer me = Hawk.get("user");
String URL = API_URLs.TokenURL(me.getID());
JsonObjectRequest jsObjRequest = new JsonObjectRequest(Request.Method.POST, url,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
//Log
}
},
new Response.ErrorListener()
{
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
//Log
}
}
){
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String,String> map = new HashMap();
//add your params here to the map
return map;
}
};
requestQueue.add(jsObjRequest);
You may have to override getParams of JsonObjectRequest and pass your POST params.
JsonObjectRequest jsObjRequest = new JsonObjectRequest(Request.Method
.POST, URL, null, listener, errorListener){
protected Map<String,String> getParams() throws AuthFailureError{
return postParamsMap;
}
}
You can also use StringRequest instead of JsonObjectRequest.
StringRequest jsonObjReq = new StringRequest(Request.Method.POST,
URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d(TAG, response);
//Converting the response to JSON
JSONObject jsonObj = new JSONObject(response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("fcm_token", token);
return params;
}
};
requestQueue.add(jsonObjReq);
after some works, I solved it using okhttp3 since volley didn't work for me, although the rest of request in my app are using volley but this one is only okhttp3, I hope that's not a bad practice.
Thanks a lot guys for ur help..!
here's the code in my request method.. in case someone might have the same problem.
public static void UpdateFCM_Token(final String token) {
Customer me = Hawk.get("user");
Log.i("USER ID: ", "" + me.getID());
String URL = API_URLs.TokenURL(me.getID());
OkHttpClient client = new OkHttpClient();
String json = "{\"fcm_token\":\"" + token + "\"}";
Log.i("Json : ", json);
MediaType mediaType = MediaType.parse("application/json");
RequestBody body = RequestBody.create(mediaType, json);
okhttp3.Request request = new okhttp3.Request.Builder()
.url(URL)
.post(body)
.addHeader("content-type", "application/json")
.build();
try {
okhttp3.Response response = client.newCall(request).execute();
isTokenSent = true;
Log.i("response ", response + "");
} catch (IOException e) {
e.printStackTrace();
Log.i("IOException", "" + e);
}
}
I am using android volley library to post data to back-end service. But I can't send any parameter with my request. I have done each and everything mentioned here . But none works for me. The post method that I am using is:
public static void post()
{
// Tag used to cancel the request
String tag_json_obj = "json_obj_req";
String url = "http://myUrl";
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.POST,
url, obj,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d("TAG", response.toString());
}
}, 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>();
return headers;
}
#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("key", "value");
return params;
}
};
// Adding request to request queue
AppController.getInstance().addToRequestQueue(jsonObjReq, tag_json_obj);
}
Always the response is "parameter missing".
How could i resolve this issue?
If you're using JSONObjectRequest, you can try this.
String url = "http://myurl";
Map<String, String> params = new HashMap<String, String>();
params.put("key", value);
RequestQueue queue = Volley.newRequestQueue(getActivity());
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST,
url, new JSONObject(params),
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject jsonObject) {
try {
success = jsonObject.getInt("success");
message = jsonObject.getString("message");
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
Activity activity = getActivity();
if (volleyError instanceof NoConnectionError) {
String errormsg = "Check your internet connection";
Toast.makeText(activity, errormsg, Toast.LENGTH_LONG).show();
}
}
});
queue.add(jsonObjectRequest);
The codes are more likely the same as yours. Check on the lines where I put the data to be posted. I'm very sure this would work!
The problem is you are approaching the request as though you were making a stringRequest. The link you reference is talking specifically about making a stringRequest.
jsonObjectRequest actually lets you put the json object into the constructor itself, instead of using the override method getParams() like so:
String url = "some_url";
JSONObject jsonObject = new JSONObject();
try {
jsonObject.put(Constants.LOGIN_EMAIL_ID, email);
jsonObject.put(Constants.LOGIN_PASSWORD, password);
}catch(JSONException e){
Log.d("JSON error", e.getMessage(), e);
}
JsonObjectRequest jsObjRequest = new JsonObjectRequest(url, jsonObject, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d("RESPONSE", response.toString());
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
if(error.getMessage()!=null){
Log.d("RESPONSE", error.getMessage());
}
}
});
VolleySingleton.getInstance(activity).getRequestQueue().add(jsObjRequest);