Koptekst toevoegen voor HttpURLConnection

Ik probeer een header voor mijn verzoek toe te voegen met behulp van HttpUrlConnectionmaar de methode setRequestProperty()lijkt niet te werken. De serverzijde ontvangt geen verzoek met mijn header.

HttpURLConnection hc;
    try {
        String authorization = "";
        URL address = new URL(url);
        hc = (HttpURLConnection) address.openConnection();
        hc.setDoOutput(true);
        hc.setDoInput(true);
        hc.setUseCaches(false);
        if (username != null && password != null) {
            authorization = username + ":" + password;
        }
        if (authorization != null) {
            byte[] encodedBytes;
            encodedBytes = Base64.encode(authorization.getBytes(), 0);
            authorization = "Basic " + encodedBytes;
            hc.setRequestProperty("Authorization", authorization);
        }

Antwoord 1, autoriteit 100%

Ik heb in het verleden de volgende code gebruikt en deze werkte met basisverificatie ingeschakeld in TomCat:

URL myURL = new URL(serviceURL);
HttpURLConnection myURLConnection = (HttpURLConnection)myURL.openConnection();
String userCredentials = "username:password";
String basicAuth = "Basic " + new String(Base64.getEncoder().encode(userCredentials.getBytes()));
myURLConnection.setRequestProperty ("Authorization", basicAuth);
myURLConnection.setRequestMethod("POST");
myURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
myURLConnection.setRequestProperty("Content-Length", "" + postData.getBytes().length);
myURLConnection.setRequestProperty("Content-Language", "en-US");
myURLConnection.setUseCaches(false);
myURLConnection.setDoInput(true);
myURLConnection.setDoOutput(true);

Je kunt de bovenstaande code proberen. De bovenstaande code is voor POST en u kunt deze wijzigen voor GET


Antwoord 2, autoriteit 4%

Omdat ik dit stukje informatie niet in de bovenstaande antwoorden zie, werkt het oorspronkelijk geposte codefragment niet correct omdat de variabele encodedByteseen byte[]en niet een String-waarde. Als u de byte[]doorgeeft aan een new String()zoals hieronder, werkt het codefragment perfect.

encodedBytes = Base64.encode(authorization.getBytes(), 0);
authorization = "Basic " + new String(encodedBytes);

Antwoord 3, autoriteit 3%

Als je Java 8 gebruikt, gebruik dan de onderstaande code.

URLConnection connection = url.openConnection();
HttpURLConnection httpConn = (HttpURLConnection) connection;
String basicAuth = Base64.getEncoder().encodeToString((username+":"+password).getBytes(StandardCharsets.UTF_8));
httpConn.setRequestProperty ("Authorization", "Basic "+basicAuth);

Antwoord 4

Eindelijk werkte dit voor mij

private String buildBasicAuthorizationString(String username, String password) {
    String credentials = username + ":" + password;
    return "Basic " + new String(Base64.encode(credentials.getBytes(), Base64.NO_WRAP));
}

Antwoord 5

Je code is in orde. Je kunt hetzelfde ook op deze manier gebruiken.

public static String getResponseFromJsonURL(String url) {
    String jsonResponse = null;
    if (CommonUtility.isNotEmpty(url)) {
        try {
            /************** For getting response from HTTP URL start ***************/
            URL object = new URL(url);
            HttpURLConnection connection = (HttpURLConnection) object
                    .openConnection();
            // int timeOut = connection.getReadTimeout();
            connection.setReadTimeout(60 * 1000);
            connection.setConnectTimeout(60 * 1000);
            String authorization="xyz:xyz$123";
            String encodedAuth="Basic "+Base64.encode(authorization.getBytes());
            connection.setRequestProperty("Authorization", encodedAuth);
            int responseCode = connection.getResponseCode();
            //String responseMsg = connection.getResponseMessage();
            if (responseCode == 200) {
                InputStream inputStr = connection.getInputStream();
                String encoding = connection.getContentEncoding() == null ? "UTF-8"
                        : connection.getContentEncoding();
                jsonResponse = IOUtils.toString(inputStr, encoding);
                /************** For getting response from HTTP URL end ***************/
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    return jsonResponse;
}

De retourresponscode 200 indien autorisatie-succes


Antwoord 6

met restassurd u kan ook het volgende doen:

String path = baseApiUrl; //This is the base url of the API tested
    URL url = new URL(path);
    given(). //Rest Assured syntax 
            contentType("application/json"). //API content type
            given().header("headerName", "headerValue"). //Some API contains headers to run with the API 
            when().
            get(url).
            then().
            statusCode(200); //Assert that the response is 200 - OK

Antwoord 7

Stap 1: Ontvang HTTPURLCONNECTIE-OBJECT

URL url = new URL(urlToConnect);
HttpURLConnection httpUrlConnection = (HttpURLConnection) url.openConnection();

Stap 2: Voeg kopteksten toe aan de HTTPURLCONNECTIE met behulp van SetReQuestProperty-methode.

Map<String, String> headers = new HashMap<>();
headers.put("X-CSRF-Token", "fetch");
headers.put("content-type", "application/json");
for (String headerKey : headers.keySet()) {
    httpUrlConnection.setRequestProperty(headerKey, headers.get(headerKey));
}

referentie link

Other episodes