nas延迟机制(cookie)

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.apache.http.HeaderIterator;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
import org.apache.http.client.CookieStore;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.cookie.BasicClientCookie;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

public class HttpClient {
// 创建CookieStore实例
static CookieStore cookieStore = null;
static HttpClientContext context = null;
String sendUrl = "";
String getUrl = "";
String openUrl = "";
String loginErrorUrl = "";
String content = "<?xml version=\"1.0\" encoding=\"utf-8\"?><batch-contract-dTO>\n</batch-contract-dTO>";

public String postPrintTask(Map<String, String> parameterMap) {
String returnValue = null;
System.out.println("1.sendxml......");

// // 创建HttpClientBuilder
// HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
// // HttpClient
// CloseableHttpClient client = httpClientBuilder.build();
// 直接创建client
//CloseableHttpClient client = HttpClients.createDefault();
CloseableHttpClient client = HttpClients.custom().setDefaultCookieStore(cookieStore).build();

HttpPost httpPost = new HttpPost(sendUrl);

//设置连接超时
RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(5000).setConnectTimeout(15000).build();//设置请求和传输超时时间
httpPost.setConfig(requestConfig);
try {
UrlEncodedFormEntity postEntity = new UrlEncodedFormEntity(getParam(parameterMap), "utf-8");
httpPost.setEntity(postEntity);
System.out.println("request line:" + httpPost.getRequestLine());
// 执行post请求
HttpResponse httpResponse = client.execute(httpPost);
String cookie = httpResponse.getFirstHeader("Set-Cookie").getValue();
if (cookie != null && cookie.startsWith(loginErrorUrl)) {
System.out.println("----loginError");
}
System.out.println("cookie:" + cookie);
//printResponse(httpResponse);

int statusCode = httpResponse.getStatusLine().getStatusCode();
if (statusCode != 200) {
return String.valueOf(statusCode);
}
//打印平台返回数据
String returnValueText = StringUtils.castNullToEmpty(EntityUtils.toString(httpResponse.getEntity()));
//返回的returnValue值
returnValue = returnValueText.substring(returnValueText.indexOf("=") + 1);
System.out.println(returnValue + ":" + httpResponse.getEntity().isStreaming());
// cookie store
setCookieStore(httpResponse);
// context
//setContext();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
// 关闭流并释放资源
client.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return returnValue;
}

public String getPdfStream(Map<String, String> parameterMap, String parameterStr) {
System.out.println("3.open.....");
String returnValue = null;
CloseableHttpClient client = HttpClients.custom().setDefaultCookieStore(cookieStore).build();
HttpGet httpGet = new HttpGet(openUrl + parameterStr);
RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(5000).setConnectTimeout(15000).build();//设置请求和传输超时时间
httpGet.setConfig(requestConfig);
System.out.println("request line:" + httpGet.getRequestLine());
try {
int statusCode = -1;
// 执行get请求
HttpResponse httpResponse = client.execute(httpGet);
statusCode = httpResponse.getStatusLine().getStatusCode();
if (statusCode != 200) {
System.out.println("打开pdf流失败.. status=" + statusCode);
return returnValue;
}
//httpResponse.getEntity().getContent()内容不可重复读写,只能一次消耗
BufferedInputStream buff_in = new BufferedInputStream(httpResponse.getEntity().getContent());
ByteArrayOutputStream byte_out = new ByteArrayOutputStream();
byte[] b = new byte[1024];
int read = 0;
while ((read = buff_in.read(b)) > 0) {
byte_out.write(b, 0, read);
}

OutputStream xmlOuts = new FileOutputStream("D:\\aa.pdf");
xmlOuts.write(byte_out.toByteArray());
xmlOuts.flush();
xmlOuts.close();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
// 关闭流并释放资源
client.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return returnValue;
}

public void reqPrintPlat() {
Map<String, String> parameterMap = new HashMap<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方式请求参数
StringBuffer parameterStr = new StringBuffer("?");
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);
String returnValue = postPrintTask(parameterMap);
if ("0".equals(returnValue)) {
returnValue = checkPdfExistWithWait(parameterMap, parameterStr.toString());
if ("0".equals(returnValue)) {
getPdfStream(parameterMap, parameterStr.toString());
}
}
}

public String checkPdfExistWithWait(Map<String, String> parameterMap, String parameterStr) {
System.out.println("2.get.....");
String returnValue = null;
CloseableHttpClient client = HttpClients.custom().setDefaultCookieStore(cookieStore).build();
HttpGet httpGet = new HttpGet(getUrl + parameterStr);
RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(5000).setConnectTimeout(15000).build();//设置请求和传输超时时间
httpGet.setConfig(requestConfig);
System.out.println("request line:" + httpGet.getRequestLine());
try {
int statusCode = -1;
int maxTime = StringUtils.isEmptyStr(parameterMap.get("maxTimeForCheck")) ? (5 * 1000) : Integer
.parseInt(parameterMap.get("maxTimeForCheck"));
//该休眠时间配置值为2000毫秒,代码固定值为500毫秒,优先取配置值
int maxSleepTime = StringUtils.isEmptyStr(parameterMap.get("sleepTime")) ? 500 : Integer
.parseInt(parameterMap.get("sleepTime"));
Date beginDate = new Date();
while (new Date().getTime() - beginDate.getTime() <= maxTime) {
// 执行get请求
HttpResponse httpResponse = client.execute(httpGet);
statusCode = httpResponse.getStatusLine().getStatusCode();
if (statusCode == 200) {
//打印平台返回数据
String returnValueText = 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 (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
try {
// 关闭流并释放资源
client.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return returnValue;
}

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

HttpClient test = new HttpClient();
test.reqPrintPlat();
/*Thread.sleep(3000);
test.testCookieStore();*/

//Thread.sleep(3000);
//test.testContext();
}

public void testContext() throws Exception {
System.out.println("----testContext----");
// 使用context方式
CloseableHttpClient client = HttpClients.custom().setDefaultCookieStore(cookieStore).build();
//CloseableHttpClient client = HttpClients.createDefault();
HttpGet httpGet = new HttpGet(testUrl);
//设置连接超时
RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(5000).setConnectTimeout(15000).build();//设置请求和传输超时时间
httpGet.setConfig(requestConfig);

System.out.println("request line:" + httpGet.getRequestLine());
try {
// 执行get请求
HttpResponse httpResponse = client.execute(httpGet, context);
//System.out.println("context cookies:"+ context.getCookieStore().getCookies());
//printResponse(httpResponse);
String cookie2 = httpResponse.getFirstHeader("Set-Cookie").getValue();
System.out.println("cookie2:" + cookie2);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
// 关闭流并释放资源
client.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}

public static void printResponse(HttpResponse httpResponse) throws ParseException, IOException {
// 获取响应消息实体
HttpEntity entity = httpResponse.getEntity();
// 响应状态
System.out.println("status:" + httpResponse.getStatusLine());
System.out.println("headers:");
HeaderIterator iterator = httpResponse.headerIterator();
while (iterator.hasNext()) {
System.out.println("\t" + iterator.next());
}
// 判断响应实体是否为空
if (entity != null) {
String responseString = EntityUtils.toString(entity);
System.out.println("response length:" + responseString.length());
System.out.println("response content:" + responseString.replace("\r\n", ""));
}
}

/*public static void setContext() {
System.out.println("----setContext");
context = HttpClientContext.create();
Registry<CookieSpecProvider> registry = RegistryBuilder.<CookieSpecProvider> create()
.register(CookieSpecs.BEST_MATCH, new BestMatchSpecFactory())
.register(CookieSpecs.BROWSER_COMPATIBILITY, new BrowserCompatSpecFactory()).build();
context.setCookieSpecRegistry(registry);
context.setCookieStore(cookieStore);
}*/

public static void setCookieStore(HttpResponse httpResponse) {
System.out.println("----setCookieStore");
cookieStore = new BasicCookieStore();
// JSESSIONID
String setCookie = httpResponse.getFirstHeader("Set-Cookie").getValue();
//System.out.println("------setCookie:-------" + setCookie);
String JSESSIONID = setCookie.substring("BIGipServerepcis-print_StgPool=".length(), setCookie.indexOf(";"));
//System.out.println("BIGipServerepcis-print_StgPool:" + JSESSIONID);
// 新建一个Cookie
//BasicClientCookie cookie = new BasicClientCookie("JSESSIONID",JSESSIONID);
BasicClientCookie cookie = new BasicClientCookie("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);
}

public static List<NameValuePair> getParam(Map parameterMap) {
List<NameValuePair> param = new ArrayList<NameValuePair>();
Iterator it = parameterMap.entrySet().iterator();
while (it.hasNext()) {
Entry parmEntry = (Entry) it.next();
param.add(new BasicNameValuePair((String) parmEntry.getKey(), (String) parmEntry.getValue()));
}
return param;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值