-1

I am learning to how to use http request. The following is the code which return JSON. All I am doing is to get it and print it. But I am facing some error. The error is also given below.

import java.io.*;
import java.net.*;

public class ZipTester {

    public static void main(String[] args) throws IOException {
        // TODO Auto-generated method stub

        URL stck = new URL("http://www.zipfeeder.us/zip?key=Ect9O9ta&zips=14623");
        URLConnection yc = stck.openConnection();
        BufferedReader in = new BufferedReader(new InputStreamReader(yc.getInputStream()));
        String inputLine;
        String add="";
        while ((inputLine = in.readLine()) != null) {
            //System.out.println(inputLine);
            add=add+inputLine;
        }
        in.close();
        System.out.println(add);

    }

}

This is the error. In my old machine this code worked perfectly fine. I just got a new machine this week. The same code is now not working. previously I was using jdk 1.7 and now i am using jdk 1.8

Exception in thread "main" java.io.IOException: Server returned HTTP response code: 403 for URL: http://www.zipfeeder.us/zip?key=Ect9O9ta&zips=14623
    at sun.net.www.protocol.http.HttpURLConnection.getInputStream0(Unknown Source)
    at sun.net.www.protocol.http.HttpURLConnection.getInputStream(Unknown Source)
    at ZipTester.main(ZipTester.java:11)
Roman C
  • 49,761
  • 33
  • 66
  • 176
user3342812
  • 343
  • 8
  • 25

2 Answers2

0

You can fix your code with adding user-agent header like this :

yc.addRequestProperty("User-Agent",""); //to avoid 403 error

The website had probably change it access rules and now it request a "user-agent".

The full code :

import java.io.*;
import java.net.*;

public class ZipTester {

    public static void main(String[] args) throws IOException {
        // TODO Auto-generated method stub

        URL stck = new URL("http://www.zipfeeder.us/zip?key=Ect9O9ta&zips=14623");
        URLConnection yc = stck.openConnection();
        yc.addRequestProperty("User-Agent",""); //to avoid 403 error
        BufferedReader in = new BufferedReader(new InputStreamReader(yc.getInputStream()));
        String inputLine;
        String add="";
        while ((inputLine = in.readLine()) != null) {
            add=add+inputLine;
        }
        in.close();
        System.out.println(add);

    }

}

I hope it will help you.

Regards.

DenisJ
  • 1
0

I fixed this issue by setting the user agent with a following value:

yc.setRequestProperty("User-Agent","Mozilla/5.0");
skuntsel
  • 11,624
  • 11
  • 44
  • 67
Tim
  • 100
  • 1
  • 4