2

我正在从网站解析 JSON 数据,然后将其放入字符串中。当我在使用家庭互联网的笔记本电脑上尝试它时,我可以毫无错误地运行它。但是,当我尝试在我们办公室(公司 PC)的本地 PC 中重新输入代码然后运行它时,我遇到了java.UnknownHostException错误。这是我的代码片段:

`  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);
    }`

请注意,我们有代理。

谢谢那些会回答的人。

4

2 回答 2

2

我终于找到了答案。由于我的本地 PC 使用代理,我刚刚添加了这一行:System.setProperty("java.net.useSystemProxies", "true");

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

于 2019-06-11T06:41:52.480 回答
0

建议将代理配置移出代码并在运行时在 JVM 配置中使用特定属性(如果可能,配置为基于环境的脚本)

java -Dhttp.proxyHost=x.x.x.x -Dhttp.proxyPort=ZZZZ -jar fatJar.jar
于 2019-06-11T07:19:19.843 回答