带有基本auth java的Http请求

时间:2018-06-04 11:01:27

标签: java api basic-authentication

我正在尝试使用基本身份验证通过httpGet访问API。我的代码是:

byte[] encodedBytes = Base64.getEncoder().encode("user:pass".getBytes());

HttpGet httpget = new HttpGet("https://app.feedcheck.co/api/reviews");
httpget.setHeader("Authorization", "Basic " + encodedBytes);

System.out.println("executing request " + httpget.getRequestLine());
HttpResponse response = httpClient.execute(httpget);
HttpEntity entity = response.getEntity();
String apiOutput = EntityUtils.toString(entity);
System.out.println(apiOutput);

在postman中,我得到了我期望的响应,但是当在Eclipse中运行程序时,它返回:

  

无法验证该网址的访问权限级别。你必须登录   有适当的证件

在Python中使用代码执行请求时:

import requests
from requests.auth import HTTPBasicAuth

r = requests.get('https://app.feedcheck.co/api/reviews', auth=HTTPBasicAuth('user', 'pass'))
print(r.text)

它与Postman一样返回。谁能帮我这个?我做错了什么?

2 个答案:

答案 0 :(得分:4)

检查一下。它对我有用。

  try {
        String webPage = "http://192.168.1.1";
        String name = "admin";
        String password = "admin";

        String authString = name + ":" + password;
        System.out.println("auth string: " + authString);
        byte[] authEncBytes = Base64.encodeBase64(authString.getBytes());
        String authStringEnc = new String(authEncBytes);
        System.out.println("Base64 encoded auth string: " + authStringEnc);

        URL url = new URL(webPage);
        URLConnection urlConnection = url.openConnection();
        urlConnection.setRequestProperty("Authorization", "Basic " + authStringEnc);
        InputStream is = urlConnection.getInputStream();
        InputStreamReader isr = new InputStreamReader(is);

        int numCharsRead;
        char[] charArray = new char[1024];
        StringBuffer sb = new StringBuffer();
        while ((numCharsRead = isr.read(charArray)) > 0) {
            sb.append(charArray, 0, numCharsRead);
        }
        String result = sb.toString();

        System.out.println("*** BEGIN ***");
        System.out.println(result);
        System.out.println("*** END ***");
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

答案 1 :(得分:0)

我刚刚玩过基本身份验证,摘要身份验证,接受所有证书的SSL,而且也很严格。此测试代码可以完成所有这些操作,并且还像op一样使用HttpClient。它带有注释,并且“ if / else”块使您可以选择要解决的方案。

package com.myorg.test;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List;

import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLHandshakeException;

import org.apache.http.Header;
import org.apache.http.HeaderElement;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.auth.AUTH;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.MalformedChallengeException;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.AuthCache;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.impl.auth.BasicScheme;
import org.apache.http.impl.auth.DigestScheme;
import org.apache.http.impl.client.BasicAuthCache;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.ssl.SSLContextBuilder;
import org.apache.http.util.EntityUtils;

public class DigestTest {
    // Test get URL. 
    static String sGetURL = "https://192.168.0.1/info";
    // Test post URL
    static String sPostURL = "https://192.168.0.1/set";

    // Fetch a URL
    //      Authentication
    //          Assumes user and password are required
    //          Will determine if Basic or Digest authentication is needed based on response header
    //      HTTP Verb
    //          If "postParams" is not null, will use POST, otherwise will use GET
    //
    public void URLFetch(String sURL, String sUser, String sPW, List<NameValuePair> postParams,
            boolean bIgnoreCerts) {

        try {
            // Create empty objects for POST and GET since we don't know which we'll use
            // below
            HttpPost httppost = null;
            HttpGet httpget = null;

            // Crate a URL object
            URL url = new URL(sURL);

            // Now create the HttpHost object from the URL
            HttpHost targetHost = new HttpHost(url.getHost(), url.getPort(), url.getProtocol());

            // Here we need an HTTP client either with or without the SSLContext that
            // ignores certs
            CloseableHttpClient httpClient = null;
            if (bIgnoreCerts) {
                // Create an SSL context that accepts certs regardless of name match or trust (for self-signed) 
                SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, (x509CertChain, authType) -> true)
                        .build();

                httpClient = HttpClientBuilder.create().setSSLContext(sslContext)
                        .setConnectionManager(new PoolingHttpClientConnectionManager(RegistryBuilder
                                .<ConnectionSocketFactory>create()
                                .register("http", PlainConnectionSocketFactory.INSTANCE)
                                .register("https",
                                        new SSLConnectionSocketFactory(sslContext, NoopHostnameVerifier.INSTANCE))
                                .build()))
                        .build();               
            } else {
                httpClient = HttpClients.createDefault();
            }

            // The HttpCLientContext
            final HttpClientContext context = HttpClientContext.create();

            // We'll need to allocate the response object below depending on type
            CloseableHttpResponse response = null;
            try {
                if (postParams != null) {
                    httppost = new HttpPost(sURL);
                    // Get the response
                    response = httpClient.execute(targetHost, httppost, context);
                } else {
                    httpget = new HttpGet(sURL);
                    // Get the response
                    response = httpClient.execute(targetHost, httpget, context);
                }
            } catch (SSLHandshakeException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            // Add credentials for digest header
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_UNAUTHORIZED) {
                // Change to just pass user and password
                Header authHeader = response.getFirstHeader(AUTH.WWW_AUTH);
                HeaderElement[] element = authHeader.getElements();
                if (element.length != 0) {
                    AuthCache authCache = new BasicAuthCache();
                    CredentialsProvider credsProvider = new BasicCredentialsProvider();
                    credsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(sUser, sPW));
                    if (element[0].getName().startsWith("Basic")) {
                        authCache.put(targetHost, new BasicScheme());
                    } else if (element[0].getName().startsWith("Digest")) {
                        DigestScheme digestScheme = new DigestScheme();
                        digestScheme.overrideParamter("realm", "thermostat");
                        digestScheme.processChallenge(authHeader);
                        authCache.put(targetHost, digestScheme);
                    }
                    context.setCredentialsProvider(credsProvider);
                    context.setAuthCache(authCache);
                }
            }

            // This ensures that the resource gets cleaned up
            response = null;
            if (postParams != null) {
                httppost = new HttpPost(sURL);
                if (postParams != null) {
                    httppost.setEntity(new UrlEncodedFormEntity(postParams, "UTF-8"));

                    // Get the response
                    response = httpClient.execute(targetHost, httppost, context);
                }
            } else {
                httpget = new HttpGet(sURL);
                // Get the response
                response = httpClient.execute(targetHost, httpget, context);
            }

            // Get the data
            HttpEntity entity = response.getEntity();
            System.out.println(response.getStatusLine());
            if (entity != null) {
                System.out.println("Response content length: " + entity.getContentLength());
            }

            try {

                try (BufferedReader in = new BufferedReader(new InputStreamReader(entity.getContent()))) {
                    String inputLine;
                    while ((inputLine = in.readLine()) != null) {
                        System.out.println(sURL + " : " + inputLine);
                    }
                    EntityUtils.consume(entity);
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            } finally {
                try {
                    httpClient.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        } catch (MalformedURLException | KeyManagementException | NoSuchAlgorithmException | KeyStoreException
                | MalformedChallengeException | UnsupportedEncodingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (ClientProtocolException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        } catch (IOException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
    }

    // Main, takes 4 arguments (see println below)
    public static void main(String[] args) {
        List<NameValuePair> postParameters = new ArrayList<NameValuePair>();
        postParameters.add(new BasicNameValuePair("away", "1"));
        DigestTest d = new DigestTest();

        d.URLFetch(sPostURL, "user", "password", postParameters, false);
        d.URLFetch(sGetURL, "user", "password", null, true);
    }
}