Advertisement
Guest User

Untitled

a guest
Jun 21st, 2016
74
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.98 KB | None | 0 0
  1. grant_type=password
  2. password=qwerty
  3. username=administrator
  4.  
  5. public JSONObject getLoginToken(String username, String password) {
  6. URL url = null;
  7. HttpURLConnection httpURLConnection = null;
  8. BufferedReader bufferedReader = null;
  9. JSONObject response = null;
  10.  
  11. try {
  12. url = new URL("someUrl");
  13. httpURLConnection = (HttpURLConnection) url.openConnection();
  14.  
  15. JSONObject data = new JSONObject();
  16. data.put("username", username);
  17. data.put("password", password);
  18. data.put("grant_type", "password");
  19.  
  20. httpURLConnection.setChunkedStreamingMode(0);
  21. httpURLConnection.setRequestMethod("POST");
  22. httpURLConnection.setDoOutput(true);
  23. httpURLConnection.setDoInput(true);
  24.  
  25. httpURLConnection.connect();
  26.  
  27. OutputStream os = httpURLConnection.getOutputStream();
  28. BufferedWriter writer = new BufferedWriter(
  29. new OutputStreamWriter(os, "UTF-8"));
  30. writer.write(URLEncoder.encode(data.toString(), "UTF-8"));
  31. writer.flush();
  32. writer.close();
  33. os.close();
  34.  
  35. bufferedReader = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream())); // <-- fails here
  36.  
  37. StringBuilder sb = new StringBuilder();
  38. String line = null;
  39.  
  40. while ((line = bufferedReader.readLine()) != null) {
  41. sb.append(line + "n");
  42. }
  43.  
  44. response = new JSONObject(sb.toString());
  45. } catch (MalformedURLException e) {
  46. e.printStackTrace();
  47. } catch (IOException e) {
  48. e.printStackTrace();
  49. } catch (JSONException e) {
  50. e.printStackTrace();
  51. } catch (Exception e) {
  52. e.printStackTrace();
  53. } finally {
  54. if (httpURLConnection != null) {
  55. httpURLConnection.disconnect();
  56. }
  57. }
  58.  
  59. return response;
  60. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement