【发布时间】:2015-09-07 16:19:25
【问题描述】:
我发现使用 apache http 客户端在 Java 中执行简单的 http 请求很困难。该请求是对以下 URL http://109.231.121.64:20622/v1/collections/S4C/objects/OpsConfig/data(当前已启动并正在运行)的简单 GET。使用 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 中执行相同操作时,会返回 500 秒的 http 错误状态。这是我正在使用的代码:
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 的输出/详细信息。
-
你遇到了什么“问题”?请在帖子中添加任何异常堆栈跟踪
-
抱歉给他们打电话有问题,我编辑了帖子并添加了 curl -v 的输出。
标签: java curl httpclient