java-http请求
https://blog.csdn.net/bushijieinside/article/details/12314923
https://segmentfault.com/a/1190000012056247?utm_source=tag-newest
方式一:RestTemplate
参考链接:https://www.jianshu.com/p/27a82c494413
public static String RestTemplate(String url, byte[] bytes, HttpMethod method,MediaType contentType,String userName,String password) { String ret = ""; CloseableHttpClient httpClient = null; try { SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory(); requestFactory.setReadTimeout(1500); requestFactory.setConnectTimeout(1000); RestTemplate restTemplate = new RestTemplate(requestFactory); //---------------------设置User credentials用户凭证--------- //由于需要使用Cookie认证,则请求时使用用户凭证代替Cookie认证 CredentialsProvider credsProvider = new BasicCredentialsProvider(); UsernamePasswordCredentials creds = new UsernamePasswordCredentials(userName,password); credsProvider.setCredentials(AuthScope.ANY, creds); httpClient = HttpClients.custom().setDefaultCredentialsProvider(credsProvider).build(); HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(httpClient); restTemplate.setRequestFactory(requestFactory); //------------------------------------------------------- HttpHeaders headers = new HttpHeaders(); if (contentType != null){ headers.setContentType(contentType); } org.springframework.http.HttpEntity<byte[]> entity = new org.springframework.http.HttpEntity<>(bytes,headers); //提交 ResponseEntity<String> responseEntity = restTemplate.exchange(url,method,entity, String.class); ret = responseEntity.getBody(); } catch (Exception e) { logger.error("RestTemplate error:"+e.toString()); }finally { try { if (httpClient != null){ httpClient.close(); } } catch (IOException e) { e.printStackTrace(); } } return ret; }
方式二:HttpClientRequest
参考链接:https://blog.csdn.net/YouCanYouUp_/article/details/80769572
https://blog.csdn.net/justry_deng/article/details/81042379
https://www.iteye.com/blog/rensanning-1550436
public static String HttpClientRequest(String url,byte[] bytes,HttpMethod method,MediaType contentType,String userName,String password){ String ret = ""; CredentialsProvider credsProvider = new BasicCredentialsProvider(); UsernamePasswordCredentials creds = new UsernamePasswordCredentials(userName,password); credsProvider.setCredentials(AuthScope.ANY, creds); CloseableHttpClient httpClient = HttpClients.custom().setDefaultCredentialsProvider(credsProvider).build(); CloseableHttpResponse response = null; try { if (method == HttpMethod.GET ){ //创建Get方法 HttpGet httpGet = new HttpGet(url); httpGet.addHeader("Content-Type",contentType.toString()); //执行请求 response = httpClient.execute(httpGet); //获取响应的实体对象 HttpEntity entity = response.getEntity(); ret = EntityUtils.toString(entity,"UTF-8"); EntityUtils.consume(entity); httpGet.releaseConnection(); }else if(method == HttpMethod.POST){ //创建Post方法 HttpPost httpPost = new HttpPost(url); httpPost.addHeader("Content-Type",contentType.toString()); HttpEntity entity = new ByteArrayEntity(bytes); httpPost.setEntity(entity); //执行请求 response = httpClient.execute(httpPost); //获取响应的实体对象 entity = response.getEntity(); ret = EntityUtils.toString(entity,"UTF-8"); EntityUtils.consume(entity); httpPost.releaseConnection(); }else if(method == HttpMethod.DELETE){ HttpDelete httpDelete = new HttpDelete(url); httpDelete.addHeader("Content-Type",contentType.toString()); //执行请求 response = httpClient.execute(httpDelete); //获取响应的实体对象 HttpEntity entity = response.getEntity(); ret = EntityUtils.toString(entity,"UTF-8"); EntityUtils.consume(entity); httpDelete.releaseConnection(); }else if(method == HttpMethod.PUT){ HttpPut httpPut = new HttpPut(url); httpPut.addHeader("Content-Type",contentType.toString()); ByteArrayEntity entity = new ByteArrayEntity(bytes); httpPut.setEntity(entity); //执行请求 response = httpClient.execute(httpPut); int code = response.getStatusLine().getStatusCode(); //获取响应的实体对象 HttpEntity httpEntity = response.getEntity(); ret = EntityUtils.toString(httpEntity,"UTF-8"); EntityUtils.consume(httpEntity); httpPut.releaseConnection(); } } catch (IOException e) { logger.error("HttpClientRequest is error:"+e.toString()); } finally { try { // 释放连接 if (response != null) { response.close(); } if (httpClient != null){ httpClient.close(); } } catch (Exception e) { logger.error("close is error:"+e.toString()); } } return ret; }
如果设置用户名和密码后仍返回401,则还需要设置realm 和 nonce 代理认证
public static String HttpClientRequest_UploadFile(String url, byte[] bytes, HttpMethod method, MediaType contentType, String userName, String password, String ip, Header[] headers,Integer count){ Boolean isFirst = true; String ret = ""; CloseableHttpClient httpClient = HttpClientBuilder.create().build(); CloseableHttpResponse response = null; try { if(method == HttpMethod.PUT){ HttpPut httpPut = new HttpPut(url); httpPut.addHeader("Content-Type",contentType.toString()); if (headers.length > 0){ for (int i=0;i<headers.length;i++) { if (headers[i].getName().equals("WWW-Authenticate")){ ByteArrayEntity entity = new ByteArrayEntity(bytes); httpPut.setEntity(entity); CredentialsProvider credsProvider = new BasicCredentialsProvider(); UsernamePasswordCredentials creds = new UsernamePasswordCredentials(userName,password); credsProvider.setCredentials(AuthScope.ANY, creds); String realm = ""; String nonce = ""; HeaderElement[] headerElements = headers[i].getElements(); if (headerElements.length > 0){ for (HeaderElement element : headerElements){ if (element.getName().equals("Digest realm")){ realm = element.getValue(); }else if(element.getName().equals("nonce")){ nonce = element.getValue(); } } } DigestScheme digestAuth = new DigestScheme(); digestAuth.overrideParamter("realm", realm); digestAuth.overrideParamter("nonce", nonce); HttpHost targetHost3 = new HttpHost(ip, 80, "http"); AuthCache authCache3 = new BasicAuthCache(); authCache3.put(targetHost3, digestAuth); BasicHttpContext localcontext3 = new BasicHttpContext(); localcontext3.setAttribute(ClientContext.AUTH_CACHE, authCache3); httpClient = HttpClients.custom().setDefaultCredentialsProvider(credsProvider).build(); //执行请求 response = httpClient.execute(httpPut,localcontext3); /*//获取响应的实体对象 HttpEntity httpEntity = response.getEntity(); ret = EntityUtils.toString(httpEntity,"UTF-8"); EntityUtils.consume(httpEntity);*/ isFirst = false; }else { httpPut.addHeader(headers[i]); } } } if (isFirst){ //执行请求 response = httpClient.execute(httpPut); } int code = response.getStatusLine().getStatusCode(); if (code == 401 && count < 3) { count++; //如果请求为401,则设置Authorization Header[] authenticate = response.getHeaders("WWW-Authenticate"); ret = HttpClientRequest_UploadFile(url, bytes, method, contentType, userName, password, ip, authenticate,count); }else { //获取响应的实体对象 HttpEntity httpEntity = response.getEntity(); ret = EntityUtils.toString(httpEntity,"UTF-8"); EntityUtils.consume(httpEntity); } httpPut.releaseConnection(); } } catch (IOException e) { logger.error("HttpClientRequest_UploadFile is error:"+e.toString()); } finally { try { // 释放连接 if (response != null) { response.close(); } if (httpClient != null){ httpClient.close(); } } catch (Exception e) { logger.error(" close is error:"+e.toString()); } } return ret; }