我试图从这个api返回一个JSON字符串: https://market.mashape.com/pareshchouhan/trivia
然而,Java正在抛出错误:java.io.FileNotFoundException: https://pareshchouhan-trivia-v1.p.mashape.com/v1/getAllQuizQuestions?limit=10&page=1
在线
br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
我使用了与其他Rest API类似的代码,所以我有点不确定为什么会这样。
static String jsonStr;
String data = "";
@Override
protected Void doInBackground(Void... params) {
BufferedReader br = null;
try {
URL url;
String urlStr = "https://pareshchouhan-trivia-v1.p.mashape.com/v1/getAllQuizQuestions?limit=10&page=1";
url = new URL(urlStr);
URLConnection connection = url.openConnection();
connection.setRequestProperty("X-Mashape-Key", "4OFryNEYTWmshe8GheSnmIVEj7gZp1kJf6cjsncjVhXj9WYACn");
connection.setRequestProperty("Accept", "application/json");
connection.setDoOutput(true);
OutputStreamWriter outputStreamWr = new OutputStreamWriter(connection.getOutputStream());
outputStreamWr.write(data);
outputStreamWr.flush();
br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = null;
while((line = br.readLine())!=null) {
sb.append(line);
sb.append(System.getProperty("line.separator"));
}
jsonStr = sb.toString();
} catch (Exception e){
e.printStackTrace();
}
return null;
}
非常感谢任何帮助。 问候。
答案 0 :(得分:0)
原来我试图执行错误类型的请求。此特定API不支持Get请求。使用https://www.hurl.it/
发现了这一点无论如何,使用此处的教程: http://www.mkyong.com/java/how-to-send-http-request-getpost-in-java/ 我能够更改请求类型并提取正确的数据。
希望这有帮助。