Advertisement
Guest User

Untitled

a guest
Feb 15th, 2019
75
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 3.02 KB | None | 0 0
  1. @Override
  2. protected String doInBackground(Context... contexts) {
  3. // get the string from params, which is an array
  4. Context context = contexts[0];
  5. System.out.println("Got context: " + context.toString());
  6.  
  7. // Do something that takes a long time, for example:
  8. OkHttpClient client = new OkHttpClient();
  9. /* if (BuildConfig.DEBUG) {
  10. client.interceptors().add(new LoggingInterceptor());
  11. } */
  12.  
  13. System.out.println("Created new OkHttpClient");
  14.  
  15. try {
  16. InputStream inputStream = context.getResources().openRawResource(R.raw.keys);
  17. String jsonString = new Scanner(inputStream).useDelimiter("\\A").next();
  18. JSONObject object = (JSONObject) new JSONTokener(jsonString).nextValue();
  19. String CLIENT_ID = object.optString("client_id");
  20. String REDIRECT_URI = object.optString("redirect_uri");
  21. String CLIENT_SECRET = object.optString("client_secret");
  22. String AUTHORIZATION_CODE = object.optString("authorization_code");
  23. String GRANT_TYPE = object.optString("grant_type");
  24. String TARGET_URL = object.optString("token_target_url");
  25. System.out.println("Got everything from keys.json");
  26.  
  27. RequestBody bodyBuilder = new FormBody.Builder()
  28. .addEncoded("client_secret", CLIENT_SECRET)
  29. .addEncoded("client_id", CLIENT_ID)
  30. .add("code", AUTHORIZATION_CODE)
  31. .add("grant_type", GRANT_TYPE)
  32. .add("redirect_uri", REDIRECT_URI)
  33. .build();
  34. System.out.println("Built body: " + bodyBuilder.toString());
  35.  
  36. // String mediaTypeString = "application/x-www-form-urlencoded";
  37. // MediaType mediaType = MediaType.parse(mediaTypeString);
  38. // RequestBody body = RequestBody.create(mediaType, bodyBuilder.toString());
  39.  
  40. Request request = new Request.Builder()
  41. .url(TARGET_URL)
  42. .post(bodyBuilder)
  43. // .addHeader("content-type", mediaTypeString)
  44. .addHeader("cache-control", "no-cache")
  45. .build();
  46.  
  47. try {
  48. System.out.println("Starting request.");
  49. Response response = client.newCall(request).execute();
  50. String targetUrl = request.url().toString() + bodyToString(request);
  51. System.out.println("request: " + targetUrl);
  52. String responseBodyString = response.body().string();
  53. System.out.println("response: " + responseBodyString);
  54. return responseBodyString;
  55. } catch (IOException ex) {
  56. System.out.println("Oof. IOException - take a look! " + ex);
  57. }
  58.  
  59. return "Error in getting access token.";
  60. } catch (JSONException e) {
  61. e.printStackTrace();
  62. }
  63.  
  64. return "Error in getting keys.json";
  65.  
  66. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement