我一直试图"下载" json成为一个字符串,但问题是我使用(http://trolasi.readthedocs.io/en/latest/)的API需要获取请求标头Accept设置为application / json,否则它返回HTML而不是json。我尝试设置setRequestProperty,当我调试它看起来实际上设置了标头但由于某种原因它仍然返回HTML。这不是网站的错,因为我尝试使用Postman的API,它工作正常。这是我的代码:
private static String readUrl(String urlString) throws Exception {
BufferedReader reader = null;
try {
URL url = new URL(urlString);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestProperty("Accept", "application/json");
reader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
StringBuffer buffer = new StringBuffer();
int read;
char[] chars = new char[1024];
while ((read = reader.read(chars)) != -1)
buffer.append(chars, 0, read);
return buffer.toString();
} finally {
if (reader != null)
reader.close();
}
}
我希望我已经足够具体了
答案 0 :(得分:0)
可能是对象变异,我通过这种方式,
public String getJSON(String url, int timeout) {
HttpURLConnection c = null;
try {
URL u = new URL(url);
c = (HttpURLConnection) u.openConnection();
c.setRequestMethod("GET");
c.setRequestProperty("Content-length", "0");
c.setUseCaches(false);
c.setAllowUserInteraction(false);
c.setConnectTimeout(timeout);
c.setReadTimeout(timeout);
c.connect();
int status = c.getResponseCode();
switch (status) {
case 200:
case 201:
BufferedReader br = new BufferedReader(new InputStreamReader(c.getInputStream()));
StringBuilder sb = new StringBuilder();
String line;
while ((line = br.readLine()) != null) {
sb.append(line+"\n");
}
br.close();
return sb.toString();
}
} catch (MalformedURLException ex) {
Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, ex);
} finally {
if (c != null) {
try {
c.disconnect();
} catch (Exception ex) {
Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, ex);
}
}
}
return null;
}
这是一个函数,更通用,在函数的第一个参数中传递你的url,第二个,传递你想要击中该url的毫秒数。
答案 1 :(得分:0)
邮递员:邮递员在内部使用重定向,打开 拦截器和关闭设置中常规选项卡下的重定向
YourCode:将网址更改为安全网址,使用协议https
希望这会有所帮助:)