1. 程式人生 > >模擬傳送帶cookies的http請求的兩種方法

模擬傳送帶cookies的http請求的兩種方法

如果想傳送帶cookies的請求,有兩種方式,一種使用工具,一種使用java程式碼,乾貨如下:

使用工具

使用的工具是postman和Postman Interceptor使用谷歌瀏覽器的擴充套件程式下載(需要科學上網或者修改本機host,不過此方法稍微麻煩點)
使用postman傳送帶cookies的請求,必須啟動谷歌瀏覽器和postman兩者的Interceptor,缺一不可
圖片1
圖片2
首先必須得啟用瀏覽器和postman的Interceptor,然後就和正常發postman的請求一樣,postman會直接讀取谷歌瀏覽器中的cookies並且和自己的get/post請求一起傳送出去

java程式碼

使用程式碼傳送,其實也很簡答。這裡給出一種最簡單的方法
使用header頭引數傳送cookies

public static String doPostCookie( String url){
        try {
            HttpPost request = new HttpPost( url );
            request.addHeader("Cookie","JSESSIONID=4A3998E6FCA477D878BFF99C26FB1608");
            return execute( request );
        } catch
( Exception e ) { throw new RuntimeException( String.format( "http post fail[message=%s]", e.getMessage() )); } }

其中request.addHeader就是新增一個cookies。此cookies在瀏覽器中的顯示如下:
這裡寫圖片描述
(此處檢視cookies的外掛也是谷歌瀏覽器的一個外掛叫editthiscookie)
上面程式碼的excute方法如下:

private static String execute( HttpUriRequest request
) { try { HttpResponse response = HTTP_CLIENT.execute( request ); StatusLine statusLine = response.getStatusLine(); if( null == statusLine ) { throw new RuntimeException( "http request fail, no status line"); } if( statusLine.getStatusCode() != HttpStatus.SC_OK ) { throw new RuntimeException(String.format( "http request fail[status=%d|message=%s]", statusLine.getStatusCode(), EntityUtils.toString( response.getEntity(), CONTENT_CHARSET ))); } return EntityUtils.toString( response.getEntity(), CONTENT_CHARSET ); } catch( RuntimeException ex ) { LOGGER.error(String.format("execute http request fail[url=%s|msg=%s]", request.getURI(), ex.getMessage())); throw ex; } catch( Exception ex ) { LOGGER.error( String.format( "http request fail[msg=%s|url=%s|param=%s]", ex.getMessage(), request.getURI(), JSON.toJSONString( request.getParams() ) ) ); throw new RuntimeException("http request fail"); } finally { if( null != request && !request.isAborted() ) { request.abort(); } } }

需要匯入的包:

        <!--http -->
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.2.2</version>
        </dependency>
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpcore</artifactId>
            <version>4.2.2</version>
        </dependency>
        <dependency>
            <groupId>org.jodd</groupId>
            <artifactId>jodd-http</artifactId>
            <version>3.7</version>
        </dependency>
        <!--http -->

over。。。。。。。。(可以加qq475804848交流技術哦····)

附:
另外如果想讓瀏覽器幫你設定一個cookies,可以使用下面方法:
//設定cookie

response.addHeader(“Set-Cookie”, “uid=112; Path=/; HttpOnly”);

//設定多個cookie

response.addHeader(“Set-Cookie”, “uid=112; Path=/; HttpOnly”);

response.addHeader(“Set-Cookie”, “timeout=30; Path=/test; HttpOnly”);

//設定https的cookie

response.addHeader(“Set-Cookie”, “uid=112; Path=/; Secure; HttpOnly”);