Get Auth AcessToken from Paypal Android sdk - java

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

Related

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

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

Calling an API with string parametrs in Android with Volley

I'am trying to call an API that adds data to a dynamoDB each time a user creates an account .
The url of the API is in the following format :
https://t3x9lg8utf.execute-api.us-east-2.amazonaws.com/prod? id=""&username=""&numero_passeport=""&decision=""
The problem is that when i call the API using volley i get this error :
06-03 14:32:23.599 13503-14515/com.amazonaws.youruserpools.CognitoYourUserPoolsDemo E/Volley: [14796] BasicNetwork.performRequest: Unexpected response code 400 for https://t3x9lg8utf.execute-api.us-east-2.amazonaws.com/prod
The code i used to call the API :
StringRequest sr = new StringRequest(Request.Method.GET, "https://t3x9lg8utf.execute-api.us-east-2.amazonaws.com/prod",
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.e("HttpClient", "success! response: " + response.toString());
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("HttpClient", "error: " + error.toString());
}
})
{
#Override
protected Map<String,String> getParams(){
Map<String,String> params = new HashMap<String, String>();
params.put("id","\"\"");
params.put("username","\"zaeae\"");
params.put("numero_passeport","\"\"");
params.put("decision","\"\"");
return params;
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String,String> params = new HashMap<String, String>();
return params;
}
};
queue.add(sr);
try this
StringRequest sr = new StringRequest(Request.Method.GET, "https://t3x9lg8utf.execute-api.us-east-2.amazonaws.com/prod?id="+Uri.encode(id)+"&username="+Uri.encode(username)+"&numero_passeport="+Uri.encode(numero_passeport)+"&decision="+Uri.encode(decision),
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.e("HttpClient", "success! response: " + response.toString());
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("HttpClient", "error: " + error.toString());
}
})
{
#Override
protected Map<String,String> getParams(){
Map<String,String> params = new HashMap<String, String>();
params.put("id","\"\"");
params.put("username","\"zaeae\"");
params.put("numero_passeport","\"\"");
params.put("decision","\"\"");
return params;
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String,String> params = new HashMap<String, String>();
return params;
}
};
queue.add(sr);
also pass values for id, username, numero_passeport and decision
? id=""&
These are URL parameters, which cannot be passed via getParams()
You need to append them to the string after Request.Method.GET

Posting Data to Server with volley library from android App

Guys i need help am trying to post this data to my server here but it is returning an error, it seems to be working just fine in postman the problem comes in while trying to implement in android app using google's volley library.
Link to server script.
This is the screenshot of a successful post working in postman rest client:2
private void SaveDataToServer() {
StringRequest serverPostRequest = new StringRequest(Request.Method.POST, Config.SAVE_INVENTORY_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String json) {
try {
Toast.makeText(SelectItemsActivity.this, json.toString(), Toast.LENGTH_SHORT).show();
Log.e("RESPONSE FROM SERVER",json);
JSONObject dataJson=new JSONObject(json);
JSONObject myJson=dataJson.getJSONObject("status");
String status=myJson.getString("status_text");
if (status.equalsIgnoreCase("Success.")){
Toast.makeText(SelectItemsActivity.this, "Data saved Successfully", Toast.LENGTH_SHORT).show();
proggressShow.dismiss();
}else {
Toast.makeText(SelectItemsActivity.this, "An error occured while saving data", Toast.LENGTH_SHORT).show();
proggressShow.dismiss();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
}
}){
#Override
protected Map<String, String> getPostParams() {
HashMap<String, String> params = new HashMap<String, String>();
params.put("api_key",Config.API_KEY);
params.put("move_id", "1");
params.put("room_name", "Attic room");
params.put("item_name", "Halloween Broom");
params.put("item_id", "6");
Log.e("datat to server",params.toString());
return params;
}
};
saveDataRequest.add(serverPostRequest);
}
Try adding getHeaders method in your request
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
final HashMap<String, String> headers = new HashMap<>();
headers.put("Content-Type", "multipart/form-data");
return headers;
}
After adding this lines to my request headers i was able to successfully commit the database to my db.
Also i made sure i am using a stringRequest for a jsonRequest it does not work for reasons i do not know.
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<>();
headers.put("Content-Type","application/x-www-form-urlencoded");
return headers;
}

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

Server side:
import flask
import flask.ext.sqlalchemy
import flask.ext.restless
app = flask.Flask(__name__)
app.config['DEBUG'] = True
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:////tmp/test.db'
SQLALCHEMY_TRACK_MODIFICATIONS=True
db = flask.ext.sqlalchemy.SQLAlchemy(app)
class Person(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.Unicode, unique=True)
birth_date = db.Column(db.Date)
class Computer(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.Unicode, unique=True)
vendor = db.Column(db.Unicode)
purchase_time = db.Column(db.DateTime)
owner_id = db.Column(db.Integer, db.ForeignKey('person.id'))
owner = db.relationship('Person', backref=db.backref('computers',
lazy='dynamic'))
db.create_all()
manager = flask.ext.restless.APIManager(app, flask_sqlalchemy_db=db)
manager.create_api(Person, methods=['GET', 'POST', 'DELETE'])
manager.create_api(Computer, methods=['GET'])
app.run(host='0.0.0.0', port=5000, debug=True)
Client Side :
Using volley post
RequestQueue queue = Volley.newRequestQueue(this);
StringRequest postRequest = new StringRequest(Request.Method.POST, url,
new Response.Listener<String>()
{
#Override
public void onResponse(String response) {
// response
Log.d("Response", response);
}
},
new Response.ErrorListener()
{
#Override
public void onErrorResponse(VolleyError error) {
// error
Log.d("Error.Response", String.valueOf(error));
}
}
) {
#Override
protected Map<String, String> getParams()
{
Map<String, String> params = new HashMap<String, String>();
params.put("name", "Anything");
return params;
}
};
queue.add( postRequest );
}
Output from log:
04-29 11:42:24.556 1890-1946/? I/Icing: Indexing done F3642025687382E430F3465743F12480D56AAC66
04-29 11:43:32.123 3147-3196/? E/Volley: [157] BasicNetwork.
performRequest: Unexpected response code 415 for http://IP:5000/api/person
04-29 11:43:32.132 3147-3147/? D/Error.Response: com.android.volley.ServerError
04-29 11:45:19.365 1298-1311/? I/UsageStatsService: User[0] Flushing usage stats to disk
provide the right content type as follows
// Optional Parameters to pass as POST request
JSONObject js = new JSONObject();
try {
js.put("name","anything");
} catch (JSONException e) {
e.printStackTrace();
}
// Make request for JSONObject
JsonObjectRequest jsonObjReq = new JsonObjectRequest(
Request.Method.POST, url, js,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d(TAG, response.toString() + " i am queen");
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
}
}) {
/**
* Passing some request headers
*/
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<String, String>();
headers.put("Content-Type", "application/json; charset=utf-8");
return headers;
}
};
// Adding request to request queue
Volley.newRequestQueue(this).add(jsonObjReq);
}
415 is the error code for wrong media type. You are sending the body or your post request in plain text when the server expects json. Find out what type of content you should send and make the post body to that type.
#Override
public byte[] getBody() {
return 'your json string'.getBytes();
}
#Override
public String getBodyContentType() {
return "application/json; charset=utf-8";
}
if you are using Kotlin, here is the snippet I implemented
val jsonBody = JSONObject()
jsonBody.put("email", email)
jsonBody.put("password", password)
val requestBody = jsonBody.toString()
val registerRequest =
object : StringRequest(Method.POST, URL_REGISTER, Response.Listener { response ->
print(response)
complete(true)
}, Response.ErrorListener { error ->
Log.d("Error", "not possible to register at this time . $error")
complete(false)
}) {
override fun getBodyContentType(): String {
return "application/json; charset=utf-8";
}
override fun getBody(): ByteArray {
return requestBody.toByteArray()
}
}
Volley.newRequestQueue(context).add(registerRequest)
}

Why Android Studio prompt “Method doesn't override its superclass”?

I want to use volley to build http connection with authentication. Following this answer I add the segment
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> params = new HashMap<String, String>();
String creds = String.format("%s:%s","USERNAME","PASSWORD");
String auth = "Basic " + Base64.encodeToString(creds.getBytes(), Base64.DEFAULT);
params.put("Authorization", auth);
return params;
}
in Anonymous Inner Class StringRequest , and it looks like:
StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
new Response.Listener<String>() {
//the segment below is what I add
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> params = new HashMap<String, String>();
String creds = String.format("%s:%s","USERNAME","PASSWORD");
String auth = "Basic " + Base64.encodeToString(creds.getBytes(), Base64.DEFAULT);
params.put("Authorization", auth);
return params;
}
//the segment above is what I add
#Override
public void onResponse(String response) {
// Display the first 500 characters of the response string.
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
However, IDE hints that getHeaders() doesn't override its superclass.
Why?I found that StringRequest extends class Request<String>, and the latter does have a method called getHeaders().
You are overriding public Map<String, String> getHeaders() inside a new instance of Response.Listener<String> instead of Request<String> and Response.Listener<String> does not have such method (only onResponse(String)).

Categories

Resources