下面列出了org.apache.http.client.methods.CloseableHttpResponse#getFirstHeader() 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
public UrlContent getResourceContent(String sessionId, String url, boolean insecure) throws IOException {
CommonHttpClientBuilder builder = new CommonHttpClientBuilder().maxConnections(CONNECTION_POOL_SIZE)
.useSystemProperties()
.insecure(insecure);
try (CloseableHttpClient client = builder.build()) {
CloseableHttpResponse response = createAndExecuteRequest(sessionId, url, client);
Header contentDispositionHeader = response.getFirstHeader("Content-Disposition");
String filename;
if (contentDispositionHeader != null &&
contentDispositionHeader.getValue().matches(CONTENT_DISPOSITIOB_REGEXP)) {
filename = contentDispositionHeader.getValue().replaceFirst(CONTENT_DISPOSITIOB_REGEXP, "$1");
} else {
filename = FileUtils.getFileNameWithExtension(new URL(url));
}
return new UrlContent(readContent(response.getEntity().getContent()), filename);
}
}
@Test
public void getShouldReturnFileContentsWithNameInHeader() throws IOException {
File fileToGet = File.createTempFile("test filename with spaces", ".txt");
FileUtils.write(fileToGet, "expected_content", StandardCharsets.UTF_8);
CloseableHttpClient httpClient = HttpClients.createDefault();
String encode = Base64.getUrlEncoder().encodeToString(fileToGet.getAbsolutePath().getBytes(StandardCharsets.UTF_8));
HttpGet httpGet = new HttpGet("/FileDownloadServlet/" + encode);
CloseableHttpResponse execute = httpClient.execute(serverHost, httpGet);
//check contents are properly sent
try (
InputStream content = execute.getEntity().getContent()) {
String s = IOUtils.toString(content, StandardCharsets.UTF_8);
assertThat(s, is("expected_content"));
}
//check file name is available from header
Header contentDispositionHeader = execute.getFirstHeader(HttpHeaders.CONTENT_DISPOSITION);
assertThat(contentDispositionHeader.getValue(), containsString("filename=" + fileToGet.getName()));
//check file is not locked by anything
assertTrue(fileToGet.delete());
}
public int postMessage(String content, String type) throws IOException {
String postUri;
String nextMsgUri = contextMap.get(KEY_MSG_CREATE_NEXT);
if (nextMsgUri == null) {
postUri = contextMap.get(KEY_MSG_CREATE);
} else {
postUri = nextMsgUri;
}
CloseableHttpResponse response = connection.post(postUri, type, content);
int code = -1;
try {
code = ResponseUtil.getHttpCode(response);
// check redirection
if (code == 307) {
Header redirLoc = response.getFirstHeader("Location");
contextMap.put(KEY_MSG_CREATE_NEXT, redirLoc.getValue());
code = postMessage(content, type);// do it again.
} else if (code == 201) {
Header header = response.getFirstHeader(KEY_MSG_CREATE_NEXT);
contextMap.put(KEY_MSG_CREATE_NEXT, header.getValue());
}
} finally {
response.close();
}
return code;
}
private void getAndCompare(String address,
String expectedValue,
String acceptType,
String expectedContentType,
int expectedStatus) throws Exception {
CloseableHttpClient client = HttpClientBuilder.create().build();
HttpGet get = new HttpGet(address);
get.setHeader("Accept", acceptType);
get.setHeader("Accept-Language", "da;q=0.8,en");
get.setHeader("Book", "1,2,3");
try {
CloseableHttpResponse response = client.execute(get);
assertEquals(expectedStatus, response.getStatusLine().getStatusCode());
String content = EntityUtils.toString(response.getEntity());
assertEquals("Expected value is wrong",
stripXmlInstructionIfNeeded(expectedValue), stripXmlInstructionIfNeeded(content));
if (expectedContentType != null) {
Header ct = response.getFirstHeader("Content-Type");
assertEquals("Wrong type of response", expectedContentType, ct.getValue());
}
} finally {
get.releaseConnection();
}
}
public void writeResponse(CloseableHttpResponse closeResponse, HttpServletResponse res) throws IOException {
String mes = EntityUtils.toString(closeResponse.getEntity());
log.info("response: " + mes);
Header encode = closeResponse.getFirstHeader(CONTENT_TYPE);
res.setHeader(encode.getName(), encode.getValue());
ServletOutputStream out = res.getOutputStream();
out.write(mes.getBytes());
}
protected final void validateParameters(CloseableHttpResponse response) {
String requestId;
if (!response.containsHeader("Request-ID")) {
throw parameterError("empty Request-ID");
} else {
requestId = response.getFirstHeader("Request-ID").getValue();
}
if (!response.containsHeader("Wechatpay-Serial")) {
throw parameterError("empty Wechatpay-Serial, request-id=[%s]", requestId);
} else if (!response.containsHeader("Wechatpay-Signature")){
throw parameterError("empty Wechatpay-Signature, request-id=[%s]", requestId);
} else if (!response.containsHeader("Wechatpay-Timestamp")) {
throw parameterError("empty Wechatpay-Timestamp, request-id=[%s]", requestId);
} else if (!response.containsHeader("Wechatpay-Nonce")) {
throw parameterError("empty Wechatpay-Nonce, request-id=[%s]", requestId);
} else {
Header timestamp = response.getFirstHeader("Wechatpay-Timestamp");
try {
Instant instant = Instant.ofEpochSecond(Long.parseLong(timestamp.getValue()));
// 拒绝5分钟之外的应答
if (Duration.between(instant, Instant.now()).abs().toMinutes() >= 5) {
throw parameterError("timestamp=[%s] expires, request-id=[%s]",
timestamp.getValue(), requestId);
}
} catch (DateTimeException | NumberFormatException e) {
throw parameterError("invalid timestamp=[%s], request-id=[%s]",
timestamp.getValue(), requestId);
}
}
}
@Override
public void initPullConsumers() throws IOException {
String pullUri = getPullConsumerUri();
CloseableHttpResponse response = null;
if (!this.autoAck) {
response = connection.post(pullUri, "application/x-www-form-urlencoded", "autoAck=false");
} else {
response = connection.post(pullUri);
}
try {
int code = ResponseUtil.getHttpCode(response);
if (code == 201) {
Header header = response.getFirstHeader("Location");
contextMap.put(KEY_PULL_CONSUMERS_LOC, header.getValue());
header = response.getFirstHeader(KEY_MSG_CONSUME_NEXT);
contextMap.put(KEY_MSG_CONSUME_NEXT, header.getValue());
header = response.getFirstHeader(KEY_MSG_ACK_NEXT);
if (header != null) {
contextMap.put(KEY_MSG_ACK_NEXT, header.getValue());
}
}
} finally {
response.close();
}
}
private void prepareSelf() throws IOException {
String destLink = getDestLink();
CloseableHttpResponse response = connection.request(destLink);
int code = ResponseUtil.getHttpCode(response);
if (code != 200) {
System.out.println("failed to init " + destLink);
System.out.println("reason: " + ResponseUtil.getDetails(response));
}
try {
Header header = response.getFirstHeader(KEY_MSG_CREATE);
contextMap.put(KEY_MSG_CREATE, header.getValue());
header = response.getFirstHeader(KEY_MSG_CREATE_ID);
contextMap.put(KEY_MSG_CREATE_ID, header.getValue());
header = response.getFirstHeader(KEY_MSG_PULL);
if (header != null) {
contextMap.put(KEY_MSG_PULL, header.getValue());
}
header = response.getFirstHeader(KEY_MSG_PUSH);
if (header != null) {
contextMap.put(KEY_MSG_PUSH, header.getValue());
}
header = response.getFirstHeader(KEY_MSG_PULL_SUB);
if (header != null) {
contextMap.put(KEY_MSG_PULL_SUB, header.getValue());
}
header = response.getFirstHeader(KEY_MSG_PUSH_SUB);
if (header != null) {
contextMap.put(KEY_MSG_PUSH_SUB, header.getValue());
}
} finally {
response.close();
}
}
@Override
public void initPullConsumers() throws IOException {
String pullUri = getPullConsumerUri();
CloseableHttpResponse response = null;
if (this.durableSub || !this.autoAck) {
String extraOpt = "durable=" + this.durableSub + "&autoAck=" + this.autoAck;
response = connection.post(pullUri, "application/x-www-form-urlencoded", extraOpt);
} else {
response = connection.post(pullUri);
}
int code = ResponseUtil.getHttpCode(response);
try {
if (code == 201) {
Header header = response.getFirstHeader("Location");
contextMap.put(KEY_PULL_CONSUMERS_LOC, header.getValue());
header = response.getFirstHeader(KEY_MSG_CONSUME_NEXT);
contextMap.put(KEY_MSG_CONSUME_NEXT, header.getValue());
header = response.getFirstHeader(KEY_MSG_ACK_NEXT);
if (header != null) {
contextMap.put(KEY_MSG_ACK_NEXT, header.getValue());
}
} else {
throw new IllegalStateException("Failed to init pull consumer " + ResponseUtil.getDetails(response));
}
} finally {
response.close();
}
}
private void getAndCompare(String address,
String expectedValue,
String acceptType,
String expectedContentType,
int expectedStatus) throws Exception {
CloseableHttpClient client = HttpClientBuilder.create().build();
HttpGet get = new HttpGet(address);
get.addHeader("Accept", acceptType);
get.addHeader("Cookie", "a=b;c=d");
get.addHeader("Cookie", "e=f");
get.addHeader("Accept-Language", "da;q=0.8,en");
get.addHeader("Book", "1,2,3");
try {
CloseableHttpResponse response = client.execute(get);
assertEquals(expectedStatus, response.getStatusLine().getStatusCode());
String content = EntityUtils.toString(response.getEntity());
assertEquals("Expected value is wrong",
stripXmlInstructionIfNeeded(expectedValue), stripXmlInstructionIfNeeded(content));
if (expectedStatus == 200) {
assertEquals("123", response.getFirstHeader("BookId").getValue());
assertNotNull(response.getFirstHeader("Date"));
}
if (expectedStatus == 405) {
assertNotNull(response.getFirstHeader("Allow"));
}
if (expectedContentType != null) {
Header ct = response.getFirstHeader("Content-Type");
assertEquals("Wrong type of response", expectedContentType, ct.getValue());
}
} finally {
get.releaseConnection();
}
}
private void validateMd5(String currentMd5, CloseableHttpResponse response, String agentContentMd5Header, String what) {
final Header md5Header = response.getFirstHeader(agentContentMd5Header);
LOGGER.debug("[Agent Upgrade Validate MD5] validating MD5 for {}, currentMD5:{}, responseMD5:{}, headerKey:{}", what, currentMd5, md5Header, agentContentMd5Header);
if (md5Header == null) {
LOGGER.debug("[Agent Upgrade Validate MD5] Did not find {} MD5 header in response {}.", agentContentMd5Header, response);
}
if (!"".equals(currentMd5)) {
if (!currentMd5.equals(md5Header.getValue())) {
jvmExitter.jvmExit(what, currentMd5, md5Header.getValue());
}
}
}
@Test
public void payPage() throws ParseException, Exception {
String mobile = "13249073372";
String email= "[email protected]";
String phoneVerifyCode="874501";
CookieStore cookieStore = valueOperations.get(mobile);
HttpClientContext httpClientContext = HttpClientContext.create();
httpClientContext.setCookieStore(cookieStore);
String url = UriComponentsBuilder.fromHttpUrl("https://upay.10010.com/npfweb/NpfWeb/buyCard/buyCardSubmit").build().toUriString();
HttpPost request = new HttpPost(url);
Map<String, String> params = new HashMap<String,String>();
params.put("cardBean.cardValueCode", "04");
params.put("offerPriceStrHidden", "100.00");
params.put("offerRateStrHidden", "1");
params.put("cardBean.cardValue", "100");
params.put("cardBean.minCardNum", "1");
params.put("cardBean.maxCardNum", "3");
params.put("MaxThreshold01", "15");
params.put("MinThreshold01", "1");
params.put("MaxThreshold02", "10");
params.put("MinThreshold02", "1");
params.put("MaxThreshold03", "6");
params.put("MinThreshold03", "1");
params.put("MaxThreshold04", "3");
params.put("MinThreshold04", "1");
params.put("commonBean.channelType", "101");
//params.put("secstate.state", IOUtils.toString(new FileReader("/Users/hdf/Desktop/1.txt")));
params.put("secstate.state", "FYlSiTsg5fqfr+wYGrqIRsetX8HDhLNTieb9/vhIHd1T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\\ntznwNHFrIryz4RMaSbajBXdHu6sBynPBa1CjOxTg44x2YdaTJiIspnYZF3qkp3eewmp7z+UxZJwp\\n1Jjfn5GsuzIs3V/O4ktBFkZTYL17fU5o/GxTmm8uMbp6ByV71RgzvqLo2nvRah3jypNtjN+ZrrTL\\n9JfwSm9YD82ecsrgIuRBiuUDibk7thXTNISBcSxtLhuSdsfonEKVJNnKKNb5G9+b8+ZGEl/Zbbkm\\n6QstnWr9nQL4kb0VhZmZTJfzfx7x2DiV+/BqLDSReHo6^@^0.0.1");
params.put("cardBean.buyCardAmount", "1");
params.put("cardBean.buyCardEmail", email);
params.put("cardBean.buyCardPhoneNo", mobile);
params.put("phoneVerifyCode",phoneVerifyCode);
params.put("invoiceBean.need_invoice", " 0");
params.put("invoiceBean.invoice_type ", "");
params.put("invoiceBean.is_mailing", "0");
params.put("saveflag ", "false");
params.put("commonBean.provinceCode", "");
params.put("commonBean.cityCode", "");
params.put("invoiceBean.invoice_list ", "");
request.setEntity(getUrlEncodedFormEntity(params));
request.setHeader("Referer", "https://upay.10010.com/npfweb/npfbuycardweb/buycard_recharge_fill.htm");
request.setHeader("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.181 Safari/537.36");
CloseableHttpResponse response = client.execute(request, httpClientContext);
System.out.println("response:" + JSON.toJSONString(response));
if (HttpStatus.SC_OK == response.getStatusLine().getStatusCode()) {// 成功
HttpEntity entity = response.getEntity();
if (null != entity) {
String result = EntityUtils.toString(entity, "UTF-8");
EntityUtils.consume(entity);
System.out.println("result" + result);
} else {
throw new ServiceException("请求无数据返回");
}
} else if (response.getStatusLine().getStatusCode() == 302) {
Header header = response.getFirstHeader("location"); // 跳转的目标地址是在 HTTP-HEAD 中的
String newuri = header.getValue(); // 这就是跳转后的地址,再向这个地址发出新申请,以便得到跳转后的信息是啥。
System.out.println("redirect url:" + newuri);
HttpGet redirectRequest = new HttpGet(newuri);
CloseableHttpResponse response2 = client.execute(redirectRequest, httpClientContext);
System.out.println("response2:" + JSON.toJSONString(response2));
} else {
throw new ServiceException("请求状态异常失败");
}
}
public String getRedirectLocation(CloseableHttpResponse r) {
Header locationHeader = r.getFirstHeader("Location");
assertNotNull(locationHeader);
return locationHeader.getValue();
}
/**
*
* @param url
* the url to retrive
* @param lastModified
* header we got last time we queried that url, or null
* @param eTag
* header we got last time we queried that url, or null
* @return
* @throws ClientProtocolException
* @throws IOException
* @throws NotModifiedException
* if the url hasn't changed since we asked for it last time
*/
public HttpResult getBinary(String url, String lastModified, String eTag, int timeout) throws ClientProtocolException, IOException,
NotModifiedException {
HttpResult result = null;
long start = System.currentTimeMillis();
CloseableHttpClient client = newClient(timeout);
CloseableHttpResponse response = null;
try {
HttpGet httpget = new HttpGet(url);
HttpClientContext context = HttpClientContext.create();
httpget.addHeader(HttpHeaders.ACCEPT_LANGUAGE, ACCEPT_LANGUAGE);
httpget.addHeader(HttpHeaders.PRAGMA, PRAGMA_NO_CACHE);
httpget.addHeader(HttpHeaders.CACHE_CONTROL, CACHE_CONTROL_NO_CACHE);
httpget.addHeader(HttpHeaders.USER_AGENT, userAgent);
if (lastModified != null) {
httpget.addHeader(HttpHeaders.IF_MODIFIED_SINCE, lastModified);
}
if (eTag != null) {
httpget.addHeader(HttpHeaders.IF_NONE_MATCH, eTag);
}
try {
response = client.execute(httpget, context);
int code = response.getStatusLine().getStatusCode();
if (code == HttpStatus.SC_NOT_MODIFIED) {
throw new NotModifiedException("'304 - not modified' http code received");
} else if (code >= 300) {
throw new HttpResponseException(code, "Server returned HTTP error code " + code);
}
} catch (HttpResponseException e) {
if (e.getStatusCode() == HttpStatus.SC_NOT_MODIFIED) {
throw new NotModifiedException("'304 - not modified' http code received");
} else {
throw e;
}
}
Header lastModifiedHeader = response.getFirstHeader(HttpHeaders.LAST_MODIFIED);
String lastModifiedHeaderValue = lastModifiedHeader == null ? null : StringUtils.trimToNull(lastModifiedHeader.getValue());
if (lastModifiedHeaderValue != null && StringUtils.equals(lastModified, lastModifiedHeaderValue)) {
throw new NotModifiedException("lastModifiedHeader is the same");
}
Header eTagHeader = response.getFirstHeader(HttpHeaders.ETAG);
String eTagHeaderValue = eTagHeader == null ? null : StringUtils.trimToNull(eTagHeader.getValue());
if (eTag != null && StringUtils.equals(eTag, eTagHeaderValue)) {
throw new NotModifiedException("eTagHeader is the same");
}
HttpEntity entity = response.getEntity();
byte[] content = null;
String contentType = null;
if (entity != null) {
content = EntityUtils.toByteArray(entity);
if (entity.getContentType() != null) {
contentType = entity.getContentType().getValue();
}
}
String urlAfterRedirect = url;
if (context.getRequest() instanceof HttpUriRequest) {
HttpUriRequest req = (HttpUriRequest) context.getRequest();
HttpHost host = context.getTargetHost();
urlAfterRedirect = req.getURI().isAbsolute() ? req.getURI().toString() : host.toURI() + req.getURI();
}
long duration = System.currentTimeMillis() - start;
result = new HttpResult(content, contentType, lastModifiedHeaderValue, eTagHeaderValue, duration, urlAfterRedirect);
} finally {
IOUtils.closeQuietly(response);
IOUtils.closeQuietly(client);
}
return result;
}