【发布时间】:2013-12-07 12:51:07
【问题描述】:
我正在尝试在 Java 命令行中从 Google 自定义搜索中输出一些结果(标题、网址)以进行测试,但我不断收到 java.io.EOFException 错误。编译器列出了有问题的行,但我不知道要改变什么,即使花了几个小时寻找答案。我从 Stack Overflow 上的一个现有问题中获取了大部分代码。任何帮助表示赞赏。
package google.api.search;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import com.google.gson.Gson;
class GSearch {
public static void main(String args[]) throws IOException {
String key = ""; //replace with API key
String qry = ""; // search key word
String cx = ""; //replace with cx
URL url = new URL ("https://www.googleapis.com/customsearch/v1?key=" +key+ "&cx=" +cx+ "&q=" +qry+ "&alt=json");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("Accept","application/json");
BufferedReader br = new BufferedReader(new InputStreamReader ( ( conn.getInputStream() ) ) );
String output;
{while ((output = br.readLine()) != null){
GResults results = new Gson().fromJson(output, GResults.class);
System.out.println(results);
}
conn.disconnect();
}
}
}
GResults 类:
public class GResults {
String title;
String link;
public GResults(String title, String link) {
this.title = title;
this.link = link;
}
public String getTitle(){
return title;
}
public String getLink(){
return link;
}
public void setTitle(String title){
this.title = title;
}
public void setLink(String link){
this.link = link;
}
public String toString(){
return ("Title:%s, Link:%s", title, link);
}
}
错误行:
GResults results = new Gson().fromJson(output, GResults.class);
错误信息:
Exception in thread "main" com.google.gson.JsonSyntaxException: java.io.EOFException: End of input at line 1 column 2
at com.google.gson.Gson.fromJson(Gson.java:813)
at com.google.gson.Gson.fromJson(Gson.java:768)
at com.google.gson.Gson.fromJson(Gson.java:717)
at com.google.gson.Gson.fromJson(Gson.java:689)
at google.api.search.GSearch.main(GSearch.java:26)
Caused by: java.io.EOFException: End of input at line 1 column 2
at com.google.gson.stream.JsonReader.nextNonWhitespace(JsonReader.java:1377)
at com.google.gson.stream.JsonReader.doPeek(JsonReader.java:483)
at com.google.gson.stream.JsonReader.hasNext(JsonReader.java:403)
at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.read(ReflectiveTypeAdapterFactory.java:166)
at com.google.gson.Gson.fromJson(Gson.java:803)
... 4 more
【问题讨论】:
-
能否请您发布完整的堆栈跟踪以及出现错误的行?
-
我已按要求添加了错误消息。
标签: java json gson google-custom-search