我发现难以使用apache http客户端在Java中执行简单的http请求。该请求是一个简单的GET朝向以下url http://109.231.121.64:20622/v1/collections/S4C/objects/OpsConfig/data(目前正在运行)。请求成功使用curl如以下:Java Apache HTTP客户端失败,并发出http请求,其中cURL成功
curl -v -X GET http://109.231.121.64:20622/v1/collections/S4C/objects/OpsConfig/data > s4cOpsInitModel.xml
这是输出:
* Hostname was NOT found in DNS cache
* Trying 109.231.121.64...
% Total % Received % Xferd Average Speed Time Time Time Current
Dload Upload Total Spent Left Speed
0 0 0 0 0 0 0 0 --:--:-- --:--:----:--:-- 0* Connected to 109.231.121.64 (109.231.121.64) port 20622 (#0)
> GET /v1/collections/S4C/objects/OpsConfig/data HTTP/1.1
> User-Agent: curl/7.35.0
> Host: 109.231.121.64:20622
> Accept: */*
>
< HTTP/1.1 200 OK
< connection: keep-alive
* Server Cowboy is not blacklisted
< server: Cowboy
< date: Tue, 08 Sep 2015 08:11:22 GMT
< content-length: 2349
< content-type: application/octet-stream
<
{ [data not shown]
100 2349 100 2349 0 0 27819 0 --:--:-- --:--:----:--:-- 27964
* Connection #0 to host 109.231.121.64 left intact
但随后做同样的,当Java中的HTTP错误状态500秒返回。这里是我使用的代码:
try {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet getRequest = new HttpGet(
"http://109.231.121.64:20622/v1/collections/S4C/objects/OpsConfig/data");
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();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
我看过谷歌,但我无法弄清楚发生了什么。我的猜测是接受的内容类型有问题,但我试图设置不同类型的内容类型而不成功。你有什么想法我做错了吗?谢谢大家。
curl -verbose -silent?为什么? –
请检查/提供curl中的输出/详细信息。 –
你有什么“问题”?请添加任何异常stacktrace到帖子 – wero