java-http request

https://blog.csdn.net/bushijieinside/article/details/12314923

https://segmentfault.com/a/1190000012056247?utm_source=tag-newest

Method 1: RestTemplate

Reference Links: https://www.jianshu.com/p/27a82c494413

 

public  static String RestTemplate (URL String, byte [] bytes, HttpMethod Method, the MediaType contentType, the userName String, String password) { 
        String RET = "" ; 
        CloseableHttpClient httpClient = null ;
         the try { 
            RestTemplate RestTemplate = new new RestTemplate ();
       // - user credentials user credentials provided -------------------- ---------
       // since Cookie requires authentication, instead of using the user credentials request Cookie certified 
            the CredentialsProvider credsProvider = new 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;
    }

Second way : HttpClientRequest

Reference Links: 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;
         The try {
             IF (Method == HttpMethod.GET) {
                 // create a Get method 
                HttpGet HttpGet = new new HttpGet (URL); 
                httpGet.addHeader ( "the Type-the Content" , contentType.toString ());
                 // execution request 
                response = httpClient.execute (HttpGet);
                 // Get response entity object 
                the HttpEntity entity = response.getEntity (); 
                RET = EntityUtils.toString (entity, "UTF-. 8" );  
                EntityUtils.consume (entity);
                httpGet.releaseConnection (); 
            } the else  IF (Method == HttpMethod.POST) {
                 // Create Post method 
                HttpPost HttpPost = new new HttpPost (URL); 
                httpPost.addHeader ( "the Type-the Content" , contentType.toString ()); 
                the HttpEntity entity = new new ByteArrayEntity (bytes); 
                httpPost.setEntity (entity); 
                // execution request 
                response = httpClient.execute (HttpPost);
                 // entity object of the fetch response 
                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 still returns after setting a user name and password, you also need to set up proxy authentication realm and 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 (HTTP PUT, localcontext3);
                             / * // fetch response entity object of 
                            the HttpEntity response.getEntity HttpEntity = (); 
                            RET = EntityUtils.toString (HttpEntity, "UTF-. 8"); 
                            EntityUtils.consume (HttpEntity); * / 
                            isFirst = to false ; 
                        } the else { 
                            httpPut.addHeader (headers [I]); 
                        } 
                    } 
                } 
                IF (isFirst) {
                     // execution request
                    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;
    }

 

Guess you like

Origin www.cnblogs.com/lijianda/p/11712626.html