有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

Java Apache HTTP客户端通过HTTP请求失败,其中cURL成功

我发现使用ApacheHTTP客户端在Java中执行简单的http请求很困难。该请求是对以下url http://109.231.121.64:20622/v1/collections/S4C/objects/OpsConfig/data(当前正在运行)的简单获取。使用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();
}    

我在谷歌上看了一下,但我不知道发生了什么。我的猜测是,接受的内容类型有问题,但我试图设置不同类型的内容类型,但没有成功。你知道我做错了什么吗?提前谢谢大家


共 (0) 个答案