2

I am working on Parsing JSON data from a website then put in into a string. When I tried it in my laptop using home internet, I could run it without any errors. But when I tried to retype the code in my local PC in our office (corporate PC) then ran it, I am getting java.UnknownHostException error. Here is my code snippet:

`  try {
        String url = "https://jsonplaceholder.typicode.com/posts/1";
        URL obj = new URL(url);
        System.out.println(obj);
        HttpURLConnection con = (HttpURLConnection) obj.openConnection();
        // optional default is GET
        con.setRequestMethod("GET");
        // add request header
        con.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 5.1; rv:19.0) Gecko/20100101 Firefox/19.0");
        BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));

        String inputLine;
        StringBuffer response = new StringBuffer();
        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);

        }
        in.close();

        String final_response = response.toString();
        System.out.println(final_response);

    } catch (Exception e) {
        // TODO: handle exception
        System.out.println(e);
    }`

Please do note that we have proxy.

Thank you to those who will answer.

susenj
  • 342
  • 1
  • 4
  • 12
Arian
  • 41
  • 4
  • You can try it using this post. https://stackoverflow.com/questions/14250600/proxy-settings-in-a-java-program – Tran Ho Jun 11 '19 at 05:35
  • @Arian - Can you please check if the url is accessible from your office network. Since it's a get request, you can directly put that URL in browser and execute it. If you are not getting any response, it means it might be blocked by your office network. – Rohit Jun 11 '19 at 05:42
  • Hi @Rohit the URL is accessible when i access it using a browser. – Arian Jun 11 '19 at 05:49
  • Hi guys, i finally found the answer. since my local PC uses a proxy, i just added this line : System.setProperty`("java.net.useSystemProxies", "true");` – Arian Jun 11 '19 at 06:40

2 Answers2

2

i finally found the answer. since my local PC uses a proxy, i just added this line : System.setProperty("java.net.useSystemProxies", "true");

reference: https://memorynotfound.com/configure-http-proxy-settings-java/

Arian
  • 41
  • 4
0

Recommend to move the proxy configuration out of code and use specific attributes at runtime in the JVM configuration ( configure as environment based script if possible )

java -Dhttp.proxyHost=x.x.x.x -Dhttp.proxyPort=ZZZZ -jar fatJar.jar
TechFree
  • 2,600
  • 1
  • 17
  • 18