http请求digest auth认证

时间: 2023-07-09 admin IT培训

http请求digest auth认证

http请求digest auth认证

1.post请求
public static String postMethod(String url, String query,String host) throws IOException {String content = null;//认证CloseableHttpClient httpclient=digestAuth(host);try {HttpPost postMethod = new HttpPost(url);StringEntity s = new StringEntity(query);s.setContentEncoding("utf-8");//编码s.setContentType("application/xml");postMethod.setEntity(s);HttpResponse response = httpclient.execute(postMethod);content = EntityUtils.toString(response.getEntity());} catch (Exception e) {System.out.println("推送失败:" + e);} finally {httpclient.close();}return content;
}2.byte[]类型参数
public static String postMethodAnalysisImage(String url, byte[] binaryStreamsStr,String host) throws IOException {CloseableHttpClient httpclient=digestAuth(host);String content=null;try {HttpPost postMethod = new HttpPost(url);HttpEntity reqEntity = new ByteArrayEntity(binaryStreamsStr, ContentType.APPLICATION_JSON);postMethod.setEntity(reqEntity);StringEntity s = new StringEntity(reqEntity.toString());s.setContentEncoding("utf-8");//编码postMethod.setEntity(s);postMethod.setEntity(reqEntity);HttpResponse response = httpclient.execute(postMethod);content = EntityUtils.toString(response.getEntity());} catch (Exception e) {System.out.println("推送失败:" + e);}finally {httpclient.close();}return content;
}
3.HttpGet 请求
public static String getMethodFDLib(String url, String host) throws IOException {String content = null;CloseableHttpClient httpclient=digestAuth(host);try {HttpGet getMethod = new HttpGet(url);org.apache.http.HttpResponse response = httpclient.execute(getMethod);content = EntityUtils.toString(response.getEntity());} catch (Exception e) {System.out.println("推送失败:" + e);}finally {httpclient.close();}return content;
}
private static CloseableHttpClient digestAuth(String host) {CredentialsProvider credsProvider = new BasicCredentialsProvider();credsProvider.setCredentials(new AuthScope(host, 80),//请求地址 + 端口号密码2b3e201690"));// 用户名 + 密码 (用于验证)CloseableHttpClient httpclient = HttpClients.custom().setDefaultCredentialsProvider(credsProvider).build();return httpclient;
}