Java Code Examples for org.apache.http.Header

The following are top voted examples for showing how to use org.apache.http.Header. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: Mobike   File: RangeFileAsyncHttpResponseHandler.java   View source code 6 votes vote down vote up
@Override
public void sendResponseMessage(HttpResponse response) throws IOException {
    if (!Thread.currentThread().isInterrupted()) {
        StatusLine status = response.getStatusLine();
        if (status.getStatusCode() == HttpStatus.SC_REQUESTED_RANGE_NOT_SATISFIABLE) {
            //already finished
            if (!Thread.currentThread().isInterrupted())
                sendSuccessMessage(status.getStatusCode(), response.getAllHeaders(), null);
        } else if (status.getStatusCode() >= 300) {
            if (!Thread.currentThread().isInterrupted())
                sendFailureMessage(status.getStatusCode(), response.getAllHeaders(), null, new HttpResponseException(status.getStatusCode(), status.getReasonPhrase()));
        } else {
            if (!Thread.currentThread().isInterrupted()) {
                Header header = response.getFirstHeader(AsyncHttpClient.HEADER_CONTENT_RANGE);
                if (header == null) {
                    append = false;
                    current = 0;
                } else {
                    Log.v(LOG_TAG, AsyncHttpClient.HEADER_CONTENT_RANGE + ": " + header.getValue());
                }
                sendSuccessMessage(status.getStatusCode(), response.getAllHeaders(), getResponseData(response.getEntity()));
            }
        }
    }
}
 
Example 2
Project: Tenable.io-SDK-for-Java   File: HttpFuture.java   View source code 6 votes vote down vote up
private LogInstance logResponse( LogInstance logInstance, HttpResponse response, String respBody ) {
    if( response != null ) {
        logInstance.setRespHttpStatus( response.getStatusLine().getStatusCode() );

        // log request headers and body?
        for( Header header : response.getAllHeaders() ) {
            if( logLevel == LogLevel.TRACE || header.getName().toLowerCase().equals( "x-gateway-site-id" ) || header.getName().toLowerCase().equals( "x-request-uuid" ) ) {
                logInstance.addRespHeader( header.getName(), header.getValue() );
            }
        }

        if( logLevel == LogLevel.TRACE ) {
            if( respBody != null ) {
                String logRespBody;
                if( respBody.length() > REQUEST_AND_RESPONSE_BODY_LOG_MAX_LENGTH ) {
                    logRespBody = respBody.substring( 0, REQUEST_AND_RESPONSE_BODY_LOG_MAX_LENGTH ) + "...response body truncated...";
                }
                else logRespBody = respBody;

                logInstance.setRespBody( logRespBody );
            }
       }
    }
    return logInstance;
}
 
Example 3
Project: illuminati   File: IlluminatiHttpClient.java   View source code 6 votes vote down vote up
private void initPoolingHttpClientManager () {
    final Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
            .register("https", SSLConnectionSocketFactory.getSocketFactory())
            .register("http", PlainConnectionSocketFactory.getSocketFactory()).build();

    final PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
    connectionManager.setMaxTotal(MAX_CONNECTION);
    connectionManager.setDefaultMaxPerRoute(MAX_CONNECTION_PER_ROUTE);

    final RequestConfig.Builder requestConfigBuilder = RequestConfig.custom().setConnectTimeout(CONNECTION_TIMEOUT)
            .setConnectionRequestTimeout(CONNECTION_TIMEOUT).setSocketTimeout(SOCKET_TIMEOUT);

    final RequestConfig requestConfig = requestConfigBuilder.build();

    HashSet<Header> defaultHeaders = new HashSet<Header>();
    defaultHeaders.add(new BasicHeader(HttpHeaders.PRAGMA, "no-cache"));
    defaultHeaders.add(new BasicHeader(HttpHeaders.CACHE_CONTROL, "no-cache"));

    final HttpClientBuilder httpClientBuilder = HttpClients.custom().setDefaultHeaders(defaultHeaders).disableAuthCaching().disableContentCompression();
    this.httpClient = httpClientBuilder.setConnectionManager(connectionManager).setDefaultRequestConfig(requestConfig).build();
}
 
Example 4
Project: Tenable.io-SDK-for-Java   File: DockerImageHelper.java   View source code 6 votes vote down vote up
private void uploadTarZip( String token, String headerLocationUrl, String digestTgz, String filePath ) throws TenableIoException {
    Header[] headersArray = new Header[2];
    headersArray[0] = getTokenHeader( token );
    headersArray[1] = new BasicHeader( "Content-Type", "application/vnd.docker.image.rootfs.diff.tar.gzip" );

    try {
        byte[] fileBinary = Files.readAllBytes( Paths.get( filePath ) );
        URIBuilder uploadUrl = new URIBuilder( headerLocationUrl );
        uploadUrl.addParameter( "digest", digestTgz );

        AsyncHttpService asyncHttpService = new AsyncHttpService( null );
        HttpFuture httpFuture = asyncHttpService.doPut( uploadUrl.build(), ContentType.DEFAULT_BINARY, fileBinary, headersArray );
        httpFuture.get();
    } catch ( Exception e ) {
        throw new TenableIoException( TenableIoErrorCode.Generic, "Error while uploading tar zip.", e );
    }
}
 
Example 5
Project: ibm-cos-sdk-java   File: AmazonHttpClient.java   View source code 6 votes vote down vote up
/**
 * Creates and initializes an HttpResponse object suitable to be passed to an HTTP response
 * handler object.
 *
 * @param method  The HTTP method that was invoked to get the response.
 * @param context The HTTP context associated with the request and response.
 * @return The new, initialized HttpResponse object ready to be passed to an HTTP response
 * handler object.
 * @throws IOException If there were any problems getting any response information from the
 *                     HttpClient method object.
 */
private HttpResponse createResponse(HttpRequestBase method,
                                    org.apache.http.HttpResponse apacheHttpResponse,
                                    HttpContext context) throws IOException {
    HttpResponse httpResponse = new HttpResponse(request, method, context);

    if (apacheHttpResponse.getEntity() != null) {
        httpResponse.setContent(apacheHttpResponse.getEntity().getContent());
    }

    httpResponse.setStatusCode(apacheHttpResponse.getStatusLine().getStatusCode());
    httpResponse.setStatusText(apacheHttpResponse.getStatusLine().getReasonPhrase());
    for (Header header : apacheHttpResponse.getAllHeaders()) {
        httpResponse.addHeader(header.getName(), header.getValue());
    }

    return httpResponse;
}
 
Example 6
Project: rongyunDemo   File: BinaryHttpResponseHandler.java   View source code 6 votes vote down vote up
@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) {
        }
    }
    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 7
Project: lams   File: BasicScheme.java   View source code 6 votes vote down vote up
/**
 * Produces basic authorization header for the given set of {@link Credentials}.
 *
 * @param credentials The set of credentials to be used for authentication
 * @param request The request being authenticated
 * @throws InvalidCredentialsException if authentication credentials are not
 *   valid or not applicable for this authentication scheme
 * @throws AuthenticationException if authorization string cannot
 *   be generated due to an authentication failure
 *
 * @return a basic authorization string
 */
@Override
public Header authenticate(
        final Credentials credentials,
        final HttpRequest request,
        final HttpContext context) throws AuthenticationException {

    if (credentials == null) {
        throw new IllegalArgumentException("Credentials may not be null");
    }
    if (request == null) {
        throw new IllegalArgumentException("HTTP request may not be null");
    }

    String charset = AuthParams.getCredentialCharset(request.getParams());
    return authenticate(credentials, charset, isProxy());
}
 
Example 8
Project: letv   File: HttpTask.java   View source code 6 votes vote down vote up
protected void sendResponseMessage(HttpResponse response) {
    super.sendResponseMessage(response);
    Header[] headers = response.getHeaders("Set-Cookie");
    if (headers != null && headers.length > 0) {
        CookieSyncManager.createInstance(LemallPlatform.getInstance().getContext()).sync();
        CookieManager instance = CookieManager.getInstance();
        instance.setAcceptCookie(true);
        instance.removeSessionCookie();
        String mm = "";
        for (Header header : headers) {
            String[] split = header.toString().split("Set-Cookie:");
            EALogger.i("游客登录", "split[1]===>" + split[1]);
            instance.setCookie(Constants.GUESTLOGIN, split[1]);
            int index = split[1].indexOf(";");
            if (TextUtils.isEmpty(mm)) {
                mm = split[1].substring(index + 1);
                EALogger.i("正式登录", "mm===>" + mm);
            }
        }
        EALogger.i("游客登录", "split[11]===>COOKIE_DEVICE_ID=" + LemallPlatform.getInstance().uuid + ";" + mm);
        instance.setCookie(Constants.GUESTLOGIN, "COOKIE_DEVICE_ID=" + LemallPlatform.getInstance().uuid + ";" + mm);
        instance.setCookie(Constants.THIRDLOGIN, "COOKIE_APP_ID=" + LemallPlatform.getInstance().getmAppInfo().getId() + ";" + mm);
        CookieSyncManager.getInstance().sync();
        this.val$iLetvBrideg.reLoadWebUrl();
    }
}
 
Example 9
Project: matrix-java-sdk   File: MatrixHttpContentResult.java   View source code 6 votes vote down vote up
public MatrixHttpContentResult(CloseableHttpResponse response) throws IOException {
    HttpEntity entity = response.getEntity();
    valid = entity != null && response.getStatusLine().getStatusCode() == 200;

    if (entity != null) {
        headers = Arrays.asList(response.getAllHeaders());
        Header contentTypeHeader = entity.getContentType();
        if (contentTypeHeader != null) {
            contentType = Optional.of(contentTypeHeader.getValue());
        } else {
            contentType = Optional.empty();
        }
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        entity.writeTo(outStream);
        data = outStream.toByteArray();
    } else {
        headers = new ArrayList<>();
        contentType = Optional.empty();
        data = new byte[0];
    }
}
 
Example 10
Project: degiro-java-client   File: DeGiroImpl.java   View source code 5 votes vote down vote up
@Override
public DProductDescriptions getProducts(List<Long> productIds) throws DeGiroException {

    DProductDescriptions products = null;

    ensureLogged();
    try {
        List<Header> headers = new ArrayList<>(1);
        ArrayList<String> productIdStr = new ArrayList<>(productIds.size());
        for (Long productId : productIds) {
            productIdStr.add(productId + "");
        }
        DResponse response = comm.getUrlData(session.getConfig().getProductSearchUrl(), "v5/products/info?intAccount=" + session.getClient().getIntAccount() + "&sessionId=" + session.getJSessionId(), productIdStr, headers);
        products = gson.fromJson(getResponseData(response), DProductDescriptions.class);

    } catch (IOException e) {
        throw new DeGiroException("IOException while retrieving product information", e);
    }

    return products;
}
 
Example 11
Project: sealtalk-android-master   File: AsyncHttpResponseHandler.java   View source code 5 votes vote down vote up
/**
 * Fired when a request fails to complete, override to handle in your own code
 *
 * @param statusCode   return HTTP status code
 * @param headers      return headers, if any
 * @param responseBody the response body, if any
 * @param error        the underlying cause of the failure
 */
public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
    try {
        String response = responseBody == null ? null : new String(responseBody, getCharset());
        onFailure(statusCode, headers, error, response);
    } catch (UnsupportedEncodingException e) {
        onFailure(statusCode, headers, e, null);
    }
}
 
Example 12
Project: jkes   File: EsRestClient.java   View source code 5 votes vote down vote up
@Inject
public EsRestClient(JkesProperties jkesProperties) {
    SniffOnFailureListener sniffOnFailureListener = new SniffOnFailureListener();
    Header[] defaultHeaders = {new BasicHeader("Content-Type", "application/json")};

    String[] urls = jkesProperties.getEsBootstrapServers().split("\\s*,");
    HttpHost[] hosts = new HttpHost[urls.length];
    for (int i = 0; i < urls.length; i++) {
        hosts[i] = HttpHost.create(urls[i]);
    }

    RestClient restClient = RestClient.builder(hosts)
            .setRequestConfigCallback(requestConfigBuilder -> {
                return requestConfigBuilder.setConnectTimeout(5000) // default 1s
                        .setSocketTimeout(60000); // defaults to 30 seconds
            }).setHttpClientConfigCallback(httpClientBuilder -> {
                return httpClientBuilder.setDefaultIOReactorConfig(
                        IOReactorConfig.custom().setIoThreadCount(2).build()); // because only used for admin, so not necessary to hold many worker threads
            })
            .setMaxRetryTimeoutMillis(60000) // defaults to 30 seconds
            .setDefaultHeaders(defaultHeaders)
            .setFailureListener(sniffOnFailureListener)
            .build();

    Sniffer sniffer = Sniffer.builder(restClient).build();
    sniffOnFailureListener.setSniffer(sniffer);

    this.sniffer = sniffer;
    this.restClient = restClient;
}
 
Example 13
Project: Photato   File: VideoHandler.java   View source code 5 votes vote down vote up
@Override
protected Header[] getHeaders() {
    int maxAge = 30 * 86400;

    return new Header[]{
        new BasicHeader("Cache-Control", "max-age=" + maxAge + ", public"),
        new BasicHeader("Expires", expiresDateFormat.format(new Date(System.currentTimeMillis() + maxAge * 1000L)))
    };
}
 
Example 14
Project: boohee_v5.6   File: BaseJsonHttpResponseHandler.java   View source code 5 votes vote down vote up
public final void onSuccess(final int statusCode, final Header[] headers, final String
        responseString) {
    if (statusCode != 204) {
        Runnable parser = new Runnable() {
            public void run() {
                try {
                    final JSON_TYPE jsonResponse = BaseJsonHttpResponseHandler.this
                            .parseResponse(responseString, false);
                    BaseJsonHttpResponseHandler.this.postRunnable(new Runnable() {
                        public void run() {
                            BaseJsonHttpResponseHandler.this.onSuccess(statusCode, headers,
                                    responseString, jsonResponse);
                        }
                    });
                } catch (final Throwable t) {
                    Log.d(BaseJsonHttpResponseHandler.LOG_TAG, "parseResponse thrown an " +
                            "problem", t);
                    BaseJsonHttpResponseHandler.this.postRunnable(new Runnable() {
                        public void run() {
                            BaseJsonHttpResponseHandler.this.onFailure(statusCode, headers,
                                    t, responseString, null);
                        }
                    });
                }
            }
        };
        if (getUseSynchronousMode() || getUsePoolThread()) {
            parser.run();
            return;
        } else {
            new Thread(parser).start();
            return;
        }
    }
    onSuccess(statusCode, headers, null, null);
}
 
Example 15
Project: degiro-java-client   File: DeGiroImpl.java   View source code 5 votes vote down vote up
private void getVwdSession() throws DeGiroException {

        try {
            List<Header> headers = new ArrayList<>(1);
            headers.add(new BasicHeader("Origin", session.getConfig().getTradingUrl()));
            HashMap<String, String> data = new HashMap();
            data.put("referrer", "https://trader.degiro.nl");
            DResponse response = comm.getUrlData("https://degiro.quotecast.vwdservices.com/CORS", "/request_session?version=1.0.20170315&userToken=" + session.getClient().getId(), data, headers);
            HashMap map = gson.fromJson(getResponseData(response), HashMap.class);
            session.setVwdSession((String) map.get("sessionId"));
            session.setLastVwdSessionUsed(System.currentTimeMillis());
        } catch (IOException e) {
            throw new DeGiroException("IOException while retrieving vwd session", e);
        }
    }
 
Example 16
Project: GitHub   File: BasicNetwork.java   View source code 5 votes vote down vote up
/**
 * Converts Headers[] to Map<String, String>.
 */
protected static Map<String, String> convertHeaders(Header[] headers) {
    Map<String, String> result = new TreeMap<String, String>(String.CASE_INSENSITIVE_ORDER);
    for (int i = 0; i < headers.length; i++) {
        result.put(headers[i].getName(), headers[i].getValue());
    }
    return result;
}
 
Example 17
Project: GitHub   File: OkApacheClientTest.java   View source code 5 votes vote down vote up
@Test public void contentType() throws Exception {
  server.enqueue(new MockResponse().setBody("<html><body><h1>Hello, World!</h1></body></html>")
      .setHeader("Content-Type", "text/html"));
  server.enqueue(new MockResponse().setBody("{\"Message\": { \"text\": \"Hello, World!\" } }")
      .setHeader("Content-Type", "application/json"));
  server.enqueue(new MockResponse().setBody("Hello, World!"));

  HttpGet request1 = new HttpGet(server.url("/").url().toURI());
  HttpResponse response1 = client.execute(request1);
  Header[] headers1 = response1.getHeaders("Content-Type");
  assertEquals(1, headers1.length);
  assertEquals("text/html", headers1[0].getValue());
  assertNotNull(response1.getEntity().getContentType());
  assertEquals("text/html", response1.getEntity().getContentType().getValue());

  HttpGet request2 = new HttpGet(server.url("/").url().toURI());
  HttpResponse response2 = client.execute(request2);
  Header[] headers2 = response2.getHeaders("Content-Type");
  assertEquals(1, headers2.length);
  assertEquals("application/json", headers2[0].getValue());
  assertNotNull(response2.getEntity().getContentType());
  assertEquals("application/json", response2.getEntity().getContentType().getValue());

  HttpGet request3 = new HttpGet(server.url("/").url().toURI());
  HttpResponse response3 = client.execute(request3);
  Header[] headers3 = response3.getHeaders("Content-Type");
  assertEquals(0, headers3.length);
  assertNull(response3.getEntity().getContentType());
}
 
Example 18
Project: lams   File: HeaderGroup.java   View source code 5 votes vote down vote up
/**
 * Tests if headers with the given name are contained within this group.
 *
 * <p>Header name comparison is case insensitive.
 *
 * @param name the header name to test for
 * @return <code>true</code> if at least one header with the name is
 * contained, <code>false</code> otherwise
 */
public boolean containsHeader(String name) {
    for (int i = 0; i < headers.size(); i++) {
        Header header = headers.get(i);
        if (header.getName().equalsIgnoreCase(name)) {
            return true;
        }
    }

    return false;
}
 
Example 19
Project: rs-aggregator   File: AbstractUriReader.java   View source code 5 votes vote down vote up
public <R> Result<R> execute(URI uri, LambdaUtil.BiFunction_WithExceptions<URI, HttpResponse, R, ?> func) {
  logger.debug("Executing GET on uri {}", uri);
  currentUri = uri;
  Result<R> result = new Result<R>(uri);
  HttpGet request = new HttpGet(uri);
  CloseableHttpResponse response = null;
  try  {
    response = httpClient.execute(request);
    int statusCode = response.getStatusLine().getStatusCode();
    result.setStatusLine(response.getStatusLine().toString());
    logger.debug("Received {} from {}", response.getStatusLine(), uri);
    result.setStatusCode(statusCode);
    if (keepingHeaders) {
      for (Header header : response.getAllHeaders()) {
        result.getHeaders().put(header.getName(), header.getValue());
      }
    }
    if (statusCode < 200 || statusCode > 299) {
      result.addError(new RemoteException(statusCode, response.getStatusLine().getReasonPhrase(), uri));
    } else {
      result.accept(func.apply(uri, response));
    }
  } catch (Exception e) {
    logger.error("Error executing GET on uri {}", uri, e);
    result.addError(e);
  } finally {
    closeResponse(response);
  }
  return result;
}
 
Example 20
Project: elasticsearch_my   File: RequestLogger.java   View source code 5 votes vote down vote up
static String buildWarningMessage(HttpUriRequest request, HttpHost host, Header[] warnings) {
    StringBuilder message = new StringBuilder("request [").append(request.getMethod()).append(" ").append(host)
            .append(getUri(request.getRequestLine())).append("] returned ").append(warnings.length).append(" warnings: ");
    for (int i = 0; i < warnings.length; i++) {
        if (i > 0) {
            message.append(",");
        }
        message.append("[").append(warnings[i].getValue()).append("]");
    }
    return message.toString();
}
 
Example 21
Project: nest-spider   File: HttpClientUtil.java   View source code 5 votes vote down vote up
public String getHeaders(String url, String cookie, String headerName) {
	HttpGet get = new HttpGet(url);
	if(StringUtils.isNotBlank(cookie))
    	get.addHeader("cookie", cookie);
	res(get);
	Header[] headers = get.getHeaders(headerName);
	return headers == null ? null : headers.toString();
}
 
Example 22
Project: personium-core   File: AbstractCase.java   View source code 5 votes vote down vote up
/**
 * DomainのJson形式のリストのフォーマットチェック.
 * @param response DcResponseオブジェクト
 * @param contentType レスポンスのContentType
 */
public final void checkDomainListResponse(PersoniumResponse response, MediaType contentType) {

    // Cell取得のレスポンスチェック
    // 200になることを確認
    assertEquals(HttpStatus.SC_OK, response.getStatusCode());

    // DataServiceVersionのチェック
    Header[] resDsvHeaders = response.getResponseHeaders(ODataConstants.Headers.DATA_SERVICE_VERSION);
    assertEquals(1, resDsvHeaders.length);
    assertEquals("2.0", resDsvHeaders[0].getValue());

    // ContentTypeのチェック
    Header[] resContentTypeHeaders = response.getResponseHeaders(HttpHeaders.CONTENT_TYPE);
    assertEquals(1, resContentTypeHeaders.length);
    String value = resContentTypeHeaders[0].getValue();
    String[] values = value.split(";");
    assertEquals(contentType.toString(), values[0]);

    if (contentType == MediaType.APPLICATION_JSON_TYPE) {
        // レスポンスボディのJsonもチェックが必要
        checkDomainListResponse(response.bodyAsJson());

    } else if (contentType == MediaType.APPLICATION_ATOM_XML_TYPE) {
        // レスポンスボディのチェック
        fail("Not Implemented.");
        // checkCellXML(response.bodyAsXml());
    }
}
 
Example 23
Project: plugin-bt-jira   File: JiraSudoHttpResponseCallbackTest.java   View source code 5 votes vote down vote up
@Test
public void acceptResponse302WithHeader() {
	final CloseableHttpResponse response = Mockito.mock(CloseableHttpResponse.class);
	final StatusLine statusLine = Mockito.mock(StatusLine.class);
	Mockito.when(response.getStatusLine()).thenReturn(statusLine);
	Mockito.when(statusLine.getStatusCode()).thenReturn(302);
	final Header header = Mockito.mock(Header.class);
	Mockito.when(header.getValue()).thenReturn("any");
	Mockito.when(response.getFirstHeader("X-Atlassian-WebSudo")).thenReturn(header);
	Assert.assertFalse(jiraSudoHttpResponseCallback.acceptResponse(response));
}
 
Example 24
Project: PlusGram   File: BasicNetwork.java   View source code 5 votes vote down vote up
/**
 * Converts Headers[] to Map<String, String>.
 */
protected static Map<String, String> convertHeaders(Header[] headers) {
    Map<String, String> result = new TreeMap<String, String>(String.CASE_INSENSITIVE_ORDER);
    for (int i = 0; i < headers.length; i++) {
        result.put(headers[i].getName(), headers[i].getValue());
    }
    return result;
}
 
Example 25
Project: personium-core   File: PersoniumResponse.java   View source code 5 votes vote down vote up
/**
 * レスポンスボディのストリームを受け取る.
 * @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 26
Project: BUbiNG   File: RandomTestMocks.java   View source code 5 votes vote down vote up
public HttpResponse(final int maxNumberOfHeaders, final int maxLenghtOfHeader, final int maxLengthOfBody, final int pos) {
	this.statusLine = new BasicStatusLine(PROTOCOL_VERSION, 200, "OK");
	Header[] headers = randomHeaders(maxNumberOfHeaders, maxLenghtOfHeader);
	headers[RNG.nextInt(headers.length)] = new BasicHeader("Position", Integer.toString(pos));
	this.setHeaders(headers);
	this.content = RandomStringUtils.randomAscii(RNG.nextInt(maxLengthOfBody) + 1);
	byte[] body = Util.toByteArray(content);
	this.addHeader("Content-Length", Integer.toString(body.length));
	this.entity = new ByteArrayEntity(body, ContentType.DEFAULT_BINARY);
}
 
Example 27
Project: openssp   File: DemandBroker.java   View source code 5 votes vote down vote up
public DemandBroker(final Supplier supplier, final OpenRtbConnector connector, final SessionAgent agent) {
	sessionAgent = agent;
	this.supplier = supplier;
	this.connector = connector;

	headers = new Header[2];
	headers[0] = new BasicHeader("x-openrtb-version", supplier.getOpenRtbVersion());
	headers[1] = new BasicHeader("ContentType", supplier.getContentType());
	// headers[2] = new BasicHeader("Accept-Encoding", supplier.getAcceptEncoding());
	// headers[3] = new BasicHeader("Content-Encoding", supplier.getContentEncoding());

	gson = new GsonBuilder().setVersion(Double.valueOf(supplier.getOpenRtbVersion())).create();
}
 
Example 28
Project: lams   File: RequestAuthenticationBase.java   View source code 5 votes vote down vote up
@SuppressWarnings("deprecation")
private Header authenticate(
        final AuthScheme authScheme,
        final Credentials creds,
        final HttpRequest request,
        final HttpContext context) throws AuthenticationException {
    if (authScheme == null) {
        throw new IllegalStateException("Auth state object is null");
    }
    if (authScheme instanceof ContextAwareAuthScheme) {
        return ((ContextAwareAuthScheme) authScheme).authenticate(creds, request, context);
    } else {
        return authScheme.authenticate(creds, request);
    }
}
 
Example 29
Project: airsonic   File: PodcastService.java   View source code 5 votes vote down vote up
private String getCoverArtSuffix(HttpResponse response) {
    String result = null;
    Header contentTypeHeader = response.getEntity().getContentType();
    if (contentTypeHeader != null && contentTypeHeader.getValue() != null) {
        ContentType contentType = ContentType.parse(contentTypeHeader.getValue());
        String mimeType = contentType.getMimeType();
        result = StringUtil.getSuffix(mimeType);
    }
    return result == null ? "jpeg" : result;
}
 
Example 30
Project: http-agent   File: AgentServlet.java   View source code 5 votes vote down vote up
/** Copy proxied response headers back to the servlet client. */
protected void copyResponseHeaders(HttpResponse proxyResponse, HttpServletRequest servletRequest, HttpServletResponse servletResponse) {
    for (Header header : proxyResponse.getAllHeaders()) {
        if (hopByHopHeaders.containsHeader(header.getName()))
            continue;
        if (header.getName().equalsIgnoreCase(org.apache.http.cookie.SM.SET_COOKIE)
                || header.getName().equalsIgnoreCase(org.apache.http.cookie.SM.SET_COOKIE2)) {
            copyProxyCookie(servletRequest, servletResponse, header);
        } else {
            servletResponse.addHeader(header.getName(), header.getValue());
        }
    }
}
 
Example 31
Project: elasticsearch_my   File: RestHighLevelClientTests.java   View source code 5 votes vote down vote up
public void testPingSuccessful() throws IOException {
    Header[] headers = RestClientTestUtil.randomHeaders(random(), "Header");
    Response response = mock(Response.class);
    when(response.getStatusLine()).thenReturn(newStatusLine(RestStatus.OK));
    when(restClient.performRequest(anyString(), anyString(), anyMapOf(String.class, String.class),
            anyObject(), anyVararg())).thenReturn(response);
    assertTrue(restHighLevelClient.ping(headers));
    verify(restClient).performRequest(eq("HEAD"), eq("/"), eq(Collections.emptyMap()),
            Matchers.isNull(HttpEntity.class), argThat(new HeadersVarargMatcher(headers)));
}
 
Example 32
Project: smockin   File: HttpClientServiceTest.java   View source code 5 votes vote down vote up
@Test
public void extractResponseHeadersTest() {

    // Setup
    Mockito.when(httpResponse.getAllHeaders()).thenReturn(new Header[] { new BasicHeader("one", "1"), new BasicHeader("two", "2") });

    // Test
    final Map<String, String> result = httpClientServiceImpl.extractResponseHeaders(httpResponse);

    // Assertions
    Assert.assertNotNull(result);
    Assert.assertEquals(2, result.size());
    Assert.assertTrue(result.containsKey("one"));
    Assert.assertTrue(result.containsKey("two"));
}
 
Example 33
Project: elasticsearch_my   File: RequestLoggerTests.java   View source code 5 votes vote down vote up
public void testResponseWarnings() throws Exception {
    HttpHost host = new HttpHost("localhost", 9200);
    HttpUriRequest request = randomHttpRequest(new URI("/index/type/_api"));
    int numWarnings = randomIntBetween(1, 5);
    StringBuilder expected = new StringBuilder("request [").append(request.getMethod()).append(" ").append(host)
            .append("/index/type/_api] returned ").append(numWarnings).append(" warnings: ");
    Header[] warnings = new Header[numWarnings];
    for (int i = 0; i < numWarnings; i++) {
        String warning = "this is warning number " + i;
        warnings[i] = new BasicHeader("Warning", warning);
        if (i > 0) {
            expected.append(",");
        }
        expected.append("[").append(warning).append("]");
    }
    assertEquals(expected.toString(), RequestLogger.buildWarningMessage(request, host, warnings));
}
 
Example 34
Project: lams   File: BasicListHeaderIterator.java   View source code 5 votes vote down vote up
/**
 * Obtains the next header from this iteration.
 *
 * @return  the next header in this iteration
 *
 * @throws NoSuchElementException   if there are no more headers
 */
public Header nextHeader()
    throws NoSuchElementException {

    final int current = this.currentIndex;
    if (current < 0) {
        throw new NoSuchElementException("Iteration already finished.");
    }

    this.lastIndex    = current;
    this.currentIndex = findNext(current);

    return this.allHeaders.get(current);
}
 
Example 35
Project: letv   File: AsyncHttpClient.java   View source code 5 votes vote down vote up
public void post(Context context, String url, Header[] headers, HttpEntity entity, String contentType, AsyncHttpResponseHandler responseHandler) {
    HttpEntityEnclosingRequestBase request = addEntityToRequestBase(new HttpPost(url), entity);
    if (headers != null) {
        request.setHeaders(headers);
    }
    sendRequest(this.httpClient, this.httpContext, request, contentType, responseHandler, context);
}
 
Example 36
Project: Mobike   File: BaseJsonHttpResponseHandler.java   View source code 5 votes vote down vote up
@Override
public final void onFailure(final int statusCode, final Header[] headers, final String responseString, final Throwable throwable) {
    if (responseString != null) {
        Runnable parser = new Runnable() {
            @Override
            public void run() {
                try {
                    final JSON_TYPE jsonResponse = parseResponse(responseString, true);
                    postRunnable(new Runnable() {
                        @Override
                        public void run() {
                            onFailure(statusCode, headers, throwable, responseString, jsonResponse);
                        }
                    });
                } catch (Throwable t) {
                    Log.d(LOG_TAG, "parseResponse thrown an problem", t);
                    postRunnable(new Runnable() {
                        @Override
                        public void run() {
                            onFailure(statusCode, headers, throwable, responseString, null);
                        }
                    });
                }
            }
        };
        if (!getUseSynchronousMode()) {
            new Thread(parser).start();
        } else {
            // In synchronous mode everything should be run on one thread
            parser.run();
        }
    } else {
        onFailure(statusCode, headers, throwable, null, null);
    }
}
 
Example 37
Project: BUbiNG   File: AbstractWarcRecord.java   View source code 5 votes vote down vote up
protected static void writeHeaders(final HeaderGroup headers, final OutputStream output) throws IOException {
	for (final HeaderIterator it = headers.iterator(); it.hasNext();) {
		final org.apache.http.Header header = it.nextHeader();
		Util.toOutputStream(BasicLineFormatter.formatHeader(header, null), output);
		output.write(ByteArraySessionOutputBuffer.CRLF);
	}
}
 
Example 38
Project: java-bitbankcc   File: Bitbankcc.java   View source code 5 votes vote down vote up
private List<Header> makePrivateRequestHeader(long nonce, String sign) throws BitbankException {
    List<Header> headers = new ArrayList<Header>();
    headers.add(new BasicHeader("content-type","application/json; charset=utf-8"));
    headers.add(new BasicHeader("ACCESS-KEY", this.apiKey));
    headers.add(new BasicHeader("ACCESS-NONCE", String.valueOf(nonce)));
    headers.add(new BasicHeader("ACCESS-SIGNATURE", sign));
    return headers;
}
 
Example 39
Project: iosched-reader   File: HurlStack.java   View source code 5 votes vote down vote up
@Override
public HttpResponse performRequest(Request<?> request, Map<String, String> additionalHeaders)
        throws IOException, AuthFailureError {
    String url = request.getUrl();
    HashMap<String, String> map = new HashMap<String, String>();
    map.putAll(request.getHeaders());
    map.putAll(additionalHeaders);
    if (mUrlRewriter != null) {
        String rewritten = mUrlRewriter.rewriteUrl(url);
        if (rewritten == null) {
            throw new IOException("URL blocked by rewriter: " + url);
        }
        url = rewritten;
    }
    URL parsedUrl = new URL(url);
    HttpURLConnection connection = openConnection(parsedUrl, request);
    for (String headerName : map.keySet()) {
        connection.addRequestProperty(headerName, map.get(headerName));
    }
    setConnectionParametersForRequest(connection, request);
    // Initialize HttpResponse with data from the HttpURLConnection.
    ProtocolVersion protocolVersion = new ProtocolVersion("HTTP", 1, 1);
    int responseCode = connection.getResponseCode();
    if (responseCode == -1) {
        // -1 is returned by getResponseCode() if the response code could not be retrieved.
        // Signal to the caller that something was wrong with the connection.
        throw new IOException("Could not retrieve response code from HttpUrlConnection.");
    }
    StatusLine responseStatus = new BasicStatusLine(protocolVersion,
            connection.getResponseCode(), connection.getResponseMessage());
    BasicHttpResponse response = new BasicHttpResponse(responseStatus);
    response.setEntity(entityFromConnection(connection));
    for (Entry<String, List<String>> header : connection.getHeaderFields().entrySet()) {
        if (header.getKey() != null) {
            Header h = new BasicHeader(header.getKey(), header.getValue().get(0));
            response.addHeader(h);
        }
    }
    return response;
}
 
Example 40
Project: elasticsearch_my   File: ESRestTestCase.java   View source code 5 votes vote down vote up
protected RestClient buildClient(Settings settings, HttpHost[] hosts) throws IOException {
    RestClientBuilder builder = RestClient.builder(hosts);
    String keystorePath = settings.get(TRUSTSTORE_PATH);
    if (keystorePath != null) {
        final String keystorePass = settings.get(TRUSTSTORE_PASSWORD);
        if (keystorePass == null) {
            throw new IllegalStateException(TRUSTSTORE_PATH + " is provided but not " + TRUSTSTORE_PASSWORD);
        }
        Path path = PathUtils.get(keystorePath);
        if (!Files.exists(path)) {
            throw new IllegalStateException(TRUSTSTORE_PATH + " is set but points to a non-existing file");
        }
        try {
            KeyStore keyStore = KeyStore.getInstance("jks");
            try (InputStream is = Files.newInputStream(path)) {
                keyStore.load(is, keystorePass.toCharArray());
            }
            SSLContext sslcontext = SSLContexts.custom().loadTrustMaterial(keyStore, null).build();
            SSLIOSessionStrategy sessionStrategy = new SSLIOSessionStrategy(sslcontext);
            builder.setHttpClientConfigCallback(httpClientBuilder -> httpClientBuilder.setSSLStrategy(sessionStrategy));
        } catch (KeyStoreException|NoSuchAlgorithmException|KeyManagementException|CertificateException e) {
            throw new RuntimeException("Error setting up ssl", e);
        }
    }

    try (ThreadContext threadContext = new ThreadContext(settings)) {
        Header[] defaultHeaders = new Header[threadContext.getHeaders().size()];
        int i = 0;
        for (Map.Entry<String, String> entry : threadContext.getHeaders().entrySet()) {
            defaultHeaders[i++] = new BasicHeader(entry.getKey(), entry.getValue());
        }
        builder.setDefaultHeaders(defaultHeaders);
    }
    return builder.build();
}