Httpclient處理摘要認證

    雖然摘要認證的安全性比BASIC認證提高了不少,但是從接口調用上來看,並不比BASIC認證複雜,而且Realm和Scheme參數都可以爲空,這時候就和BASIC認證的調用方式一模一樣了。


import java.net.URI;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.client.methods.RequestBuilder;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
public class DigestTest {
    public static void main(String[] args) throws Exception {
        CredentialsProvider credsProvider = new BasicCredentialsProvider();
        credsProvider.setCredentials(new AuthScope("10.0.0.90", 8080, "favourite digest realm", AuthScope.ANY_SCHEME),
                new UsernamePasswordCredentials("admin", "password"));
        CloseableHttpClient httpclient = HttpClients.custom().setDefaultCredentialsProvider(credsProvider).build();
        HttpUriRequest login = RequestBuilder.post()
                .setUri(new URI("http://10.0.0.100:8080/hibaby/getBabiesByGender"))
                .addParameter("appKey", "BEST")
                .addParameter("gender", "boy").build();
        CloseableHttpResponse response = httpclient.execute(login);
        System.out.println("響應狀態:" + response.getStatusLine());
        String result = EntityUtils.toString(response.getEntity(), "UTF-8");
        System.out.println("Result: " + result);
    }
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章