我正在尝试使用Apache HttpClient从站点的API获取JSON响应,但是它给了我一个“IllegalStateException:目标主机不能为null,或者在参数中设置。”
Java代码:
private String orderInURL = "https://r-test.ordr.in";
public String deliveryList(String datetime, String zip, String city, String addr) throws ClientProtocolException, IOException {
String listURL = orderInURL+"/dl/" + datetime + "/" + zip + "/" + city + "/" +
addr + "?_auth=1," + this.privateKey;
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet getRequest = new HttpGet(URLEncoder.encode(listURL, "UTF-8"));
//header
getRequest.setHeader("accept", "application/json");
HttpResponse response = httpClient.execute(getRequest);
if (response.getStatusLine().getStatusCode() != 200) {
throw new RuntimeException("Failed : HTTP error code : "
+ response.getStatusLine().getStatusCode());
}
BufferedReader br = new BufferedReader(
new InputStreamReader((response.getEntity().getContent())));
String output;
System.out.println("Output from Server .... \n");
while ((output = br.readLine()) != null) {
System.out.println(output);
}
httpClient.getConnectionManager().shutdown();
return output;
}
....
System.out.println(orderin.deliveryList("ASAP", "11111", "MyCity", "100 My Address"));
GET网址原为:
https://r-test.ordr.in/dl/ASAP/11111/MyCity/100%20My%20Address?_auth=1,XXXXXXXXXXXXXXXXX
如果用私钥替换XXXXXXXXX ....如果我只是复制了这个URL并将其放入浏览器中,那么返回正确的JSON。我不知道为什么它不能在Java中返回正确的结果。任何帮助表示赞赏。
答案 0 :(得分:0)
不确定问题是什么,但有一种更简单的方法从URL读取JSON。尝试这样的事情:
public static String readJsonFromUrl(String url) throws IOException
{
InputStream is = new URL(url).openStream();
try {
BufferedReader rd = new BufferedReader(
new InputStreamReader(is, Charset.forName("UTF-8")));
String jsonText = readAll(rd);
return jsonText;
} finally {
is.close();
}
return "";
}
private static String readAll(Reader rd) throws IOException
{
StringBuilder sb = new StringBuilder();
int cp;
while ((cp = rd.read()) != -1) {
sb.append((char) cp);
}
return sb.toString();
}
答案 1 :(得分:0)
rfc2616要求HTTP 1.1服务器在没有主机标头的情况下拒绝HTTP请求,请参阅rfc2616第14.23节。
在调用httpClient.execute
之前尝试添加以下行:
getRequest.setHeader("host", "r-test.ordr.in");