我正在从网站解析 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);
}`
请注意,我们有代理。
谢谢那些会回答的人。