Java Code Examples for org.apache.http.httpresponse#getHeaders()
The following examples show how to use
org.apache.http.httpresponse#getHeaders() .
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ClientCertTestCase.java From quarkus-http with Apache License 2.0 | 6 votes |
@Test @Ignore("UT3 - P3") public void testClientCertSuccess() throws Exception { TestHttpClient client = new TestHttpClient(); client.setSSLContext(clientSSLContext); HttpGet get = new HttpGet(DefaultServer.getDefaultServerSSLAddress()); HttpResponse result = client.execute(get); assertEquals(StatusCodes.OK, result.getStatusLine().getStatusCode()); Header[] values = result.getHeaders("ProcessedBy"); assertEquals("ProcessedBy Headers", 1, values.length); assertEquals("ResponseHandler", values[0].getValue()); values = result.getHeaders("AuthenticatedUser"); assertEquals("AuthenticatedUser Headers", 1, values.length); assertEquals("CN=Test Client,OU=OU,O=Org,L=City,ST=State,C=GB", values[0].getValue()); HttpClientUtils.readResponse(result); assertSingleNotificationType(EventType.AUTHENTICATED); }
Example 2
Source File: SdsTHttpClient.java From galaxy-sdk-java with Apache License 2.0 | 6 votes |
/** * Adjust local clock when clock skew error received from server. The client clock need to be * roughly synchronized with server clock to make signature secure and reduce the chance of replay * attacks. * * @param response server response * @param httpStatusCode status code * @return if clock is adjusted */ private boolean adjustClock(HttpResponse response, int httpStatusCode) { if (httpStatusCode == HttpStatusCode.CLOCK_TOO_SKEWED.getValue()) { Header[] headers = response.getHeaders(AuthenticationConstants.HK_TIMESTAMP); for (Header h : headers) { String hv = h.getValue(); long serverTime = Long.parseLong(hv); long min = 60 * 60 * 24 * 365 * (2010 - 1970); long max = 60 * 60 * 24 * 365 * (2030 - 1970); if (serverTime > min && serverTime < max) { LOG.debug("Adjusting client time from {} to {}", new Date(clock.getCurrentEpoch() * 1000), new Date(serverTime * 1000)); clock.adjust(serverTime); return true; } } } return false; }
Example 3
Source File: SimpleSSLTestCase.java From quarkus-http with Apache License 2.0 | 6 votes |
@Test public void simpleSSLTestCase() throws IOException, GeneralSecurityException { DefaultServer.setRootHandler(new HttpHandler() { @Override public void handleRequest(final HttpServerExchange exchange) throws Exception { exchange.setResponseHeader("scheme", exchange.getRequestScheme()); exchange.endExchange(); } }); DefaultServer.startSSLServer(); TestHttpClient client = new TestHttpClient(); client.setSSLContext(DefaultServer.getClientSSLContext()); try { HttpGet get = new HttpGet(DefaultServer.getDefaultServerSSLAddress()); HttpResponse result = client.execute(get); Assert.assertEquals(StatusCodes.OK, result.getStatusLine().getStatusCode()); Header[] header = result.getHeaders("scheme"); Assert.assertEquals("https", header[0].getValue()); } finally { client.getConnectionManager().shutdown(); DefaultServer.stopSSLServer(); } }
Example 4
Source File: CrossOriginSimpleTest.java From cxf with Apache License 2.0 | 6 votes |
private void assertOriginResponse(boolean allOrigins, String[] requestOrigins, boolean permitted, HttpResponse response) { Header[] aaoHeaders = response.getHeaders(CorsHeaderConstants.HEADER_AC_ALLOW_ORIGIN); if (permitted) { assertNotNull(aaoHeaders); if (allOrigins) { assertEquals(1, aaoHeaders.length); assertEquals("*", aaoHeaders[0].getValue()); } else { List<String> ovalues = headerValues(aaoHeaders); assertEquals(1, ovalues.size()); // get back one ac-allow-origin header. String[] origins = ovalues.get(0).split(" +"); for (int x = 0; x < requestOrigins.length; x++) { assertEquals(requestOrigins[x], origins[x]); } } } else { // Origin: null? We don't use it and it's not in the CORS spec. assertTrue(aaoHeaders == null || aaoHeaders.length == 0); } }
Example 5
Source File: DateHandlerTestCase.java From quarkus-http with Apache License 2.0 | 6 votes |
@Test public void testDateHandler() throws IOException, InterruptedException { HttpGet get = new HttpGet(DefaultServer.getDefaultServerURL() + "/path"); TestHttpClient client = new TestHttpClient(); try { HttpResponse result = client.execute(get); Assert.assertEquals(StatusCodes.OK, result.getStatusLine().getStatusCode()); Header date = result.getHeaders("Date")[0]; final long firstDate = DateUtils.parseDate(date.getValue()).getTime(); Assert.assertTrue((firstDate + 3000) > System.currentTimeMillis()); Assert.assertTrue(System.currentTimeMillis() >= firstDate); HttpClientUtils.readResponse(result); Thread.sleep(1500); result = client.execute(get); Assert.assertEquals(StatusCodes.OK, result.getStatusLine().getStatusCode()); date = result.getHeaders("Date")[0]; final long secondDate = DateUtils.parseDate(date.getValue()).getTime(); Assert.assertTrue((secondDate + 2000) > System.currentTimeMillis()); Assert.assertTrue(System.currentTimeMillis() >= secondDate); Assert.assertTrue(secondDate > firstDate); HttpClientUtils.readResponse(result); } finally { client.getConnectionManager().shutdown(); } }
Example 6
Source File: MixerHttpClient.java From beam-client-java with MIT License | 5 votes |
/** * Checks the response for an X-JWT header so we can parse it. * @param partialResponse */ private void handleJWT(HttpResponse partialResponse) { Header[] jwtHeaders = partialResponse.getHeaders(X_JWT_HEADER); if (jwtHeaders.length > 0) { Header jwtHeader = jwtHeaders[0]; this.jwtString = jwtHeader.getValue(); this.jwt = parseJWTData(jwtHeader.getValue()); } }
Example 7
Source File: ClientUtils.java From org.hl7.fhir.core with Apache License 2.0 | 5 votes |
protected String getLocationHeader(HttpResponse response) { String location = null; if(response.getHeaders("location").length > 0) {//TODO Distinguish between both cases if necessary location = response.getHeaders("location")[0].getValue(); } else if(response.getHeaders("content-location").length > 0) { location = response.getHeaders("content-location")[0].getValue(); } return location; }
Example 8
Source File: ClientUtils.java From org.hl7.fhir.core with Apache License 2.0 | 5 votes |
protected String getLocationHeader(HttpResponse response) { String location = null; if(response.getHeaders("location").length > 0) {//TODO Distinguish between both cases if necessary location = response.getHeaders("location")[0].getValue(); } else if(response.getHeaders("content-location").length > 0) { location = response.getHeaders("content-location")[0].getValue(); } return location; }
Example 9
Source File: MoveResponseHeader.java From esigate with Apache License 2.0 | 5 votes |
/** * This method can be used directly to move an header. * * @param response * HTTP response * @param srcName * source header name * @param targetName * target header name */ public static void moveHeader(HttpResponse response, String srcName, String targetName) { if (response.containsHeader(srcName)) { LOG.info("Moving header {} to {}", srcName, targetName); Header[] headers = response.getHeaders(srcName); response.removeHeaders(targetName); for (Header h : headers) { response.addHeader(targetName, h.getValue()); } response.removeHeaders(srcName); } }
Example 10
Source File: BinaryHttpResponseHandler.java From Libraries-for-Android-Developers with MIT License | 5 votes |
@Override public final void sendResponseMessage(HttpResponse response) throws IOException { StatusLine status = response.getStatusLine(); Header[] contentTypeHeaders = response.getHeaders("Content-Type"); if (contentTypeHeaders.length != 1) { //malformed/ambiguous HTTP Header, ABORT! sendFailureMessage(status.getStatusCode(), response.getAllHeaders(), null, new HttpResponseException(status.getStatusCode(), "None, or more than one, Content-Type Header found!")); return; } Header contentTypeHeader = contentTypeHeaders[0]; boolean foundAllowedContentType = false; for (String anAllowedContentType : getAllowedContentTypes()) { try { if (Pattern.matches(anAllowedContentType, contentTypeHeader.getValue())) { foundAllowedContentType = true; } } catch (PatternSyntaxException e) { Log.e("BinaryHttpResponseHandler", "Given pattern is not valid: " + anAllowedContentType, e); } } if (!foundAllowedContentType) { //Content-Type not in allowed list, ABORT! sendFailureMessage(status.getStatusCode(), response.getAllHeaders(), null, new HttpResponseException(status.getStatusCode(), "Content-Type not allowed!")); return; } super.sendResponseMessage(response); }
Example 11
Source File: TokenDemo.java From ais-sdk with Apache License 2.0 | 5 votes |
/** * 获取Token参数, 注意,此函数的目的,主要为了从HTTP请求返回体中的Header中提取出Token * 参数名为: X-Subject-Token * * @param username 用户名 * @param password 密码 * @param projectName 区域名,可以参考http://developer.huaweicloud.com/dev/endpoint * @return 包含Token串的返回体, * @throws URISyntaxException * @throws UnsupportedOperationException * @throws IOException */ private static String getToken(String username, String password, String projectName) throws URISyntaxException, UnsupportedOperationException, IOException { String requestBody = requestBody(username, password, username, projectName); String url ="https://iam.cn-north-1.myhuaweicloud.com/v3/auth/tokens"; Header[] headers = new Header[] { new BasicHeader("Content-Type", ContentType.APPLICATION_JSON.toString()) }; StringEntity stringEntity = new StringEntity(requestBody, "utf-8"); HttpResponse response = HttpClientUtils.post(url, headers, stringEntity, connectionTimeout, connectionRequestTimeout, socketTimeout); Header[] xst = response.getHeaders("X-Subject-Token"); return xst[0].getValue(); }
Example 12
Source File: AopHttpClient.java From ArgusAPM with Apache License 2.0 | 5 votes |
private static HttpResponse handleResponse(HttpResponse response, NetInfo data) { data.setStatusCode(response.getStatusLine().getStatusCode()); Header[] headers = response.getHeaders("Content-Length"); if ((headers != null) && (headers.length > 0)) { try { long l = Long.parseLong(headers[0].getValue()); data.setReceivedBytes(l); if (DEBUG) { LogX.d(TAG, SUB_TAG, "-handleResponse--end--1"); } data.end(); } catch (NumberFormatException e) { if (Env.DEBUG) { LogX.d(TAG, SUB_TAG, "NumberFormatException ex : " + e.getMessage()); } } } else if (response.getEntity() != null) { response.setEntity(new AopHttpResponseEntity(response.getEntity(), data)); } else { data.setReceivedBytes(0); if (DEBUG) { LogX.d(TAG, SUB_TAG, "----handleResponse--end--2"); } data.end(); } if (DEBUG) { LogX.d(TAG, SUB_TAG, "execute:" + data.toString()); } return response; }
Example 13
Source File: DcResponse.java From io with Apache License 2.0 | 5 votes |
/** * レスポンスボディのストリームを受け取る. * @param res Responseオブジェクト * @return ストリーム * @throws IOException IO例外 */ protected final InputStream getResponseBodyInputStream(final HttpResponse res) throws IOException { // GZip 圧縮されていたら解凍する。 Header[] contentEncodingHeaders = res.getHeaders("Content-Encoding"); if (contentEncodingHeaders.length > 0 && "gzip".equalsIgnoreCase(contentEncodingHeaders[0].getValue())) { return new GZIPInputStream(res.getEntity().getContent()); } else { return res.getEntity().getContent(); } }
Example 14
Source File: TokenDemo.java From ais-sdk with Apache License 2.0 | 5 votes |
/** * 获取Token参数, 注意,此函数的目的,主要为了从HTTP请求返回体中的Header中提取出Token * 参数名为: X-Subject-Token * * @param username 用户名 * @param domainname 账户名 * @param password 密码 * @param regionName 区域名,可以参 * @return 包含Token串的返回体, * @throws URISyntaxException * @throws UnsupportedOperationException * @throws IOException */ private static String getToken(String username, String domainname, String password, String regionName) throws URISyntaxException, UnsupportedOperationException, IOException { String requestBody = requestBody(username, password, domainname, regionName); String url ="https://iam.cn-north-1.myhuaweicloud.com/v3/auth/tokens"; Header[] headers = new Header[] { new BasicHeader("Content-Type", ContentType.APPLICATION_JSON.toString()) }; StringEntity stringEntity = new StringEntity(requestBody, "utf-8"); HttpResponse response = HttpClientUtils.post(url, headers, stringEntity, connectionTimeout, connectionRequestTimeout, socketTimeout); Header[] xst = response.getHeaders("X-Subject-Token"); return xst[0].getValue(); }
Example 15
Source File: IAMAccountPasswordValidator.java From aws-iam-ldap-bridge with Apache License 2.0 | 5 votes |
private boolean containsHeaders(HttpResponse response, String... headers) { Header[] headerList = response.getHeaders("Set-Cookie"); Set<String> lookup = new HashSet<String>(Arrays.asList(headers)); for (Header header : headerList) { String value = header.getValue(); if (!value.contains("=")) continue; String[] parts = value.split("="); if (parts.length < 2) continue; lookup.remove(parts[0]); } return lookup.isEmpty(); }
Example 16
Source File: HttpLogin.java From javabase with Apache License 2.0 | 4 votes |
public void login() { CloseableHttpClient httpclient = HttpClients.createDefault(); HttpGet httpGet = new HttpGet(INDEX_URL); try { HttpResponse response = httpclient.execute(httpGet); Header[] cookieHeaders = response.getHeaders("Set-Cookie"); // 设置登录参数 List<NameValuePair> formparams = new ArrayList<NameValuePair>(); formparams.add(new BasicNameValuePair("username", "18638217959")); formparams.add(new BasicNameValuePair("pwd", "1qaz1qaz")); formparams.add(new BasicNameValuePair("target", "http://m.ule.com:80/user/center?source=index")); UrlEncodedFormEntity entity1 = new UrlEncodedFormEntity(formparams, "UTF-8"); // 新建Http post请求 HttpPost httppost = new HttpPost(LOGIN_URL); httppost.setEntity(entity1); for (Header cookieHeader : cookieHeaders) { httppost.addHeader(cookieHeader); // log.info(cookieHeader.getName() + "=" + cookieHeader.getValue()); } EntityUtils.consume(response.getEntity()); HttpResponse responsePost = httpclient.execute(httppost); Header[] loginCookieHeaders = responsePost.getHeaders("Set-Cookie"); EntityUtils.consume(responsePost.getEntity()); //带着cookie去访问 // HttpGet httpGetAddress = new HttpGet(ADDRESS_URL); // for (Header cookieHeader : loginCookieHeaders) { // // log.info(cookieHeader.getName() + "=" + cookieHeader.getValue()); // httpGetAddress.addHeader(cookieHeader); // } // HttpResponse responseAddress = httpclient.execute(httpGetAddress); // String result = EntityUtils.toString(responseAddress.getEntity(), "UTF-8"); // log.info(result); for (int i=0;i<=2560000;i++) praseAddress(httpclient,loginCookieHeaders,i); log.info(""+successLinkedList.size()); } catch (IOException e) { e.printStackTrace(); } }
Example 17
Source File: QCRestHttpClient.java From Cognizant-Intelligent-Test-Scripter with Apache License 2.0 | 4 votes |
public Header[] getCookies(HttpResponse response) { return response.getHeaders("Set-Cookie"); }
Example 18
Source File: CrossOriginSimpleTest.java From cxf with Apache License 2.0 | 4 votes |
private void assertAllowCredentials(HttpResponse response, boolean correct) { Header[] aaoHeaders = response.getHeaders(CorsHeaderConstants.HEADER_AC_ALLOW_CREDENTIALS); assertEquals(1, aaoHeaders.length); assertEquals(Boolean.toString(correct), aaoHeaders[0].getValue()); }
Example 19
Source File: ResponseCachingPolicy.java From apigee-android-sdk with Apache License 2.0 | 4 votes |
/** * Determines if an HttpResponse can be cached. * * @param httpMethod * What type of request was this, a GET, PUT, other? * @param response * The origin response * @return <code>true</code> if response is cacheable */ public boolean isResponseCacheable(String httpMethod, HttpResponse response) { boolean cacheable = false; if (!HeaderConstants.GET_METHOD.equals(httpMethod)) { log.debug("Response was not cacheable."); return false; } switch (response.getStatusLine().getStatusCode()) { case HttpStatus.SC_OK: case HttpStatus.SC_NON_AUTHORITATIVE_INFORMATION: case HttpStatus.SC_MULTIPLE_CHOICES: case HttpStatus.SC_MOVED_PERMANENTLY: case HttpStatus.SC_GONE: // these response codes MAY be cached cacheable = true; log.debug("Response was cacheable"); break; case HttpStatus.SC_PARTIAL_CONTENT: // we don't implement Range requests and hence are not // allowed to cache partial content log.debug("Response was not cacheable (Partial Content)"); return cacheable; default: // If the status code is not one of the recognized // available codes in HttpStatus Don't Cache log.debug("Response was not cacheable (Unknown Status code)"); return cacheable; } Header contentLength = response.getFirstHeader(HTTP.CONTENT_LEN); if (contentLength != null) { int contentLengthValue = Integer.parseInt(contentLength.getValue()); if (contentLengthValue > this.maxObjectSizeBytes) return false; } Header[] ageHeaders = response.getHeaders(HeaderConstants.AGE); if (ageHeaders.length > 1) return false; Header[] expiresHeaders = response.getHeaders(HeaderConstants.EXPIRES); if (expiresHeaders.length > 1) return false; Header[] dateHeaders = response.getHeaders(HTTP.DATE_HEADER); if (dateHeaders.length != 1) return false; try { DateUtils.parseDate(dateHeaders[0].getValue()); } catch (DateParseException dpe) { return false; } for (Header varyHdr : response.getHeaders(HeaderConstants.VARY)) { for (HeaderElement elem : varyHdr.getElements()) { if ("*".equals(elem.getName())) { return false; } } } if (isExplicitlyNonCacheable(response)) return false; return (cacheable || isExplicitlyCacheable(response)); }
Example 20
Source File: BinaryHttpResponseHandler.java From android-project-wo2b with Apache License 2.0 | 4 votes |
@Override public final void sendResponseMessage(HttpResponse response) throws IOException { StatusLine status = response.getStatusLine(); Header[] contentTypeHeaders = response.getHeaders(AsyncHttpClient.HEADER_CONTENT_TYPE); if (contentTypeHeaders.length != 1) { //malformed/ambiguous HTTP Header, ABORT! sendFailureMessage( status.getStatusCode(), response.getAllHeaders(), null, new HttpResponseException( status.getStatusCode(), "None, or more than one, Content-Type Header found!" ) ); return; } Header contentTypeHeader = contentTypeHeaders[0]; boolean foundAllowedContentType = false; for (String anAllowedContentType : getAllowedContentTypes()) { try { if (Pattern.matches(anAllowedContentType, contentTypeHeader.getValue())) { foundAllowedContentType = true; } } catch (PatternSyntaxException e) { Log.e("BinaryHttpResponseHandler", "Given pattern is not valid: " + anAllowedContentType, e); } } if (!foundAllowedContentType) { //Content-Type not in allowed list, ABORT! sendFailureMessage( status.getStatusCode(), response.getAllHeaders(), null, new HttpResponseException( status.getStatusCode(), "Content-Type not allowed!" ) ); return; } super.sendResponseMessage(response); }