Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- grant_type=password
- password=qwerty
- username=administrator
- public JSONObject getLoginToken(String username, String password) {
- URL url = null;
- HttpURLConnection httpURLConnection = null;
- BufferedReader bufferedReader = null;
- JSONObject response = null;
- try {
- url = new URL("someUrl");
- httpURLConnection = (HttpURLConnection) url.openConnection();
- JSONObject data = new JSONObject();
- data.put("username", username);
- data.put("password", password);
- data.put("grant_type", "password");
- httpURLConnection.setChunkedStreamingMode(0);
- httpURLConnection.setRequestMethod("POST");
- httpURLConnection.setDoOutput(true);
- httpURLConnection.setDoInput(true);
- httpURLConnection.connect();
- OutputStream os = httpURLConnection.getOutputStream();
- BufferedWriter writer = new BufferedWriter(
- new OutputStreamWriter(os, "UTF-8"));
- writer.write(URLEncoder.encode(data.toString(), "UTF-8"));
- writer.flush();
- writer.close();
- os.close();
- bufferedReader = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream())); // <-- fails here
- StringBuilder sb = new StringBuilder();
- String line = null;
- while ((line = bufferedReader.readLine()) != null) {
- sb.append(line + "n");
- }
- response = new JSONObject(sb.toString());
- } catch (MalformedURLException e) {
- e.printStackTrace();
- } catch (IOException e) {
- e.printStackTrace();
- } catch (JSONException e) {
- e.printStackTrace();
- } catch (Exception e) {
- e.printStackTrace();
- } finally {
- if (httpURLConnection != null) {
- httpURLConnection.disconnect();
- }
- }
- return response;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement