1

Here is my sample code :

String code = request.getParameter("authcode1");
String clientSecret = "xxxxxxxxxxxxx";
String newUrl = "https://accounts.google.com/o/oauth2/token";
String clientId = "xxxxxxxxxxxxxxx";
String callback = "http://localhost:8080/web/guest/home";

String tokenUrl = new String("https://accounts.google.com/o/oauth2/token");

        StringBuffer params = new StringBuffer("");
        params.append("code=" + URLEncoder.encode(code));
        params.append("&client_id=" + clientId);
        params.append("&client_secret=" + clientSecret);
        params.append("&redirect_uri=" + callback);
        params.append("&grant_type=authorization_code");

        try
        {
            // Send data
            URL url = new URL(tokenUrl.toString());
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("POST");
            conn.setDoOutput(true);
            conn.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
            conn.setRequestProperty("Content-Length", "0");
                conn.connect();

            InputStream is;
            if (conn.getResponseCode() != 200) {
                is = conn.getInputStream();
            } else {
                is = conn.getErrorStream();
            }

            //URLConnection conn = url.openConnection();
            //conn.setDoOutput(true);
            OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
            wr.write(params.toString());
            wr.flush();

            // Get the response
            BufferedReader rd = new BufferedReader(new InputStreamReader(is));
            String line;
            while ((line = rd.readLine()) != null)
            {
                System.out.println("-----" + line);
            }
            wr.close();
            rd.close();
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }

I am getting following exception in Tomcat:

java.io.IOException: Server returned HTTP response code: 400 for URL: https://accounts.google.com/o/oauth2/token
        at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
        at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:39)
        at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:27)
        at java.lang.reflect.Constructor.newInstance(Constructor.java:513)
        at sun.net.www.protocol.http.HttpURLConnection$6.run(HttpURLConnection.java:1368)
        at java.security.AccessController.doPrivileged(Native Method)
        at sun.net.www.protocol.http.HttpURLConnection.getChainedException(HttpURLConnection.java:1362)

Please help me what am I doing wrong here? why I am getting java.io.IOException: HTTP response code: 400 for URL exception?

2
  • 1
    Have you checked what 400 means ? did you try it through the browser. Check this :?checkupdown.com/status/E400.html Commented Jun 11, 2012 at 7:38
  • 2
    When conn.getResponseCode() != 200 you will process the input stream ? That should'nt be reverse ? Commented Jun 11, 2012 at 7:39

1 Answer 1

3

First of all, this is incorrect:

if (conn.getResponseCode() != 200) {
                is = conn.getInputStream();
            } else {
                is = conn.getErrorStream();
            }

It should be

if (conn.getResponseCode() == 200) {
                is = conn.getInputStream();
            } else {
                is = conn.getErrorStream();
            }

Your issue is on this line:

conn.setRequestProperty("Content-Length", "0");

You can't send a Content-Length of 0 when you have entity body appended in HTTP message.

Rather, set it as

conn.setRequestProperty("Content-Length", params.toString().length());
Sign up to request clarification or add additional context in comments.

5 Comments

Thanks for all comments. I did change content-length to params.toString.length() and conn.getResponseCode() == 200 but now I am getting java.net.ProtocolException: Cannot write output after reading input. at sun.net.www.protocol.http.HttpURLConnection.getOutputStream(HttpURLConnection.java:900) at sun.net.www.protocol.https.HttpsURLConnectionImpl.getOutputStream(HttpsURLConnectionImpl.java:230) I get exception at line : OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream()); whats wrong here?
It simple. You first write to OutputStream before reading from InputStream. You are doing the inverse.
@The Elite Gentleman.Thanks. Now I got access_token from server successfully.
Then accept the answer (tick mark below the score) to approve the answer really helped you.
@user1443749 You don't need to set the Content-Length at all. Java will do it for you. Correctly. Anything you set yourself is likely to be wrong. Especially zero.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.