如果想发送带cookies的请求,有两种方式,一种使用工具,一种使用java代码,干货如下:
使用的工具是postman和Postman Interceptor使用谷歌浏览器的扩展程序下载(需要科学上网或者修改本机host,不过此方法稍微麻烦点)
使用postman发送带cookies的请求,必须启动谷歌浏览器和postman两者的Interceptor,缺一不可
首先必须得启用浏览器和postman的Interceptor,然后就和正常发postman的请求一样,postman会直接读取谷歌浏览器中的cookies并且和自己的get/post请求一起发送出去
使用代码发送,其实也很简答。这里给出一种最简单的方法
使用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();
}
}
}
需要导入的包:
<dependency>
<groupId>org.apache.httpcomponentsgroupId>
<artifactId>httpclientartifactId>
<version>4.2.2version>
dependency>
<dependency>
<groupId>org.apache.httpcomponentsgroupId>
<artifactId>httpcoreartifactId>
<version>4.2.2version>
dependency>
<dependency>
<groupId>org.joddgroupId>
<artifactId>jodd-httpartifactId>
<version>3.7version>
dependency>
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”);