org.apache.http.Header Java Examples

The following examples show how to use org.apache.http.Header. 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: NodeFragment.java    From v2ex-daily-android with Apache License 2.0 6 votes vote down vote up
private void syncCollection(final int nodeId, final boolean added, String regTime){
    V2EX.syncCollection(getActivity(), nodeId, regTime, added, new JsonHttpResponseHandler(){
        @Override
        public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
            if(getActivity() != null){
                try {
                    if(response.getString("result").equals("ok")){
                        mProgressDialog.setMessage("OK");
                        mAllNodesDataHelper.setCollected(added, nodeId);
                    }else if(response.getString("result").equals("fail")){
                        mProgressDialog.setMessage("Fail");
                        MessageUtils.toast(getActivity(), "Sync collections failed.");
                    }
                    mProgressDialog.dismiss();
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }
    });
}
 
Example #2
Source File: FHIRToolingClient.java    From org.hl7.fhir.core with Apache License 2.0 6 votes vote down vote up
public ConceptMap updateClosure(String name, Coding coding) {
  Parameters params = new Parameters();
  params.addParameter().setName("name").setValue(new StringType(name));
  params.addParameter().setName("concept").setValue(coding);
  List<Header> headers = null;
  ResourceRequest<Resource> result = utils.issuePostRequest(resourceAddress.resolveOperationUri(null, "closure", new HashMap<String, String>()),
      utils.getResourceAsByteArray(params, false, isJson(getPreferredResourceFormat())), getPreferredResourceFormat(), headers);
  result.addErrorStatus(410);//gone
  result.addErrorStatus(404);//unknown
  result.addErrorStatus(405);
  result.addErrorStatus(422);//Unprocessable Entity
  result.addSuccessStatus(200);
  result.addSuccessStatus(201);
  if(result.isUnsuccessfulRequest()) {
    throw new EFhirClientException("Server returned error code " + result.getHttpStatus(), (OperationOutcome)result.getPayload());
  }
  return (ConceptMap) result.getPayload();
}
 
Example #3
Source File: FHIRToolingClient.java    From org.hl7.fhir.core with Apache License 2.0 6 votes vote down vote up
public ValueSet expandValueset(ValueSet source, Parameters expParams,Map<String, String> params) {
  List<Header> headers = null;
  
  Parameters p = expParams == null ? new Parameters() : expParams.copy();
  p.addParameter().setName("valueSet").setResource(source);
  for (String n : params.keySet())
    p.addParameter().setName(n).setValue(new StringType(params.get(n)));
  
  ResourceRequest<Resource> result = utils.issuePostRequest(resourceAddress.resolveOperationUri(ValueSet.class, "expand", params), 
      utils.getResourceAsByteArray(p, false, isJson(getPreferredResourceFormat())), getPreferredResourceFormat(), headers);
  result.addErrorStatus(410); //gone
  result.addErrorStatus(404); //unknown
  result.addErrorStatus(405);
  result.addErrorStatus(422); //Unprocessable Entity
  result.addSuccessStatus(200);
  result.addSuccessStatus(201);
  if(result.isUnsuccessfulRequest()) {
    throw new EFhirClientException("Server returned error code " + result.getHttpStatus(), (OperationOutcome)result.getPayload());
  }
  return (ValueSet) result.getPayload();
}
 
Example #4
Source File: NUHttpOptions.java    From neembuu-uploader with GNU General Public License v3.0 6 votes vote down vote up
public Set<String> getAllowedMethods(final HttpResponse response) {
    if (response == null) {
        throw new IllegalArgumentException("HTTP response may not be null");
    }

    HeaderIterator it = response.headerIterator("Allow");
    Set<String> methods = new HashSet<String>();
    while (it.hasNext()) {
        Header header = it.nextHeader();
        HeaderElement[] elements = header.getElements();
        for (HeaderElement element : elements) {
            methods.add(element.getName());
        }
    }
    return methods;
}
 
Example #5
Source File: BasicNetwork.java    From android-common-utils with Apache License 2.0 6 votes vote down vote up
/**
 * Converts Headers[] to Map<String, String>.
 */
private static Map<String, String> convertHeaders(Header[] headers) {
    Map<String, String> result = new HashMap<String, String>();
    for (int i = 0; i < headers.length; i++) {
        result.put(headers[i].getName(), headers[i].getValue());
    }
    return result;
}
 
Example #6
Source File: FedoraProvider.java    From fcrepo-camel-toolbox with Apache License 2.0 6 votes vote down vote up
private Optional<String> getNonRDFSourceDescribedByUri(final String resourceUri) throws IOException {
    Optional<String> nonRdfSourceDescUri = Optional.empty();
    final Header[] links = getLinkHeaders(resourceUri);
    if ( links != null ) {
        String descriptionUri = null;
        boolean isNonRDFSource = false;
        for ( final Header h : links ) {
            final FcrepoLink link = new FcrepoLink(h.getValue());
            if ( link.getRel().equals("describedby") ) {
                descriptionUri = link.getUri().toString();
            } else if ( link.getUri().toString().contains(NON_RDF_SOURCE_URI)) {
                isNonRDFSource = true;
            }
        }
        LOGGER.debug("isNonRDFSource: " + isNonRDFSource);
        if (isNonRDFSource && descriptionUri != null) {
            nonRdfSourceDescUri = Optional.of(descriptionUri);
        }
    }
    return nonRdfSourceDescUri;
}
 
Example #7
Source File: MockHttpServletRequestBuilder.java    From esigate with Apache License 2.0 6 votes vote down vote up
/**
 * Build the request as defined in the current builder.
 * 
 * @return the request
 */
public HttpServletRequest build() {
    HttpServletRequest request = Mockito.mock(HttpServletRequest.class);

    Mockito.when(request.getMethod()).thenReturn(this.method);
    Mockito.when(request.getProtocol()).thenReturn(this.protocolVersion);
    Mockito.when(request.getRequestURI()).thenReturn(this.uriString);

    Mockito.when(request.getHeaderNames()).thenReturn(Collections.enumeration(headers));
    for (Header h : headers) {
        List<String> hresult = new ArrayList<>();
        hresult.add(h.getValue());
        Mockito.when(request.getHeaders(h.getName())).thenReturn(Collections.enumeration(hresult));
        Mockito.when(request.getHeader(h.getName())).thenReturn(h.getValue());
    }

    if (session == null) {
        Mockito.when(request.getSession()).thenReturn(null);
    } else {
        HttpSession sessionMock = Mockito.mock(HttpSession.class);
        Mockito.when(request.getSession()).thenReturn(sessionMock);
    }
    return request;
}
 
Example #8
Source File: ClientCertRenegotiationTestCase.java    From quarkus-http with Apache License 2.0 6 votes vote down vote up
@Test
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 #9
Source File: HttpClientConfigTests.java    From vividus with Apache License 2.0 6 votes vote down vote up
@Test
void testCreateHeadersExists()
{
    String header1 = "header1";
    String header2 = "header2";
    String value1 = "value1";
    String value2 = "value2";
    Map<String, String> headersMap = new HashMap<>();
    headersMap.put(header1, value1);
    headersMap.put(header2, value2);
    config.setHeadersMap(headersMap);

    List<Header> headers = config.createHeaders();
    assertEquals(headersMap.size(), headers.size());
    assertThat(headers.get(0).getName(), anyOf(equalTo(header1), equalTo(header2)));
    assertThat(headers.get(0).getValue(), anyOf(equalTo(value1), equalTo(value2)));
    assertThat(headers.get(1).getName(), anyOf(equalTo(header1), equalTo(header2)));
    assertThat(headers.get(1).getValue(), anyOf(equalTo(value1), equalTo(value2)));
}
 
Example #10
Source File: RangeFileAsyncHttpResponseHandler.java    From android-project-wo2b with Apache License 2.0 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 #11
Source File: WarcRecord.java    From BUbiNG with Apache License 2.0 5 votes vote down vote up
/**
 * Determines the WARC record type given the <code>WARC-Type</code> header.
 *
 * @param header the header.
 * @return the record type.
 */
public static Type valueOf(final Header header) {
	if (! header.getName().equals(WarcHeader.Name.WARC_TYPE.value)) throw new IllegalArgumentException("Wrong header type " + header.getName());
	final String type = header.getValue();
	if (type.equals(RESPONSE.value))
		return RESPONSE;
	if (type.equals(REQUEST.value))
		return REQUEST;
	if (type.equals(WARCINFO.value))
		return WARCINFO;
	throw new IllegalArgumentException("Unrecognized type " + type);
}
 
Example #12
Source File: HTTPMethod.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Deprecated
public HTTPMethod setMethodHeaders(List<Header> headers) throws HTTPException {
  try {
    for (Header h : headers) {
      this.headers.put(h.getName(), h.getValue());
    }
  } catch (Exception e) {
    throw new HTTPException(e);
  }
  return this;
}
 
Example #13
Source File: HttpEndpoint.java    From Brutusin-RPC with Apache License 2.0 5 votes vote down vote up
private static String getAttachmentFileName(Header contentDiposition) {
    if (contentDiposition == null) {
        return null;
    }
    String value = contentDiposition.getValue();
    Pattern pat = Pattern.compile(".*filename[^;=\n]*=((['\"]).*?\\2|[^;\n]*)");
    Matcher matcher = pat.matcher(value);
    if (matcher.matches()) {
        return matcher.group(1);
    }
    return null;
}
 
Example #14
Source File: SiteToSiteRestApiClient.java    From nifi with Apache License 2.0 5 votes vote down vote up
private String readTransactionUrl(final HttpResponse response) {
    final Header locationUriIntentHeader = response.getFirstHeader(LOCATION_URI_INTENT_NAME);
    logger.debug("locationUriIntentHeader={}", locationUriIntentHeader);

    if (locationUriIntentHeader != null && LOCATION_URI_INTENT_VALUE.equals(locationUriIntentHeader.getValue())) {
        final Header transactionUrl = response.getFirstHeader(LOCATION_HEADER_NAME);
        logger.debug("transactionUrl={}", transactionUrl);

        if (transactionUrl != null) {
            return transactionUrl.getValue();
        }
    }

    return null;
}
 
Example #15
Source File: AsyncRequestWrapperImpl.java    From olingo-odata4 with Apache License 2.0 5 votes vote down vote up
private void retrieveMonitorDetails(final HttpResponse res) {
  Header[] headers = res.getHeaders(HttpHeader.LOCATION);
  if (ArrayUtils.isNotEmpty(headers)) {
    this.location = createLocation(headers[0].getValue());
  } else {
    throw new AsyncRequestException(
        "Invalid async request response. Monitor URL '" + headers[0].getValue() + "'");
  }

  headers = res.getHeaders(HttpHeader.RETRY_AFTER);
  if (ArrayUtils.isNotEmpty(headers)) {
    this.retryAfter = parseReplyAfter(headers[0].getValue());
  }

  headers = res.getHeaders(HttpHeader.PREFERENCE_APPLIED);
  if (ArrayUtils.isNotEmpty(headers)) {
    for (Header header : headers) {
      if (header.getValue().equalsIgnoreCase(new ODataPreferences().respondAsync())) {
        preferenceApplied = true;
      }
    }
  }
  try {
    EntityUtils.consume(res.getEntity());
  } catch (IOException ex) {
    Logger.getLogger(AsyncRequestWrapperImpl.class.getName()).log(Level.SEVERE, null, ex);
  }
}
 
Example #16
Source File: NavigationDrawerFragment.java    From school_shop with MIT License 5 votes vote down vote up
private void setAvatar(){
	RequestParams params = new RequestParams();
	params.add("userId", MyApplication.userInfo[1]);
	params.add("authCode", MyApplication.userInfo[0]);
	networkHelper.getNetJson(URLs.USERINFO, params, new AsyncHttpResponseHandler(){
		
		@Override
		public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
			Gson gson = new Gson();
			DataJson dataJson = gson.fromJson(new String(responseBody), DataJson.class);
			if (dataJson.isSuccess()) {
				if(dataJson.getData()!=null){
					UserEntity userEntity = gson.fromJson(gson.toJson(dataJson.getData()), UserEntity.class);
					if(userEntity.getAvatarUrl()!=null){
						Picasso picasso = Picasso.with(avatar.getContext());
						picasso.load(userEntity.getAvatarUrl()).placeholder(R.drawable.ic_avatar).into(avatar);
					}
				}else {
					showButtomToast(getStringByRId(R.string.getUserInfo_fail));
				}
			}else {
				showButtomToast("用户信息有误");
			}
		}
		
		@Override
		public void onFailure(int arg0, Header[] arg1, byte[] arg2, Throwable arg3) {
			loadingProgressDialog.dismiss();
		}
	});
}
 
Example #17
Source File: SimpleSSLTestCase.java    From quarkus-http with Apache License 2.0 5 votes vote down vote up
private void runTest(int concurrency, HttpHandler handler) throws IOException, InterruptedException {
    DefaultServer.setRootHandler(handler);
    DefaultServer.startSSLServer();
    try (CloseableHttpClient client = HttpClients.custom().disableConnectionState()
            .setSSLContext(DefaultServer.getClientSSLContext())
            .setDefaultSocketConfig(SocketConfig.custom().setSoTimeout(5000).build())
            .setMaxConnPerRoute(1000)
            .build()) {
        ExecutorService executorService = Executors.newFixedThreadPool(concurrency);
        AtomicBoolean failed = new AtomicBoolean();
        Runnable task = new Runnable() {
            @Override
            public void run() {
                if (failed.get()) {
                    return;
                }
                try (CloseableHttpResponse result = client.execute(new HttpGet(DefaultServer.getDefaultServerSSLAddress()))) {
                    Assert.assertEquals(StatusCodes.OK, result.getStatusLine().getStatusCode());
                    Header[] header = result.getHeaders("scheme");
                    Assert.assertEquals("https", header[0].getValue());
                    EntityUtils.consumeQuietly(result.getEntity());
                } catch (Throwable t) {
                    if (failed.compareAndSet(false, true)) {
                        t.printStackTrace();
                        executorService.shutdownNow();
                    }
                }
            }
        };
        for (int i = 0; i < concurrency * 300; i++) {
            executorService.submit(task);
        }
        executorService.shutdown();
        Assert.assertTrue(executorService.awaitTermination(70, TimeUnit.SECONDS));
        Assert.assertFalse(failed.get());
    } finally {
        DefaultServer.stopSSLServer();
    }
}
 
Example #18
Source File: HttpFetch.java    From activitystreams with Apache License 2.0 5 votes vote down vote up
private CloseableHttpClient initClient(Builder builder) {
  HttpClientBuilder b = builder.builder;
  b.setConnectionManager(manager);
  ImmutableSet<Header> headers = 
    builder.defaultHeaders.build();
  if (!headers.isEmpty())
    b.setDefaultHeaders(headers);
  if (builder.userAgent != null)
    b.setUserAgent(builder.userAgent);
  return b.build();
}
 
Example #19
Source File: AbstractRestApiUnitTest.java    From deprecated-security-advanced-modules with Apache License 2.0 5 votes vote down vote up
protected void setupStarfleetIndex() throws Exception {
	boolean sendHTTPClientCertificate = rh.sendHTTPClientCertificate;
	rh.sendHTTPClientCertificate = true;
	rh.executePutRequest("sf", null, new Header[0]);
	rh.executePutRequest("sf/ships/0", "{\"number\" : \"NCC-1701-D\"}", new Header[0]);
	rh.executePutRequest("sf/public/0", "{\"some\" : \"value\"}", new Header[0]);
	rh.sendHTTPClientCertificate = sendHTTPClientCertificate;
}
 
Example #20
Source File: Client.java    From hbase with Apache License 2.0 5 votes vote down vote up
/**
 * Send a POST request
 * @param cluster the cluster definition
 * @param path the path or URI
 * @param headers the HTTP headers to include, <tt>Content-Type</tt> must be
 * supplied
 * @param content the content bytes
 * @return a Response object with response detail
 * @throws IOException
 */
public Response post(Cluster cluster, String path, Header[] headers,
    byte[] content) throws IOException {
  HttpPost method = new HttpPost(path);
  try {
    method.setEntity(new InputStreamEntity(new ByteArrayInputStream(content), content.length));
    HttpResponse resp = execute(cluster, method, headers, path);
    headers = resp.getAllHeaders();
    content = getResponseBody(resp);
    return new Response(resp.getStatusLine().getStatusCode(), headers, content);
  } finally {
    method.releaseConnection();
  }
}
 
Example #21
Source File: RandomTestMocks.java    From BUbiNG with Apache License 2.0 5 votes vote down vote up
private static Header[] randomHeaders(final int maxNum, final int maxLen) {
	int n = RNG.nextInt(maxNum) + 1;
	Header[] ret = new Header[n];
	for (int i = 0; i < n; i++) {
		String name = "Random-" + RandomStringUtils.randomAlphabetic(RNG.nextInt(maxLen) + 1);
		String value = RandomStringUtils.randomAscii(RNG.nextInt(maxLen) + 1);
		ret[i] = new BasicHeader(name, value);
	}
	return ret;
}
 
Example #22
Source File: TokenDemo.java    From ais-sdk with Apache License 2.0 5 votes vote down vote up
/**
    * 身份证识别,使用Base64编码后的文件方式,使用Token认证方式访问服务
    * @param token token认证串
    * @param formFile 文件路径
    * @throws IOException
    */
   public static void requestOcrIDCardBase64(String token, String formFile) {

       // 1.构建身份证识别服务所需要的参数
	String url = "https://ais.cn-north-1.myhuaweicloud.com/v1.0/ocr/id-card";
	Header[] headers = new Header[] {new BasicHeader("X-Auth-Token", token), new BasicHeader("Content-Type", ContentType.APPLICATION_JSON.toString()) };
	try {
		byte[] fileData = FileUtils.readFileToByteArray(new File(formFile));
		String fileBase64Str = Base64.encodeBase64String(fileData);
		JSONObject json = new JSONObject();
		json.put("image", fileBase64Str);

		//
		// 此参数可选,指定获取身份证的正面或反面信息
		// "side"可选"front", "back"或"",不填默认为"",由算法自由判断,建议填写提高准确率
		//
		json.put("side","front");

		StringEntity stringEntity = new StringEntity(json.toJSONString(), "utf-8");

		// 2.传入身份证识别服务对应的参数, 使用POST方法调用服务并解析输出识别结果
		HttpResponse response = HttpClientUtils.post(url, headers, stringEntity);
		System.out.println(response);
		String content = IOUtils.toString(response.getEntity().getContent());
		System.out.println(content);
	} catch (Exception e) {
		e.printStackTrace();
	}

}
 
Example #23
Source File: TestGzipFilter.java    From hbase with Apache License 2.0 5 votes vote down vote up
void testScannerResultCodes() throws Exception {
  Header[] headers = new Header[3];
  headers[0] = new BasicHeader("Content-Type", Constants.MIMETYPE_XML);
  headers[1] = new BasicHeader("Accept", Constants.MIMETYPE_JSON);
  headers[2] = new BasicHeader("Accept-Encoding", "gzip");
  Response response = client.post("/" + TABLE + "/scanner", headers, Bytes.toBytes("<Scanner/>"));
  assertEquals(201, response.getCode());
  String scannerUrl = response.getLocation();
  assertNotNull(scannerUrl);
  response = client.get(scannerUrl);
  assertEquals(200, response.getCode());
  response = client.get(scannerUrl);
  assertEquals(204, response.getCode());
}
 
Example #24
Source File: CMODataAbapClient.java    From devops-cm-client with Apache License 2.0 5 votes vote down vote up
private Transport getTransport(CloseableHttpResponse response) throws UnsupportedOperationException, IOException, EntityProviderException, EdmException, UnexpectedHttpResponseException {

      Header[] contentType = response.getHeaders(HttpHeaders.CONTENT_TYPE);
      try(InputStream content = response.getEntity().getContent()) {
          return new Transport(EntityProvider.readEntry(contentType[0].getValue(),
                                         getEntityDataModel().getDefaultEntityContainer()
                                             .getEntitySet(TransportRequestBuilder.getEntityKey()),
                                         content,
                                         EntityProviderReadProperties.init().build()).getProperties());
      }
  }
 
Example #25
Source File: HttpClientTests.java    From vividus with Apache License 2.0 5 votes vote down vote up
@Test
void testDoHttpGet() throws Exception
{
    HttpHost httpHost = HttpHost.create(VIVIDUS_ORG);
    httpClient.setHttpHost(httpHost);
    CloseableHttpResponse closeableHttpResponse = mock(CloseableHttpResponse.class);
    HttpContext context = null;
    HttpEntity httpEntity = mock(HttpEntity.class);
    byte[] body = { 0, 1, 2 };
    Header[] headers = { header };
    StatusLine statusLine = mock(StatusLine.class);
    int statusCode = HttpStatus.SC_OK;
    when(httpEntity.getContent()).thenReturn(new ByteArrayInputStream(body));
    when(closeableHttpResponse.getEntity()).thenReturn(httpEntity);
    when(closeableHttpResponse.getAllHeaders()).thenReturn(headers);
    when(statusLine.getStatusCode()).thenReturn(statusCode);
    when(closeableHttpResponse.getStatusLine()).thenReturn(statusLine);
    when(closeableHttpClient.execute(eq(httpHost), isA(HttpGet.class), eq(context)))
            .thenAnswer(getAnswerWithSleep(closeableHttpResponse));
    HttpResponse httpResponse = httpClient.doHttpGet(URI_TO_GO);
    assertEquals(VIVIDUS_ORG, httpResponse.getFrom().toString());
    assertEquals(GET, httpResponse.getMethod());
    assertArrayEquals(body, httpResponse.getResponseBody());
    assertArrayEquals(headers, httpResponse.getResponseHeaders());
    assertEquals(statusCode, httpResponse.getStatusCode());
    assertThat(httpResponse.getResponseTimeInMs(), greaterThan(0L));
}
 
Example #26
Source File: RestClient.java    From nbp with Apache License 2.0 5 votes vote down vote up
private String getAuthToken(Header[] headers) 
{
	for (Header header : headers) {
		if(header.getName().equals("X-Subject-Token"))
		{
			return header.getValue();
		}
 	}
	return null;
}
 
Example #27
Source File: GraphqlDataServiceImpl.java    From commerce-cif-connector with Apache License 2.0 5 votes vote down vote up
protected GraphqlResponse<Query, Error> execute(String query, String storeView) {
    RequestOptions options = requestOptions;
    if (storeView != null) {
        Header storeHeader = new BasicHeader(Constants.STORE_HEADER, storeView);

        // Create new options to avoid setting the storeView as the new default value
        options = new RequestOptions()
            .withGson(requestOptions.getGson())
            .withHeaders(Collections.singletonList(storeHeader));
    }

    return baseClient.execute(new GraphqlRequest(query), Query.class, Error.class, options);
}
 
Example #28
Source File: Cookies.java    From api-layer with Eclipse Public License 2.0 5 votes vote down vote up
public void set(HttpCookie cookie) {
    if (getHeader(HttpHeaders.COOKIE).isEmpty()) {
        request.setHeader(new BasicHeader(HttpHeaders.COOKIE, cookie.toString()));
    } else {
        //cookie always added to first cookie header found
        Header cookieHeader = getHeader(HttpHeaders.COOKIE).get(0);
        List<HttpCookie> cookieList = getAllCookiesFromHeader(cookieHeader);
        cookieList = cookieList.stream()
            .filter(c -> !c.getName().equalsIgnoreCase(cookie.getName()))
            .collect(Collectors.toList());
        cookieList.add(cookie);
        request.setHeader(getCookieHeader(cookieList));
    }
}
 
Example #29
Source File: AppEngineHttpFetcher.java    From openid4java with Apache License 2.0 5 votes vote down vote up
private static Header getResponseHeader(HTTPResponse httpResponse, String headerName) {
  Header[] allHeaders = getResponseHeaders(httpResponse, headerName);
  if (allHeaders.length == 0) {
    return null;
  } else {
    return allHeaders[0];
  }
}
 
Example #30
Source File: GoogleApacheHttpResponse.java    From PYX-Reloaded with Apache License 2.0 5 votes vote down vote up
@Override
public String getContentType() {
    HttpEntity entity = response.getEntity();
    if (entity != null) {
        Header contentTypeHeader = entity.getContentType();
        if (contentTypeHeader != null) {
            return contentTypeHeader.getValue();
        }
    }

    return null;
}