使用Apache异步http客户端的Http POST + auth

时间:2015-07-29 08:05:46

标签: java json authentication post

我正在对Web服务执行异步http请求。我不确定这是否是正确的方法,但它有效。

这是使用HttpAsyncClient进行POST +身份验证的正确方法吗?

我应该用httpclient.close()关闭最后的httpclient; ?

public void asyncHttpRequest() {
    try {            

        RequestConfig requestConfig = RequestConfig.custom()
                .setSocketTimeout(3000)
                .setConnectTimeout(3000).build();
        CloseableHttpAsyncClient httpclient = HttpAsyncClients.custom()
                .setDefaultRequestConfig(requestConfig)
                .build();

        httpclient.start();

        String postParameter = new JSONObject().put("key", "value").toString(); //Creating JSON string

        HttpPost httpPost = new HttpPost("http://www.url.com");
        httpPost.setEntity(new StringEntity(postParameter));
        UsernamePasswordCredentials creds
                = new UsernamePasswordCredentials("username", "password");
        httpPost.addHeader(new BasicScheme().authenticate(creds, httpPost, null));
        httpPost.setHeader("Accept", "application/json");
        httpPost.setHeader("Content-type", "application/json");

        httpclient.execute(httpPost, new FutureCallback<HttpResponse>() {

            @Override
            public void completed(final HttpResponse response) {

                try {
                    InputStream responseBody = response.getEntity().getContent();
                    String serverResponse = IOUtils.toString(responseBody);

                    System.out.println("Server response : " + serverResponse);
                    System.out.println(httpPost.getRequestLine() + "->" + response.getStatusLine());

                } catch (IOException | UnsupportedOperationException ex) {
                    //Do something
                }

            }

            @Override
            public void failed(final Exception ex) {
                //Do something
            }

            @Override
            public void cancelled() {
                //Do something
            }
        });
    } catch (IOException ex) {
        //Do something
    } catch (AuthenticationException ex) {
        //Do something
    }
}

感谢任何帮助!

1 个答案:

答案 0 :(得分:1)

我建议使用如下所示的凭据提供程序,而不是显式添加用于基本身份验证的标头:

CredentialsProvider provider = new BasicCredentialsProvider();
UsernamePasswordCredentials creds = 
    new UsernamePasswordCredentials("username", "password");
provider.setCredentials(AuthScope.ANY, creds);

CloseableHttpAsyncClient httpclient = HttpAsyncClients.custom()
            .setDefaultRequestConfig(requestConfig)
            .setDefaultCredentialsProvider(provider)
            .build();

此外,最好在请求完全处理后显式关闭httpclient。