我试图从网址获取json对象:
http://www.alfanous.org/jos2?action=search&unit=aya&fuzzy=True&query=حم
然而,当我使用该url运行我的代码时,我得到了一个空的json,当我从浏览器请求url时,josn被填充。
我的代码出了什么问题?
URL url = new URL("http://www.alfanous.org/jos2?action=search&unit=aya&fuzzy=True&query=حم");
URLConnection conn = url.openConnection();
InputStream is = conn.getInputStream();
Scanner scan = new Scanner(is);
while (scan.hasNextLine()) {
System.out.println(scan.nextLine());
}
我也试过
// Create URL object
URL obj = new URL("http://www.alfanous.org/jos2?action=search&unit=aya&fuzzy=True&query=حم");
// Communicate with the URL by HTTP
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
// optional default is GET
con.setRequestMethod("GET");
// add request header
con.setRequestProperty("User-Agent", "Mozilla/5.0");
// Getting response data
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
System.out.println(response.toString());
答案 0 :(得分:1)
解决方案是在将url字符串传递给URL
构造函数之前对其进行编码。
String urlstring = "http://www.alfanous.org/jos2?action=search&unit=aya&fuzzy=True&query=حم";
URLEncoder.encode(urlstring, "UTF-8");
URL url = new URL(urlstring);
然后继续使用原始帖子中显示的上一个代码。
URLConnection conn = url.openConnection();
InputStream is = conn.getInputStream();
Scanner scan = new Scanner(is);
while (scan.hasNextLine()) {
System.out.println(scan.nextLine());
}
道德是......我应该在使用它之前对网址进行编码!
答案 1 :(得分:0)
尝试使用BufferedReader
,如下所示:
URL url = new URL("http://www.alfanous.org/jos2?action=search&unit=aya&fuzzy=True&query=حم");
URLConnection conn = url.openConnection();
BufferedReader br =new BufferedReader(new InputStreamReader(conn.getInputStream()));
while ((thisLine = br.readLine()) != null) {
System.out.println(thisLine);
}