0

I wanted to get the response from the server with the following code

(This is the part where it connects)

        InputStream is = new URL(url + "?p=" + pnb).openStream();
        while (is.available() > 0)
            out[i++] = (char) is.read();

Why does it crash with java.io.IOException: Server returned HTTP response code: 403 for URL: http://172.18.19.16:32000/php/test.php?p=662 when it works when i type that very line into a browser?

2xsaiko
  • 1,043
  • 10
  • 14
  • Did you try to browse the url with your browser? Does it return error 403? If it doesn't, try [setting the User Agent](http://stackoverflow.com/questions/2529682/setting-user-agent-of-a-java-urlconnection) – BackSlash Dec 09 '14 at 18:27
  • _when it works when i type that very line into a browser?_ Yes i did. hm ok ill try with the user agent – 2xsaiko Dec 09 '14 at 18:29
  • Sorry, I missed that part. Then, if it works with the browser, it's most likely an User Agent issue: the browser sets it for you, java doesn't. – BackSlash Dec 09 '14 at 18:31
  • Hmm, this URLConnection conn = new URL(url + "?p=" + pnb).openConnection(); conn.setRequestProperty("User-Agent", "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:34.0) Gecko/20100101 Firefox/34.0"); InputStream is = conn.getInputStream(); while (is.available() > 0) out[i++] = (char) is.read(); doesn't work, return same error. – 2xsaiko Dec 09 '14 at 18:34
  • @HardcodedCat set properties before opening connection – Adil Shaikh Dec 09 '14 at 18:35
  • @HardcodedCat see this post, http://stackoverflow.com/questions/15845075/set-user-agent-property-in-https-connection-header – Adil Shaikh Dec 09 '14 at 18:42

2 Answers2

0

403 is Forbidden --> http://en.wikipedia.org/wiki/HTTP_403

Sometimes it may happen that some websites look for referrer or some other parameter (like user-agent) with the request, and if they do not see those particular parameters they simply respond with an error (In your case it's 403). The same link may open fine on browser, as browser sends additional data with the request which you are not sending with your custom request.

Adil Shaikh
  • 44,509
  • 17
  • 89
  • 111
0

I solved it using this:

        URL u = new URL(url + "?p=" + pnb);
        URLConnection conn = u.openConnection();
        conn.setRequestProperty("User-Agent", "Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.4; en-US; rv:1.9.2.2) Gecko/20100316 Firefox/3.6.2");
        conn.connect();
        InputStream is = conn.getInputStream();

It works perfectly. Thanks @Mohammad Adil for helping me out

2xsaiko
  • 1,043
  • 10
  • 14