Base64 암호화 인증 방식의 기본 인증입니다.
base64의 기본 인증에 주의하세요.
httpclient에 제공되는 인증 방법을 사용하면 다음과 같이 인증이 실패합니다.
CredentialsProvider provider = new BasicCredentialsProvider();UsernamePasswordCredentials credentials = new UsernamePasswordCredentials("username", "user1Pass");provider.setCredentials(AuthScope.ANY, credentials);HttpClient client = HttpClientBuilder.create() .setDefaultCredentialsProvider(provider) .build();
성공한 통과 예:
package com.biologic.api.service.impl;import java.io.IOException;import java.util.Base64;import java.util.Map;import org.apache.http.HttpEntity;import org.apache.http.HttpResponse;import org.apache.http.client.ClientProtocolException;import org.apache.http.client.methods.HttpPost;import org.apache.http.entity.ContentType;import org.apache.http.entity.mime.MultipartEntityBuilder;import org.apache.http.entity.mime.content.StringBody;import org.apache.http.impl.client.CloseableHttpClient;import org.apache.http.impl.client.HttpClientBuilder;import org.apache.http.util.EntityUtils;import org.springframework.stereotype.Service;import com.biologic.api.service.HttpService;@Service public class HttpServiceImpl implements HttpService { @Override public int httpClientWithBasicAuth(String username, String password, String uri, Map<String, String> paramMap) { try { // 创建HttpClientBuilder HttpClientBuilder httpClientBuilder = HttpClientBuilder.create(); CloseableHttpClient closeableHttpClient = httpClientBuilder.build(); HttpPost httpPost = new HttpPost(uri); //添加http头信息 httpPost.addHeader("Authorization", "Basic " + Base64.getUrlEncoder().encodeToString((username + ":" + password).getBytes())); MultipartEntityBuilder builder = MultipartEntityBuilder.create(); paramMap.forEach((k,v)->{ builder.addPart(k, new StringBody(v, ContentType.MULTIPART_FORM_DATA)); }); HttpEntity postEntity = builder.build(); httpPost.setEntity(postEntity); String result = ""; HttpResponse httpResponse = null; HttpEntity entity = null; try { httpResponse = closeableHttpClient.execute(httpPost); entity = httpResponse.getEntity(); if( entity != null ){ result = EntityUtils.toString(entity); } } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } // 关闭连接 closeableHttpClient.close(); System.out.println(result); }catch (Exception e) { System.out.println(e.getStackTrace()); } return 0; } }
관련 기사:
관련 동영상:
위 내용은 Java는 httpclient와 함께 제공되는 인증 방법을 사용하여 기본 인증으로 보냅니다.의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!