我正在从BufferReader
创建一个InputStreamReader
来加载来自webservice的响应,如下所示:
HttpURLConnection c = (HttpURLConnection) new URL(url).openConnection();
try {
InputStream in = c.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
// returns null
String line = reader.readLine();
// correctly instantiates Article object
Article article = new Gson().fromJson(reader, Article.class);
但是,出于某种原因,reader.readLine();
返回null
,虽然数据成功来自服务器 - 我知道因为Article对象是从返回的JSON中正确实例化的。返回null
的原因是什么?
答案 0 :(得分:1)
File file = new File("plugin.yml");
BufferedReader reader = new BufferedReader(new FileReader(file));
String line;
while((line = reader.readLine()) != null) {
System.out.println(line);
}
reader.close();
我知道,你已经说过用System.out.println(东西)测试了一切,但我仍然会问最基本的问题,也许问题隐藏在那里的某个地方: 它甚至进入方法吗? 文件是否正确拼写(也是从日志添加到日志的位置)? 如果您使用扫描仪读取文件,它是否有效?
Scanner scan = new Scanner(file);
String line;
while(scan.hasNextLine()) {
line = scan.nextLine();
//...
}
scan.close();
这些可能都是愚蠢的问题,但它可能会有所帮助。至于现在,我在代码中看不到任何问题。
答案 1 :(得分:0)
我认为您错过了将连接输出设置为true。 此外,我会这样做:
try {
URL url = new URL("http://im-an-url.com");
HttpURLConnection c = (HttpURLConnection) url.openConnection();
c.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(c.getOutputStream());
//do whatever you like here with the StreamWriter
wr.close()
}
答案 2 :(得分:0)
HttpURLConnection c = (HttpURLConnection) new URL(url).openConnection();
try {
c.connect();
if (c.getResponseCode == 200) {
InputStream in = c.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
// returns null
String line = reader.readLine();
// correctly instantiates Article object
Article article = new Gson().fromJson(reader, Article.class);
}
如果使用readLine方法,请确保网络流具有结束标记\ r \ n,或者您可以使用BufferOutputStream