在Apache Http Client Java中传递用户名/密码,类似于CURL

时间:2014-01-30 05:57:06

标签: curl apache-httpclient-4.x

我有一个特定的CURL请求网址,如下所示

curl -XGET -ukey:sec https://api.calltrackingmetrics.com/api/v1/accounts/-your-account/calls.json

我有钥匙和秒(秘密)和我在一起。请帮助我使用Apache HTTP Client版本4.3将相同的CURL调用转换为Java中的HTTP请求。当我尝试编写示例代码时,我得到以下异常。

Exception in thread "main" org.apache.http.conn.HttpHostConnectException: Connect to api.calltrackingmetrics.com:443 [api.calltrackingmetrics.com/166.78.112.169, api.calltrackingmetrics.com/198.61.173.12] failed: Connection refused: connect
    at org.apache.http.impl.conn.HttpClientConnectionOperator.connect(HttpClientConnectionOperator.java:138)
    at org.apache.http.impl.conn.PoolingHttpClientConnectionManager.connect(PoolingHttpClientConnectionManager.java:314)
    at org.apache.http.impl.execchain.MainClientExec.establishRoute(MainClientExec.java:363)
    at org.apache.http.impl.execchain.MainClientExec.execute(MainClientExec.java:219)
    at org.apache.http.impl.execchain.ProtocolExec.execute(ProtocolExec.java:195)
    at org.apache.http.impl.execchain.RetryExec.execute(RetryExec.java:85)
    at org.apache.http.impl.execchain.RedirectExec.execute(RedirectExec.java:108)
    at org.apache.http.impl.client.InternalHttpClient.doExecute(InternalHttpClient.java:186)
    at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:82)
    at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:106)
    at com.test.callmetrics.mains.CallMetricsTester.main(CallMetricsTester.java:35)
Caused by: java.net.ConnectException: Connection refused: connect
    at java.net.DualStackPlainSocketImpl.connect0(Native Method)
    at java.net.DualStackPlainSocketImpl.socketConnect(Unknown Source)
    at java.net.AbstractPlainSocketImpl.doConnect(Unknown Source)
    at java.net.AbstractPlainSocketImpl.connectToAddress(Unknown Source)
    at java.net.AbstractPlainSocketImpl.connect(Unknown Source)
    at java.net.PlainSocketImpl.connect(Unknown Source)
    at java.net.SocksSocketImpl.connect(Unknown Source)
    at java.net.Socket.connect(Unknown Source)
    at org.apache.http.conn.ssl.SSLConnectionSocketFactory.connectSocket(SSLConnectionSocketFactory.java:239)
    at org.apache.http.impl.conn.HttpClientConnectionOperator.connect(HttpClientConnectionOperator.java:118)
    ... 10 more

这是我的java代码

public static void main(String[] args) throws Exception {
        // TODO Auto-generated method stub

        CloseableHttpClient httpclient = HttpClients.createDefault();
        try{
            CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
            AuthScope authscp = new AuthScope("api.calltrackingmetrics.com", 443);
            credentialsProvider.setCredentials(authscp, new UsernamePasswordCredentials("mykey","mysecret"));
            HttpClientContext localContext = HttpClientContext.create();
            localContext.setCredentialsProvider(credentialsProvider);
                HttpGet httpGet = new HttpGet("https://api.calltrackingmetrics.com/api/v1/accounts/myaccout/calls.json");
        CloseableHttpResponse response1 = httpclient.execute(httpGet);
        // The underlying HTTP connection is still held by the response object
        // to allow the response content to be streamed directly from the network socket.
        // In order to ensure correct deallocation of system resources
        // the user MUST either fully consume the response content  or abort request
        // execution by calling CloseableHttpResponse#close().

        try {
            System.out.println(response1.getStatusLine());
            HttpEntity entity1 = response1.getEntity();
            // do something useful with the response body
            // and ensure it is fully consumed
            EntityUtils.consume(entity1);
        } finally {
            response1.close();
            }
        }
        finally {
        httpclient.close();
    }
    }
}

请帮我解决这个问题

1 个答案:

答案 0 :(得分:2)

您无需创建上下文 - 您可以在创建时直接将凭据提供程序传递给客户端:

CredentialsProvider provider = new BasicCredentialsProvider();
UsernamePasswordCredentials credentials = new UsernamePasswordCredentials("mykey","mysecret");
AuthScope authscp = new AuthScope("api.calltrackingmetrics.com", 443);
provider.setCredentials(authscp, credentials);
HttpClient client = HttpClientBuilder.create().setDefaultCredentialsProvider(provider).build();

HttpResponse response = client.execute(new HttpGet("https://api.calltrackingmetrics.com/api/v1/accounts/myaccout/calls.json"));
int statusCode = response.getStatusLine().getStatusCode();
assertThat(statusCode, equalTo(HttpStatus.SC_OK));

那应该解决问题。 希望能帮助到你。