nas延迟机制(cookie)

importjava.io.BufferedInputStream;

importjava.io.ByteArrayOutputStream;

importjava.io.FileOutputStream;

importjava.io.IOException;

importjava.io.OutputStream;

importjava.util.ArrayList;

importjava.util.Date;

importjava.util.HashMap;

importjava.util.Iterator;

importjava.util.List;

importjava.util.Map;

importjava.util.Map.Entry;

importorg.apache.http.HeaderIterator;

importorg.apache.http.HttpEntity;

importorg.apache.http.HttpResponse;

importorg.apache.http.NameValuePair;

importorg.apache.http.ParseException;

importorg.apache.http.client.CookieStore;

importorg.apache.http.client.config.RequestConfig;

importorg.apache.http.client.entity.UrlEncodedFormEntity;

importorg.apache.http.client.methods.HttpGet;

importorg.apache.http.client.methods.HttpPost;

importorg.apache.http.client.protocol.HttpClientContext;

importorg.apache.http.impl.client.BasicCookieStore;

importorg.apache.http.impl.client.CloseableHttpClient;

importorg.apache.http.impl.client.HttpClients;

importorg.apache.http.impl.cookie.BasicClientCookie;

importorg.apache.http.message.BasicNameValuePair;

importorg.apache.http.util.EntityUtils;

publicclassHttpClient{

//创建CookieStore实例

staticCookieStorecookieStore=null;

staticHttpClientContextcontext=null;

StringsendUrl="";

StringgetUrl="";

StringopenUrl="";

StringloginErrorUrl="";

Stringcontent="<?xmlversion=\"1.0\"encoding=\"utf-8\"?><batch-contract-dTO>\n</batch-contract-dTO>";

publicStringpostPrintTask(Map<String,String>parameterMap){

StringreturnValue=null;

System.out.println("1.sendxml......");

////创建HttpClientBuilder

//HttpClientBuilderhttpClientBuilder=HttpClientBuilder.create();

////HttpClient

//CloseableHttpClientclient=httpClientBuilder.build();

//直接创建client

//CloseableHttpClientclient=HttpClients.createDefault();

CloseableHttpClientclient=HttpClients.custom().setDefaultCookieStore(cookieStore).build();

HttpPosthttpPost=newHttpPost(sendUrl);

//设置连接超时

RequestConfigrequestConfig=RequestConfig.custom().setSocketTimeout(5000).setConnectTimeout(15000).build();//设置请求和传输超时时间

httpPost.setConfig(requestConfig);

try{

UrlEncodedFormEntitypostEntity=newUrlEncodedFormEntity(getParam(parameterMap),"utf-8");

httpPost.setEntity(postEntity);

System.out.println("requestline:"+httpPost.getRequestLine());

//执行post请求

HttpResponsehttpResponse=client.execute(httpPost);

Stringcookie=httpResponse.getFirstHeader("Set-Cookie").getValue();

if(cookie!=null&&cookie.startsWith(loginErrorUrl)){

System.out.println("----loginError");

}

System.out.println("cookie:"+cookie);

//printResponse(httpResponse);

intstatusCode=httpResponse.getStatusLine().getStatusCode();

if(statusCode!=200){

returnString.valueOf(statusCode);

}

//打印平台返回数据

StringreturnValueText=StringUtils.castNullToEmpty(EntityUtils.toString(httpResponse.getEntity()));

//返回的returnValue值

returnValue=returnValueText.substring(returnValueText.indexOf("=")+1);

System.out.println(returnValue+":"+httpResponse.getEntity().isStreaming());

//cookiestore

setCookieStore(httpResponse);

//context

//setContext();

}catch(IOExceptione){

e.printStackTrace();

}finally{

try{

//关闭流并释放资源

client.close();

}catch(IOExceptione){

e.printStackTrace();

}

}

returnreturnValue;

}

publicStringgetPdfStream(Map<String,String>parameterMap,StringparameterStr){

System.out.println("3.open.....");

StringreturnValue=null;

CloseableHttpClientclient=HttpClients.custom().setDefaultCookieStore(cookieStore).build();

HttpGethttpGet=newHttpGet(openUrl+parameterStr);

RequestConfigrequestConfig=RequestConfig.custom().setSocketTimeout(5000).setConnectTimeout(15000).build();//设置请求和传输超时时间

httpGet.setConfig(requestConfig);

System.out.println("requestline:"+httpGet.getRequestLine());

try{

intstatusCode=-1;

//执行get请求

HttpResponsehttpResponse=client.execute(httpGet);

statusCode=httpResponse.getStatusLine().getStatusCode();

if(statusCode!=200){

System.out.println("打开pdf流失败..status="+statusCode);

returnreturnValue;

}

//httpResponse.getEntity().getContent()内容不可重复读写,只能一次消耗

BufferedInputStreambuff_in=newBufferedInputStream(httpResponse.getEntity().getContent());

ByteArrayOutputStreambyte_out=newByteArrayOutputStream();

byte[]b=newbyte[1024];

intread=0;

while((read=buff_in.read(b))>0){

byte_out.write(b,0,read);

}

OutputStreamxmlOuts=newFileOutputStream("D:\\aa.pdf");

xmlOuts.write(byte_out.toByteArray());

xmlOuts.flush();

xmlOuts.close();

}catch(IOExceptione){

e.printStackTrace();

}finally{

try{

//关闭流并释放资源

client.close();

}catch(IOExceptione){

e.printStackTrace();

}

}

returnreturnValue;

}

publicvoidreqPrintPlat(){

Map<String,String>parameterMap=newHashMap<String,String>();

parameterMap.put("sysid","icoreacss");

parameterMap.put("docno","8888108888100431");

parameterMap.put("doctype","01");

parameterMap.put("xslFileName","I0009");

parameterMap.put("userName","V_PA003_ICORE_ACSS");

parameterMap.put("password","Q52reeE1");

parameterMap.put("isSigned","false");

parameterMap.put("datatype","XML");

parameterMap.put("maxTimeForCheck","50000");

parameterMap.put("sleepTime","2000");

//get方式请求参数

StringBufferparameterStr=newStringBuffer("?");

parameterStr.append("sysid="+parameterMap.get("sysid"));

parameterStr.append("&docno="+parameterMap.get("docno"));

parameterStr.append("&doctype="+parameterMap.get("doctype"));

parameterStr.append("&xslFilename="+parameterMap.get("xslFileName"));

parameterStr.append("&username="+parameterMap.get("userName"));

parameterStr.append("&password="+parameterMap.get("password"));

parameterStr.append("&isSigned="+parameterMap.get("isSigned"));

parameterStr.append("&datatype="+parameterMap.get("datatype"));

System.out.println(parameterStr);

parameterMap.put("xmlString",content);

StringreturnValue=postPrintTask(parameterMap);

if("0".equals(returnValue)){

returnValue=checkPdfExistWithWait(parameterMap,parameterStr.toString());

if("0".equals(returnValue)){

getPdfStream(parameterMap,parameterStr.toString());

}

}

}

publicStringcheckPdfExistWithWait(Map<String,String>parameterMap,StringparameterStr){

System.out.println("2.get.....");

StringreturnValue=null;

CloseableHttpClientclient=HttpClients.custom().setDefaultCookieStore(cookieStore).build();

HttpGethttpGet=newHttpGet(getUrl+parameterStr);

RequestConfigrequestConfig=RequestConfig.custom().setSocketTimeout(5000).setConnectTimeout(15000).build();//设置请求和传输超时时间

httpGet.setConfig(requestConfig);

System.out.println("requestline:"+httpGet.getRequestLine());

try{

intstatusCode=-1;

intmaxTime=StringUtils.isEmptyStr(parameterMap.get("maxTimeForCheck"))?(5*1000):Integer

.parseInt(parameterMap.get("maxTimeForCheck"));

//该休眠时间配置值为2000毫秒,代码固定值为500毫秒,优先取配置值

intmaxSleepTime=StringUtils.isEmptyStr(parameterMap.get("sleepTime"))?500:Integer

.parseInt(parameterMap.get("sleepTime"));

DatebeginDate=newDate();

while(newDate().getTime()-beginDate.getTime()<=maxTime){

//执行get请求

HttpResponsehttpResponse=client.execute(httpGet);

statusCode=httpResponse.getStatusLine().getStatusCode();

if(statusCode==200){

//打印平台返回数据

StringreturnValueText=StringUtils

.castNullToEmpty(EntityUtils.toString(httpResponse.getEntity()));

//返回的returnValue值

returnValue=returnValueText.substring(returnValueText.indexOf("=")+1);

if("0".equals(returnValue)){

System.out.println("get成功:"+returnValue);

break;

}

}

System.out.println("getPdf:"+returnValue+":"+httpResponse.getEntity().isStreaming());

//线程休眠

Thread.sleep(maxSleepTime);

}

}catch(IOExceptione){

e.printStackTrace();

}catch(InterruptedExceptione){

e.printStackTrace();

}finally{

try{

//关闭流并释放资源

client.close();

}catch(IOExceptione){

e.printStackTrace();

}

}

returnreturnValue;

}

publicstaticvoidmain(String[]args)throwsException{

HttpClienttest=newHttpClient();

test.reqPrintPlat();

/*Thread.sleep(3000);

test.testCookieStore();*/

//Thread.sleep(3000);

//test.testContext();

}

publicvoidtestContext()throwsException{

System.out.println("----testContext----");

//使用context方式

CloseableHttpClientclient=HttpClients.custom().setDefaultCookieStore(cookieStore).build();

//CloseableHttpClientclient=HttpClients.createDefault();

HttpGethttpGet=newHttpGet(testUrl);

//设置连接超时

RequestConfigrequestConfig=RequestConfig.custom().setSocketTimeout(5000).setConnectTimeout(15000).build();//设置请求和传输超时时间

httpGet.setConfig(requestConfig);

System.out.println("requestline:"+httpGet.getRequestLine());

try{

//执行get请求

HttpResponsehttpResponse=client.execute(httpGet,context);

//System.out.println("contextcookies:"+context.getCookieStore().getCookies());

//printResponse(httpResponse);

Stringcookie2=httpResponse.getFirstHeader("Set-Cookie").getValue();

System.out.println("cookie2:"+cookie2);

}catch(IOExceptione){

e.printStackTrace();

}finally{

try{

//关闭流并释放资源

client.close();

}catch(IOExceptione){

e.printStackTrace();

}

}

}

publicstaticvoidprintResponse(HttpResponsehttpResponse)throwsParseException,IOException{

//获取响应消息实体

HttpEntityentity=httpResponse.getEntity();

//响应状态

System.out.println("status:"+httpResponse.getStatusLine());

System.out.println("headers:");

HeaderIteratoriterator=httpResponse.headerIterator();

while(iterator.hasNext()){

System.out.println("\t"+iterator.next());

}

//判断响应实体是否为空

if(entity!=null){

StringresponseString=EntityUtils.toString(entity);

System.out.println("responselength:"+responseString.length());

System.out.println("responsecontent:"+responseString.replace("\r\n",""));

}

}

/*publicstaticvoidsetContext(){

System.out.println("----setContext");

context=HttpClientContext.create();

Registry<CookieSpecProvider>registry=RegistryBuilder.<CookieSpecProvider>create()

.register(CookieSpecs.BEST_MATCH,newBestMatchSpecFactory())

.register(CookieSpecs.BROWSER_COMPATIBILITY,newBrowserCompatSpecFactory()).build();

context.setCookieSpecRegistry(registry);

context.setCookieStore(cookieStore);

}*/

publicstaticvoidsetCookieStore(HttpResponsehttpResponse){

System.out.println("----setCookieStore");

cookieStore=newBasicCookieStore();

//JSESSIONID

StringsetCookie=httpResponse.getFirstHeader("Set-Cookie").getValue();

//System.out.println("------setCookie:-------"+setCookie);

StringJSESSIONID=setCookie.substring("BIGipServerepcis-print_StgPool=".length(),setCookie.indexOf(";"));

//System.out.println("BIGipServerepcis-print_StgPool:"+JSESSIONID);

//新建一个Cookie

//BasicClientCookiecookie=newBasicClientCookie("JSESSIONID",JSESSIONID);

BasicClientCookiecookie=newBasicClientCookie("BIGipServerepcis-print_StgPool",JSESSIONID);

cookie.setVersion(0);

cookie.setDomain("epcisprint-staging.paic.com.cn");

cookie.setPath("/");

//cookie.setAttribute(ClientCookie.VERSION_ATTR,"0");

//cookie.setAttribute(ClientCookie.DOMAIN_ATTR,"127.0.0.1");

//cookie.setAttribute(ClientCookie.PORT_ATTR,"8080");

//cookie.setAttribute(ClientCookie.PATH_ATTR,"/CwlProWeb");

cookieStore.addCookie(cookie);

}

publicstaticList<NameValuePair>getParam(MapparameterMap){

List<NameValuePair>param=newArrayList<NameValuePair>();

Iteratorit=parameterMap.entrySet().iterator();

while(it.hasNext()){

EntryparmEntry=(Entry)it.next();

param.add(newBasicNameValuePair((String)parmEntry.getKey(),(String)parmEntry.getValue()));

}

returnparam;

}