curl工作正常,但在Java中调用api时会出现IOException

时间:2015-05-25 23:09:49

标签: java api curl

我正在尝试访问以下网址的数据: http://staging.api.syncromatics.com/portal/routes/710/vehicles?api-key=MY_KEY_HERE

如果我卷曲网址,一切正常。但是当我尝试从Java中执行get请求时,我得到一个IOException,说HTTP响应代码是401,这是一个授权错误。我已将accept标头设置为与curl -v http://staging.api.syncromatics.com/portal/routes/710/vehies?api-key=MY_KEY_HERE的打印输出完全相同。

这是踢球者,这是这个api发生这种情况的唯一途径。所有其他路线都可以正常工作。有什么想法可能导致这个?在此先感谢您的帮助。

编辑:这是我一直在使用的代码。

public String getData(final URL url, final String ticket) throws IOException {
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();

    String returnData="";

    connection.setDoOutput(true);
    connection.setRequestProperty("Accept-Encoding", "gzip");
    connection.setRequestProperty("Accept", "application/json");
    connection.setRequestProperty("User-Agent", "curl/7.19.7 (x86_64-redhat-linux-gnu) libcurl/7.19.7 NSS/3.15.3 zlib/1.2.3 libidn/1.18 libssh2/1.4.2");
    connection.setRequestMethod("GET");

    final InputStream replyStream = connection.getInputStream();
    final InputStreamReader inputStreamReader;

    // The following is to check if the server sending the response supports
    // Gzip
    final String contentEncodingField = connection.getHeaderField("Content-Encoding");
    if (contentEncodingField != null && contentEncodingField.equalsIgnoreCase("gzip")) {
        // read the gzipped format
        final GZIPInputStream gzipInputStream = new GZIPInputStream(replyStream);
        inputStreamReader = new InputStreamReader(gzipInputStream);
    } else {
        inputStreamReader = new InputStreamReader(replyStream);
    }

    final BufferedReader reader = new BufferedReader(inputStreamReader);
    String line;
    while ((line = reader.readLine()) != null) {
        returnData += line; //System.out.println(line);
    }
    reader.close();
    return returnData;
}

0 个答案:

没有答案