0

                     THE CODE IN BELOW IS THE SOLUTION

I am trying to send a json object with multiple elements to a social media app to get a token(I need to provide username/password) and get a token. I searched all over SO and find some questions similar to this and try to implement them but with each of them it ends up with bad request(meaning not the expected json) Here is my last try with respect to this question. And I know it should return status code 200 because I tried it in rest advanced client. Sending a JSON HTTP POST request from Android

Here is the code I tried in various different ways.

HttpURLConnection urlConnection=null;
        try {
            URL url = new URL(http);
            urlConnection = (HttpURLConnection) url.openConnection();
            urlConnection.setDoOutput(true);
            urlConnection.setRequestMethod("POST");
            urlConnection.setRequestProperty("Content-Type","application/json");
            urlConnection.setRequestProperty("user-agent","Agent/1");
            urlConnection.connect();

            //Create JSONObject here
            JSONObject jsonParam = new JSONObject();
            jsonParam.put("username", mJidView.getText().toString());
            jsonParam.put("password",mJidView.getText().toString());
            OutputStreamWriter out = new   OutputStreamWriter(urlConnection.getOutputStream());
            out.write(jsonParam.toString());
            out.close();

            int HttpResult =urlConnection.getResponseCode();
            if(HttpResult ==HttpURLConnection.HTTP_OK){
                BufferedReader br = new BufferedReader(new InputStreamReader(
                        urlConnection.getInputStream(),"utf-8"));
                String line = null;
                while ((line = br.readLine()) != null) {
                    sb.append(line + "\n");
                }
                br.close();

                System.out.println(""+sb.toString());

            }else{
                System.out.println(urlConnection.getResponseMessage());
            }
        } catch (MalformedURLException e) {

            e.printStackTrace();
        }
        catch (IOException e) {

            e.printStackTrace();
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }finally{
            if(urlConnection!=null)
                urlConnection.disconnect();
        }

Note: The application requires a header for user-agent and its signature is here.

- Request body:
{"username": "test", "password": "12345"}
Community
  • 1
  • 1
Prethia
  • 1,183
  • 3
  • 11
  • 26
  • you know that you are sending `"%7B%22username%22%3A+%22test%22%7D%7B%22password%22%3A+%2212345%22%7D"` instead `{"username": "test", "password": "12345"}` ? ... you should start to learn some basics first and Stackoverflow is not tutorial website ... why you are using URLEncoder? why you are creating 2 json objects? why you are using DataOutputStream ? – Selvin Dec 20 '16 at 00:05
  • Well I do not have prior knowledge about jsons that is why I am asking it btw I think I got the whole concept wrong and realized it now so I am updating the code drastically. – Prethia Dec 20 '16 at 00:11
  • I did the changes. Well I would not consider myself as a beginner who searches hopelessly for stackoverflow tutorials since I am a graduate and I ve a working experience but, I did not worked with android studio and json before so I am kind of confused. – Prethia Dec 20 '16 at 00:17
  • :) I see that you get it by your own ... and about unauthorized error ... well it's hard to say without knowladge about this api ... **edit** pasword and username in your code are the same ... learn how to debug ... do some logs ..fx log `jsonParam.toString()` @Prethia – Selvin Dec 20 '16 at 00:26
  • see: `jsonParam.put("username", mJidView.getText().toString()); jsonParam.put("password",mJidView.getText().toString());` ... anyway I would use okhttp3 library instead ... [post example](https://github.com/square/okhttp/blob/master/samples/guide/src/main/java/okhttp3/recipes/PostString.java) + [cutome headers](https://github.com/square/okhttp/blob/master/samples/guide/src/main/java/okhttp3/recipes/AccessHeaders.java) – Selvin Dec 20 '16 at 00:31
  • Well thanks for the comment, this was a very stupid mistake from me, I realized it when you copy pasted jsonParam.put("username", mJidView.getText().toString()); jsonParam.put("password",mJidView.getText().toString()); – Prethia Dec 20 '16 at 00:46
  • password should be an another view. With that I get a success. I will keep the question so an another person can use this solution. I could not find a code like this in SO which accomplishes this – Prethia Dec 20 '16 at 00:50

0 Answers0