Fourth HttpClient way to get data across domains

1.HttpClient is a subproject of Apache Jakarta Common, it can be used to provide efficient, new, feature-rich client support http protocol programming toolkit, and he supported the latest version of the http protocol and protocol

2. Import dependence

<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.3.5</version>
</dependency>

3.DoGet process (no reference)

 

 DoGet (there are parameters)

 

 DoPost (no-argument)

 

 post with a request parameter

 

   public static void main(String[] args) throws Exception {

        // 创建Httpclient对象
        CloseableHttpClient httpclient = HttpClients.createDefault();

        // 创建http POST请求
        HttpPost httpPost = new HttpPost("http://www.oschina.net/search");
        
     // disguised browser 
        httpPost.setHeader ( "the User-Agent", "Mozilla / 5.0 (Windows NT 6.3; WOW64) AppleWebKit / 537.36 (KHTML, like Gecko) Chrome / 50.0.2661.94 Safari / 537.36" );

        // set two post parameters, a scope, a is Q 
        List <of NameValuePairs> Parameters = new new the ArrayList <of NameValuePairs> (0 );
        parameters.add(new BasicNameValuePair("scope", "project"));
        parameters.add(new BasicNameValuePair("q", "java"));
        parameters.add ( new new BasicNameValuePair ( "fromerr", "7nXH76r7" ));
         // configured to form a sheet-like entity 
        UrlEncodedFormEntity formEntity = new new UrlEncodedFormEntity (Parameters);
         // be provided to the requesting entity httpPost object 
        httpPost.setEntity (formEntity );    

        Response CloseableHttpResponse = null ;
         the try {
             // execution request 
            Response = (HttpPost) httpclient.execute;
             // determines whether the state is returned 200 is 
            IF (response.getStatusLine () getStatusCode () == 200 is. {)
                String content = EntityUtils.toString(response.getEntity(), "UTF-8");
                System.out.println(content);
            }
        } finally {
            if (response != null) {
                response.close();
            }
            httpclient.close();
        }

    }

 

Guess you like

Origin www.cnblogs.com/sh-0131/p/11742308.html