public class TestConnection { public static String httpClientWithBasicAuth() { String username="xxx"; String password="xxx"; String uri="xxxx"; Map<String, String> paramMap = new HashMap<String,String>(); paramMap.put("xxx", "xxxx"); String result = ""; try { // 创建HttpClientBuilder HttpClientBuilder httpClientBuilder = HttpClientBuilder.create(); //绕过证书 CloseableHttpClient closeableHttpClient = httpClientBuilder.setSSLHostnameVerifier(new NoopHostnameVerifier()) .build(); HttpPost httpPost = new HttpPost(uri); //String a = Base64.getUrlEncoder().encodeToString((username + ":" + password).getBytes()); //添加http头信息 httpPost.addHeader("Authorization", "Basic " + Base64.getUrlEncoder().encodeToString((username + ":" + password).getBytes())); httpPost.addHeader("Content-Type", "application/json"); //httpPost.addHeader("Authorization","Basic "+a); StringEntity s = new StringEntity(JSON.toJSONString(paramMap)); s.setContentEncoding("UTF-8"); httpPost.setEntity(s); HttpResponse httpResponse = null; HttpEntity entity = null; try { httpResponse = closeableHttpClient.execute(httpPost); entity = httpResponse.getEntity(); System.out.println("httpResponse==="+httpResponse.getStatusLine()); if( entity != null ){ result = EntityUtils.toString(entity); System.out.println("result===="+result); } } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } // 关闭连接 closeableHttpClient.close(); }catch (Exception e) { e.printStackTrace(); } return result; } public static void main(String[] args) throws Throwable { httpClientWithBasicAuth(); } }
maven引用的依赖包:
<dependencies> <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version>4.5.3</version> </dependency> <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpmime</artifactId> <version>4.5</version> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.47</version> </dependency> </dependencies>