Retrofit Error 400 Bad Request - java

I am experiencing an interesting error. I am using mailgun and Retrofit to send e-mails through my application. On the first attempt after opening my application, the send attempt always returns a retrofit error (400 Bad Request). However, all subsequent attempts send through appropriately.
MailGunClient interface:
public interface MailGunClient {
#FormUrlEncoded
#POST("/messages")
void sendMessagePurchase(
#Field("from") String from,
#Field("to") String to,
#Field("h:Reply-To") String replyToAddress,
#Field("subject") String subject,
#Field("text") StringBuilder text,
Callback<Response> responseCallback);
}
Method instantiating the interface and attempting to send (MainActivity):
public void sendResume(String productID) {
if (productID.equals(EMAILSKU)) {
mMailGunClient = new RestAdapter.Builder()
.setEndpoint("https://api.mailgun.net/v3/mg.resumetemplatepro.com")
.setLogLevel(RestAdapter.LogLevel.FULL)
.setRequestInterceptor(new RequestInterceptor() {
#Override
public void intercept(RequestFacade request) {
final String credentials = "api" + ":" + "key-c5b8f0c0c7dcaabc23075b977a7b7e43";
final String authString = "Basic " + Base64.encodeToString(credentials.getBytes(), Base64.DEFAULT);
request.addHeader("Authorization", authString);
}
})
.build().create(MailGunClient.class);
StringBuilder messageBody = new StringBuilder();
messageBody.append("Hello," + "\r\n" + "\r\n");
messageBody.append("Thank you for purchasing a resume. You can view the resume at the following link: " + getResumeTemplateDownloadLink(pager.getCurrentItem()) + "\r\n" + "\r\n");
messageBody.append("Regards," + "\r\n");
messageBody.append("The Resume Template Pro Team");
mMailGunClient.sendMessagePurchase("resume#mg.resumetemplatepro.com", customerEmailAddress, RBPEMAIL, "Resume Template Email",
messageBody, new Callback<Response>() {
#Override
public void success(Response response, Response response2) {
System.out.println("Success");
Toast.makeText(getApplication(), R.string.successfully_sent, Toast.LENGTH_SHORT).show();
Apptentive.engage(MainActivity.this, "Post_Sale");
}
#Override
public void failure(RetrofitError error) {
Toast.makeText(getApplicationContext(), R.string.try_again, Toast.LENGTH_LONG).show();
}
});
} else if (productID.equals(RESUMECOVERLETTER)) {
mMailGunClient = new RestAdapter.Builder()
.setEndpoint("https://api.mailgun.net/v3/mg.resumetemplatepro.com")
.setLogLevel(RestAdapter.LogLevel.FULL)
.setRequestInterceptor(new RequestInterceptor() {
#Override
public void intercept(RequestFacade request) {
final String credentials = "api" + ":" + "key-c5b8f0c0c7dcaabc23075b977a7b7e43";
final String authString = "Basic " + Base64.encodeToString(credentials.getBytes(), Base64.DEFAULT);
request.addHeader("Authorization", authString);
}
})
.build().create(MailGunClient.class);
StringBuilder messageBody = new StringBuilder();
messageBody.append("Hello," + "\r\n" + "\r\n");
messageBody.append("The user with e-mail " + customerEmailAddress + " has purchased a professional edit. They purchased " + getResumeTemplateDownloadLink(pager.getCurrentItem()) + "." + "\r\n" + "\r\n");
messageBody.append("Regards," + "\r\n");
messageBody.append("The Resume Template Pro Team");
mMailGunClient.sendMessagePurchase("resume#mg.resumetemplatepro.com", RBPEMAIL, customerEmailAddress, "Resume Template Purchase",
messageBody, new Callback<Response>() {
#Override
public void success(Response response, Response response2) {
System.out.println("Success");
Toast.makeText(getApplication(), R.string.edit_purchase, Toast.LENGTH_SHORT).show();
Apptentive.engage(MainActivity.this, "Post_Sale");
}
#Override
public void failure(RetrofitError error) {
Toast.makeText(getApplicationContext(), R.string.try_again, Toast.LENGTH_LONG).show();
}
});
} else {
Toast.makeText(MainActivity.this, R.string.error, Toast.LENGTH_SHORT).show();
}
}

Related

Volley not recieving http response but postman is

I send the /getsms GET request to an API and I get the expected results on postman. However, when I try to make the same request through volley in java on android studio, it just doesn't get a response, I keep waiting and nothing happens.
I'm sure the API does get the request since the expected changes occur when I send the data associated with the get request.
So I'm at a loss as to why exactly it doesn't get a response.
Java code:
final String url = "http://10.0.2.2:3000/myroute/getsms/"+frm;
JsonObjectRequest getRequest = new JsonObjectRequest(Request.Method.GET, url, null,
new Response.Listener<JSONObject>()
{
#Override
public void onResponse(JSONObject response) {
try {
String frm = response.getString("src_num");
String msg = response.getString("msg");
int id = response.getInt("id");
itemsAdapter.add(frm + ": " + msg);
Log.d("Response", response.toString());
}
catch (Exception err) {
Log.d("excpetion", err.toString());
}
}
},
new Response.ErrorListener()
{
#Override
public void onErrorResponse(VolleyError error) {
Log.d("Error.Response", error.toString());
}
}
);
API code:
router.get('/getsms/:dest_num', function (req, res) {
console.log("get oldest unsent sms from db");
let sql = "SELECT * FROM " + table + " WHERE " + "dest_num=" + req.params.dest_num + " AND sent=FALSE " + "ORDER BY id " + "LIMIT 1;";
console.log(sql);
db.mycon.query(sql, function (err, result) {
console.log("Result: " + JSON.stringify(result));
if(err){
res.send(err);
} else {
console.log("SENT!")
res.json(result);
}
});
});
Any help is appreciated.
UPDATE: So upon sifting through the logs I found this:
2020-01-15 22:07:23.481 11880-11880/com.example.sms D/Error.Response: com.android.volley.ParseError: org.json.JSONException: Value [{"id":4,"src_num":"321","dest_num":"1003435365","msg":"first message from server","time":100,"sent":0}] of type org.json.JSONArray cannot be converted to JSONObject
Apparently the response is received but Volley kicks when parsing. I cant see why this is happening. I don't see anything wrong with the JSON string. And is this really enough for it to not go into the onResponse function?
UPDATE2: So apparently that was indeed the problem and what was sent wasn't a JSONObject but a JSONArray. and just needed to change the datatypes accordingly.
So the code ended working with:
String url = "http://10.0.2.2:3000/myroute/getsms/" + frm;
JsonArrayRequest jsonObjectRequest = new JsonArrayRequest(Request.Method.GET, url, null, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response_arr) {
try {
JSONObject response = response_arr.getJSONObject(0);
String frm = response.getString("src_num");
String msg = response.getString("msg");
int id = response.getInt("id");
itemsAdapter.add(frm + ": " + msg);
} catch (Exception err) {
System.out.println(err.toString());
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("Error.Response", error.toString());
}
});
requestQueue.add(jsonObjectRequest);
Thanks to the comments for helping :)
You can try for The code given below and also add the request to the requestqueue of the new instance of RequestHandler.
StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONArray array = new JSONArray(response); //here is the mistake of parsing which will be removed after it is converted to the json object
JSONObject object = array.getJSONObject(0); //-----mistake
String frm = object.getString("src_num");
String msg = object.getString("msg");
int id = object.getInt("id");
itemsAdapter.add(frm + ": " + msg);
Log.d("Response", response.toString());
} catch (JSONException e) {
Log.d("excpetion", err.toString());
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("Error.response", err.toString());
}
});
new RequestHandler().addToRequestQueue(stringRequest);
Hope it helps !!

How can i put some condition in Json parser in android studio

Here is my json URL https://jsonplaceholder.typicode.com/todos I want to display only completed: true is to be strike through, how can I do that?
MainActivity.java
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://jsonplaceholder.typicode.com/")
.addConverterFactory(GsonConverterFactory.create())
.build();
JsonPlaceHolderApi jsonPlaceHolderApi = retrofit.create(JsonPlaceHolderApi.class);
Call<List<Post>> call = jsonPlaceHolderApi.getPosts();
call.enqueue(new Callback<List<Post>>() {
#Override
public void onResponse(Call<List<Post>> call, Response<List<Post>> response) {
if (!response.isSuccessful()) {
textresult.setText("Code: " + response.code());
return;
}
List<Post> posts = response.body();
for (Post post : posts) {
String content = "";
content += "User ID: " + post.getUserId() + "\n";
content += "ID: " + post.getId() + "\n";
content += " Title: " + post.getTitle() + "\n";
content += "Completed: " + post.getCompleted() + "\n\n";
textresult.append(content);
if (post.getCompleted().contains("true")) {
textresult.setPaintFlags(textresult.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
}
}
}
#Override
public void onFailure(Call<List<Post>> call, Throwable t) {
textresult.setText(t.getMessage());
}
});
JsonPlaceHolderApi.java
public interface JsonPlaceHolderApi {
#GET("todos")
Call<List<Post>> getPosts();
}
Post.java
public class Post {
private int userId;
private int id;
private String title;
private String completed;
public int getUserId() {
return userId;
}
public int getId() {
return id;
}
public String getTitle() {
return title;
}
public String getCompleted() {
return completed;
}
}
When I try to run the above code I got output as image, but I need if completed: true it should be strike.
it is not possible to do setPaintFlags() with custom text better use can use HTML text for your work for you don't need to check "post.complete()", just append all content in a single string and replace your target string (complete: true) with HTML text.
just do it like
String content = "";
for (Post post : posts) {
content += "User ID: " + post.getUserId() + "\n";
content += "ID: " + post.getId() + "\n";
content += " Title: " + post.getTitle() + "\n";
content += "Completed: " + post.getCompleted() + "\n\n";
}
String tempHtmlText = content.replaceAll("Completed: true","<strike>Completed: true</strike>");
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
textresult.setText(Html.fromHtml(tempHtmlText , Html.FROM_HTML_MODE_LEGACY));
} else {
textresult.setText(Html.fromHtml(tempHtmlText));
}
or you can use Gson formmater

Retrofit2 interceptor converts special character to Question mark in Android

Special characters such as (“ ”,') gets converted into ? while applying
interceptor in retrofit2.While getting response from retrofit2 , i am getting special characters but the interceptor changes the special character to ? and displays ? instead of special characters
Adding retrofit in Interceptor:
CustomRequestInterceptor requestInterceptor = newCustomRequestInterceptor();
HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
logging.setLevel(BuildConfig.DEBUG ? HttpLoggingInterceptor.Level.BODY :
HttpLoggingInterceptor.Level.NONE);
OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
httpClient.addInterceptor(requestInterceptor);
httpClient.addInterceptor(logging);
Interceptor class(CustomRequestInterceptor.java) for retrofit2:
public class CustomRequestInterceptor implements Interceptor {
private static String newToken;
private String bodyString;
private final String TAG = getClass().getSimpleName();
#Override
public Response intercept(Chain chain) throws IOException {
String token = "";
Request request = chain.request();
RequestBody oldBody = request.body();
Buffer buffer = new Buffer();
oldBody.writeTo(buffer);
String strOldBody = buffer.readUtf8();
Log.i(TAG, "original req " + strOldBody);
MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");
JSONObject jsonObject = new JSONObject();
String decodedStr = decoder(strOldBody.replace("data=", ""));
try {
if (decodedStr != null && decodedStr.equalsIgnoreCase("")) {
token = getRandomNumber();
jsonObject.put("auth_token", token);
} else {
jsonObject = new JSONObject(decodedStr);
token = getRandomNumber();
jsonObject.put("auth_token", token);
}
} catch (Exception e) {
Log.e(AppConstants.TAG, "Exception", e);
}
Log.i(AppConstants.TAG, "Request JSONObject " + jsonObject.toString());
String strNewBody = "data=" + URLEncoder.encode(Encryption.encryptString(jsonObject.toString()));
Log.i(TAG, "strNewBody " + strNewBody);
RequestBody body = RequestBody.create(mediaType, strNewBody);
Log.i(TAG, "content type is " + body.contentType().toString());
Log.i(TAG, "content length is " + String.valueOf(body.contentLength()));
Log.i(TAG, "method is " + request.method());
request = request.newBuilder().header("Content-Type", body.contentType().toString())
.header("Content-Length", String.valueOf(body.contentLength()))
.method(request.method(), body).build();
Response response = chain.proceed(request);
String responseString = new String(response.body().bytes());
Log.i(TAG, "Response: " + responseString);
String newResponseString = Encryption.decryptString(responseString);
Log.i(TAG, "Response edited: " + URLDecoder.decode(newResponseString));
JSONObject res_JsonObject = new JSONObject();
if (newResponseString.startsWith("{")) {
try {
res_JsonObject = new JSONObject(newResponseString);
String response_token = res_JsonObject.getString("auth_token");
if (response_token.equalsIgnoreCase("" + token)) {
} else {
res_JsonObject.put("status", false);
res_JsonObject.put("message", "Authentication Failed");
Toast.makeText(new AppController().getApplicationContext(), "Authentication Failed", Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
Log.e(AppConstants.TAG, "Exception", e);
}
}
byte[] ptext = res_JsonObject.toString().getBytes(ISO_8859_1);
String value = new String(ptext, UTF_16);
return response.newBuilder()
.body(ResponseBody.create(response.body().contentType(), value))
.build();
}
public String decoder(String encodedStr) {
try {
return URLDecoder.decode(encodedStr);
} catch (Exception e) {
Log.e(AppConstants.TAG, "Exception", e);
return encodedStr;
}
}
}
Expected output:
{
"comment": "“hello”"
}
Actual output:
{
"comment": "?hello?"
}
The problem is in the return statement of intercept method,
when we call ResponseBody.create(), the responsebody class converts data to UTF-8 format and UTF-8 does not support characters like (“,”) so it gives us "?" sign because we have given response.body().contentType(), so it converts to UTF-8 which is default.
The solution is to not to pass response.body().contentType() to create() and give our own contentType.
Here is the updated class.
public class CustomRequestInterceptor implements Interceptor {
private static String newToken;
private String bodyString;
private final String TAG = getClass().getSimpleName();
#Override
public Response intercept(Chain chain) throws IOException {
String token = "";
Request request = chain.request();
RequestBody oldBody = request.body();
Buffer buffer = new Buffer();
oldBody.writeTo(buffer);
String strOldBody = buffer.readUtf8();
Log.i(TAG, "original req " + strOldBody);
MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");
JSONObject jsonObject = new JSONObject();
String decodedStr = decoder(strOldBody.replace("data=", ""));
try {
if (decodedStr != null && decodedStr.equalsIgnoreCase("")) {
token = getRandomNumber();
jsonObject.put("auth_token", token);
} else {
jsonObject = new JSONObject(decodedStr);
token = getRandomNumber();
jsonObject.put("auth_token", token);
}
} catch (Exception e) {
Log.e(AppConstants.TAG, "Exception", e);
}
Log.i(AppConstants.TAG, "Request JSONObject " + jsonObject.toString());
String strNewBody = "data=" + URLEncoder.encode(Encryption.encryptString(jsonObject.toString()));
Log.i(TAG, "strNewBody " + strNewBody);
RequestBody body = RequestBody.create(mediaType, strNewBody);
Log.i(TAG, "content type is " + body.contentType().toString());
Log.i(TAG, "content length is " + String.valueOf(body.contentLength()));
Log.i(TAG, "method is " + request.method());
request = request.newBuilder().header("Content-Type", body.contentType().toString())
.header("Content-Length", String.valueOf(body.contentLength()))
.method(request.method(), body).build();
Response response = chain.proceed(request);
String responseString = new String(response.body().bytes());
Log.i(TAG, "Response: " + responseString);
String newResponseString = Encryption.decryptString(responseString);
JSONObject res_JsonObject = new JSONObject();
if (newResponseString.startsWith("{")) {
try {
res_JsonObject = new JSONObject(newResponseString);
String response_token = res_JsonObject.getString("auth_token");
if (response_token.equalsIgnoreCase("" + token)) {
} else {
res_JsonObject.put("status", false);
res_JsonObject.put("message", "Authentication Failed");
Toast.makeText(new AppController().getApplicationContext(), "Authentication Failed", Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
Log.e(AppConstants.TAG, "Exception", e);
}
}
MediaType contentType = MediaType.parse(response.body().contentType() + "; charset=utf-32");
return response.newBuilder()
.body(ResponseBody.create(contentType, newResponseString.getBytes()))
.build();
}
public String decoder(String encodedStr) {
try {
return URLDecoder.decode(encodedStr);
} catch (Exception e) {
Log.e(AppConstants.TAG, "Exception", e);
return encodedStr;
}
}
}

Android Retrofit 2 post request responses with name of response class

In my app I make post request to the server with a special code inside the body. Then I should get some information in the response. However, I always get the name of the response class.
My request code:
#POST("/accounts/login/vk-oauth2/")
Call<RegistrationProcessCodeResponse> postCode(#Body CodePostRequest code);
My ResponseClass:
public class RegistrationProcessCodeResponse {
private String message;
private String partial_token;
private String phase;
public String getMessage() {
return message;
}
public String getPartial_token() {
return partial_token;
}
public String getPhase() {
return phase;
}
public void setMessage(String message) {
this.message = message;
}
public void setPartial_token(String partial_token) {
this.partial_token = partial_token;
}
public void setPhase(String phase) {
this.phase = phase;
}
}
My request code:
HseAlumniApi hseAlumniApi = HseAlumniApi.retrofit.create(HseAlumniApi.class);
Call<RegistrationProcessCodeResponse> postComment = hseAlumniApi.postCode(codePostRequest);
postComment.enqueue(new Callback<RegistrationProcessCodeResponse>() {
#Override
public void onResponse(Call<RegistrationProcessCodeResponse> call, Response<RegistrationProcessCodeResponse> response) {
Log.d("myLogs", "String.valueOf(response.code())\n" + String.valueOf(response.code()));
Log.d("myLogs", "response.body().toString()\n" + response.body().toString());
if (response.isSuccessful()) {
Log.d("myLogs", "Request succeeded");
}
}
#Override
public void onFailure(Call<RegistrationProcessCodeResponse> call, Throwable t) {
Log.d("myLogs", "Request failed");
}
});
My logs:
D/myLogs: String.valueOf(response.code())
200
D/myLogs: response.body().toString()
com.example.vitaly.hsealumni.RegistrationProcessCodeResponse#498e7e7
D/myLogs: Request succeeded
Response Json:
{
"message": "email needed",
"partial_token": "231445d4fc5a4ed99dccb681942d5d7e",
"phase": 1
}
I really have no idea what to do, help please
public class RegistrationProcessCodeResponse {
private String message;
private String partial_token;
private String phase;
public RegistrationProcessCodeResponse() {
message = "";
partial_token = "";
phase = "";
}
// getters and setters
#Override
public String toString() {
return "RegistrationProcessCodeResponse{" +
"message='" + message + '\'' +
", partial_token='" + partial_token + '\'' +
", phase='" + phase + '\'' +
'}';
}
}

Flickr Oauth Android

I want to authorize user from my app, I am following some example found on internet (http://www.programcreek.com/java-api-examples/index.php?api=org.scribe.model.Token):
public static void auth() throws IOException, FlickrException {
Properties properties;
InputStream in=null;
try {
in=AuthExample.class.getResourceAsStream("/setup.properties");
properties=new Properties();
properties.load(in);
}
finally {
IOUtilities.close(in);
}
Flickr flickr=new Flickr(properties.getProperty("apiKey"),properties.getProperty("secret"),new REST());
Flickr.debugStream=false;
AuthInterface authInterface=flickr.getAuthInterface();
Scanner scanner=new Scanner(System.in);
Token token=authInterface.getRequestToken();
System.out.println("token: " + token);
String url=authInterface.getAuthorizationUrl(token,Permission.READ);
System.out.println("Follow this URL to authorise yourself on Flickr");
System.out.println(url);
System.out.println("Paste in the token it gives you:");
System.out.print(">>");
String tokenKey=scanner.nextLine();
Token requestToken=authInterface.getAccessToken(token,new Verifier(tokenKey));
System.out.println("Authentication success");
Auth auth=authInterface.checkToken(requestToken);
System.out.println("Token: " + requestToken.getToken());
System.out.println("nsid: " + auth.getUser().getId());
System.out.println("Realname: " + auth.getUser().getRealName());
System.out.println("Username: " + auth.getUser().getUsername());
System.out.println("Permission: " + auth.getPermission().getType());
}
I am using webview, scribe and Flickr4Java for run URL which provide a code, authenticate and web view shows me a code, which I must pass to my app, but I can't understand how to retrieve this code from webview, and pass to tokenKey.
I am added onpageFinished and print URL which me give:
06-12 13:03:55.266 E/NEW﹕ uri is: https://m.flickr.com/services/oauth/authorize?oauth_token=72157654039925698-81abc00d035f5da0&perms=write
06-12 13:03:55.601 W/BindingManager﹕ Cannot call determinedVisibility() - never saw a connection for the pid: 4581
06-12 13:03:56.166 E/NEW﹕ uri is: https://m.flickr.com/#/services/oauth/authorize/_QM_oauth_token_IS_72157654039925698-81abc00d035f5da0_AND_perms_IS_write
06-12 13:03:56.476 W/BindingManager﹕ Cannot call determinedVisibility() - never saw a connection for the pid: 4581
06-12 13:03:56.476 E/NEW﹕ uri is: https://m.flickr.com/#/services/oauth/authorize/_QM_oauth_token_IS_72157654039925698-81abc00d035f5da0_AND_perms_IS_write
06-12 13:04:00.411 W/BindingManager﹕ Cannot call determinedVisibility() - never saw a connection for the pid: 4581
06-12 13:04:00.416 E/NEW﹕ uri is: https://m.flickr.com/#/#
Finaly, i found an answer (this provide a calback url: token = authInterface.getRequestToken("your calback url");), the code for auth for someone is:
public class FlickrLogin1 extends AsyncTask<String, String, String> {
public final String TAG = FlickrLogin1.class.getSimpleName();
String url;
int count = 0;
#Override
protected void onPreExecute() {
Log.d(TAG, "START");
}
#Override
protected String doInBackground(String... params) {
String result = "";
try {
Flickr.debugRequest = false;
Flickr.debugStream = false;
flickr = new Flickr(flickrKey, flickrSecret, new REST());
authInterface = flickr.getAuthInterface();
token = authInterface.getRequestToken("your calback url");
L("Token: " + token);
result = authInterface.getAuthorizationUrl(token, Permission.WRITE);
return result;
} catch (IllegalStateException e) {
e.printStackTrace();
return result;
} catch (VerifyError e) {
e.printStackTrace();
return result;
}
}
#Override
protected void onPostExecute(String result) {
if (result != null && result.length() > 0) {
L("Follow this URL to authorise yourself on Flickr");
L(result);
auth_dialog = new Dialog(getActivity());
auth_dialog.setContentView(R.layout.auth_dialog);
final WebView web = (WebView) auth_dialog.findViewById(R.id.webv);
web.getSettings().setJavaScriptEnabled(true);
web.loadUrl(result);
web.setWebViewClient(
new WebViewClient() {
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
L("url to start " + url);
if (url.contains("&oauth_verifier")) {
auth_dialog.dismiss();
Uri uri = Uri.parse(url);
String oauth_verifier = uri.getQueryParameter("oauth_verifier");
String oauth_token = uri.getQueryParameter("oauth_token");
new FlickrLogin2().execute(oauth_token, oauth_verifier);
}
}
String authCode;
#Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
L("url to get " + url);
}
});
auth_dialog.show();
auth_dialog.setTitle("Authorize");
auth_dialog.setCancelable(true);
}
}
}
public class FlickrLogin2 extends AsyncTask<String, Void, String> {
#Override
protected void onPreExecute() {
}
#Override
protected String doInBackground(String... oauth_verifier) {
L("CODE " + oauth_verifier[0] + " " + oauth_verifier[1]);
try {
Verifier verifier = new Verifier(oauth_verifier[1]);
Token accessToken = authInterface.getAccessToken(token, verifier);
System.out.println("Authentication success");
Auth auth = new Auth();
authInterface = flickr.getAuthInterface();
Token requestToken = authInterface.getRequestToken();
L("auth tocen and secret: " + requestToken.getToken() + " , " + requestToken.getSecret());
auth.setToken(requestToken.getToken());
auth.setTokenSecret(requestToken.getSecret()); // thats the token I got from the registration, before I set the token of the requestToken
auth.setPermission(Permission.WRITE);
RequestContext requestContext = RequestContext.getRequestContext();
requestContext.setAuth(auth);
flickr.setAuth(auth);
L("checking for token" + accessToken);
auth = authInterface.checkToken(accessToken);
// This token can be used until the user revokes it.
L("Token: " + accessToken.getToken());
L("Secret: " + accessToken.getSecret());
L("nsid: " + auth.getUser().getId());
L("Realname: " + auth.getUser().getRealName());
L("Username: " + auth.getUser().getUsername());
L("Permission: " + auth.getPermission().getType());
} catch (FlickrException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result) {
}
}
Anyone who's struggling to get this to work with more recent version of Android with Kotlin, I have a gist that can be found here.

Categories