HttpURLConnection için başlık ekleme


254

Kullanarak benim istek için başlık eklemek çalışıyorum HttpUrlConnectionama yöntem setRequestProperty()çalışmıyor gibi görünüyor. Sunucu tarafı üstbilgimle herhangi bir istek almıyor.

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);
        }

Benim için çalışıyor, başlığın gönderildiğini ve alınmadığını nasıl söylersiniz?
— Tomasz Nurkiewicz

1
bu aptalca geliyorsa özür dilerim, ama connect()URLConnection'ı nereye çağırıyorsunuz ?
— Vikdor

Bunun bir etkisi olup olmadığından emin değilim ama eklemeyi deneyebilirsiniz connection.setRequestMethod("GET");(veya POST veya istediğinizi)?
— noobed

1
authorizationBoş dizeye başlangıç ​​değeri . Ya usernameda passwordnull olursa , null authorizationdeğil boş dize olur. Bu nedenle, final ifidam edilecek, ancak "Authorization"mülkiyet boş olarak ayarlanacak, bana göre.
— zerzevul

Yanıtlar:


422

Geçmişte aşağıdaki kodu kullandım ve TomCat etkin temel kimlik doğrulaması ile çalıştı:

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);

Yukarıdaki kodu deneyebilirsiniz. Yukarıdaki kod POST içindir ve GET için değiştirebilirsiniz.


15
Android geliştiricileri için küçük bir ek (API> = 8 aka 2.2): android.util.Base64.encode (userCredentials.getBytes (), Base64.DEFAULT); Base64.DEFAULT, base64 kodlaması için RFC2045 kullanmayı söyler.
— Denis Gladkiy

@Denis, bana neden başlık kullanması gerektiğini söyler misiniz? Ben xammp üzerinde php kullanıyorum android bazı kimlik doğrulamak zorunda. nasıl yapmalıyım. gibi başlıkları ile php kodu yazma bilmiyorum
— Pankaj Nimgade

11
Değişken postDataörneğinizde nereden geldi?
— 16:28, GlenPeterson

22
Neden herkes onlara üstbilgi dediğinde "RequestProperty" denir?
— Philip Rego

2
Java8 sürümü için bir ek: Base64 sınıfı biraz değişti. Kod çözme şu şekilde yapılmalıdır:String basicAuth = "Basic " + java.util.Base64.getEncoder().encodeToString(userCredentials.getBytes());
— Mihailo Stupar

17

Sadece yukarıdaki cevaplarda bu bilgileri biraz görmüyorum, kod parçacığının başlangıçta gönderilmesinin nedeni encodedBytesdeğişkenin byte[]bir Stringdeğer değil bir değer olması. Eğer başarılı olursa byte[]bir etmek new String()olarak aşağıda kod parçacığı mükemmel çalışıyor.

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

11

Java 8 kullanıyorsanız, aşağıdaki kodu kullanın.

URLConnection connection = url.openConnection();
HttpURLConnection httpConn = (HttpURLConnection) connection;

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

6

Sonunda bu benim için çalıştı

private String buildBasicAuthorizationString(String username, String password) {

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

2
@ d3dave. Dize bayt dizisinden oluşturuldu ve "Temel" ile birleştirildi. OP kodunda sorun "Temel" byte [] ile birleştirmek ve üstbilgi olarak göndermek oldu.
— yurin

5

Kodunuz iyi. Aynı şeyi bu şekilde de kullanabilirsiniz.

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;
}

Yetkilendirme başarılıysa Dönüş yanıt kodu 200


1

RestAssurd ile aşağıdakileri de yapabilirsiniz:

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

1
Kodu burada biraz daha temiz biçimlendirmek ister misiniz? Ayrıca, ne olması given()gerekiyordu?
— Nathaniel Ford

Merhaba, Bu dinlenme Assurd (test dinlenme Api) için temel kullanımdır. Ben koda açıklama ekledi.
— Eyal Sooliman

-1

Adım 1: HttpURLConnection nesnesini alın

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

Adım 2: setRequestProperty yöntemini kullanarak HttpURLConnection öğesine üstbilgiler ekleyin.

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));
}

Referans bağlantısı

Sitemizi kullandığınızda şunları okuyup anladığınızı kabul etmiş olursunuz: Çerez Politikası ve Gizlilik Politikası.
Licensed under cc by-sa 3.0 with attribution required.