Java Code Examples for org.apache.http.Header

The following examples show how to use org.apache.http.Header. These examples are extracted from open source projects. 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 want to check out the right sidebar which shows the related API usage.
Example 1
Source Project: v2ex-daily-android   Source File: NodeFragment.java    License: 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 Project: org.hl7.fhir.core   Source File: FHIRToolingClient.java    License: 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 Project: org.hl7.fhir.core   Source File: FHIRToolingClient.java    License: 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
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 Project: fcrepo-camel-toolbox   Source File: FedoraProvider.java    License: 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 6
Source Project: esigate   Source File: MockHttpServletRequestBuilder.java    License: 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 7
@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 8
Source Project: vividus   Source File: HttpClientConfigTests.java    License: 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 9
@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 10
Source Project: BUbiNG   Source File: WarcRecord.java    License: 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 11
@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 12
Source Project: Brutusin-RPC   Source File: HttpEndpoint.java    License: 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 13
Source Project: android-common-utils   Source File: BasicNetwork.java    License: Apache License 2.0 5 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 14
Source Project: nifi   Source File: SiteToSiteRestApiClient.java    License: 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 Project: olingo-odata4   Source File: AsyncRequestWrapperImpl.java    License: 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 Project: school_shop   Source File: NavigationDrawerFragment.java    License: 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 Project: quarkus-http   Source File: SimpleSSLTestCase.java    License: 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 Project: activitystreams   Source File: HttpFetch.java    License: 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
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 Project: hbase   Source File: Client.java    License: 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 Project: BUbiNG   Source File: RandomTestMocks.java    License: 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 Project: ais-sdk   Source File: TokenDemo.java    License: 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 Project: hbase   Source File: TestGzipFilter.java    License: 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 Project: devops-cm-client   Source File: CMODataAbapClient.java    License: 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 Project: vividus   Source File: HttpClientTests.java    License: 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 Project: nbp   Source File: RestClient.java    License: 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
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 Project: api-layer   Source File: Cookies.java    License: 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 Project: openid4java   Source File: AppEngineHttpFetcher.java    License: 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 Project: PYX-Reloaded   Source File: GoogleApacheHttpResponse.java    License: 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;
}
 
Example 31
public void onSuccess(int i, Header aheader[], File file)
{
    Debug.i("Setting.Firmware", "Download On Success!!");
    if (aheader != null)
    {
        int j = aheader.length;
        for (int k = 0; k < j; k++)
        {
            Header header = aheader[k];
            Debug.i("Setting.Firmware", (new StringBuilder()).append(header.getName()).append(" : ").append(header.getValue()).toString());
        }

    }
    if (f)
    {
        return;
    }
    String s = d.getPath();
    File file1 = new File(s.substring(0, s.length() - ".tmp".length()));
    if (file1.exists())
    {
        file1.delete();
    }
    d.renameTo(file1);
    Debug.i("Setting.Firmware", (new StringBuilder()).append("FirmwareFile : ").append(file1).append(" , ").append(file1.exists()).append(" , ").append(file1.length()).toString());
    String s1 = md5sum(file1);
    Debug.i("Setting.Firmware", (new StringBuilder()).append("FirmwareMd5 : ").append(s1).toString());
    if (s1.equalsIgnoreCase(e.firmwareMd5))
    {
        b.b();
        return;
    } else
    {
        CustomToast.makeText(c, "\u56FA\u4EF6\u6821\u9A8C\u5931\u8D25\uFF0C\u8BF7\u91CD\u8BD5", 0).show();
        return;
    }
}
 
Example 32
Source Project: MiBandDecompiled   Source File: AsyncHttpClient.java    License: Apache License 2.0 5 votes vote down vote up
public RequestHandle delete(Context context, String s, Header aheader[], RequestParams requestparams, ResponseHandlerInterface responsehandlerinterface)
{
    HttpDelete httpdelete = new HttpDelete(getUrlWithQueryString(h, s, requestparams));
    if (aheader != null)
    {
        httpdelete.setHeaders(aheader);
    }
    return sendRequest(c, d, httpdelete, null, responsehandlerinterface, context);
}
 
Example 33
Source Project: vespa   Source File: ApacheGatewayConnectionTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void dynamic_headers_are_added_to_the_response() throws IOException, ServerResponseException {
    ConnectionParams.HeaderProvider headerProvider = mock(ConnectionParams.HeaderProvider.class);
    when(headerProvider.getHeaderValue())
            .thenReturn("v1")
            .thenReturn("v2")
            .thenReturn("v3");

    ConnectionParams connectionParams = new ConnectionParams.Builder()
            .addDynamicHeader("foo", headerProvider)
            .build();

    AtomicInteger counter = new AtomicInteger(1);
    ApacheGatewayConnection.HttpClientFactory mockFactory = mockHttpClientFactory(post  -> {
        Header[] fooHeader = post.getHeaders("foo");
        assertEquals(1, fooHeader.length);
        assertEquals("foo", fooHeader[0].getName());
        assertEquals("v" + counter.getAndIncrement(), fooHeader[0].getValue());
        return httpResponse("clientId", "3");

    });

    ApacheGatewayConnection apacheGatewayConnection =
        new ApacheGatewayConnection(
                Endpoint.create("localhost", 666, false),
                new FeedParams.Builder().build(),
                "",
                connectionParams,
                mockFactory,
                "clientId");
    apacheGatewayConnection.connect();
    apacheGatewayConnection.handshake();

    List<Document> documents = new ArrayList<>();
    documents.add(createDoc("42", "content", true));
    apacheGatewayConnection.writeOperations(documents);
    apacheGatewayConnection.writeOperations(documents);

    verify(headerProvider, times(3)).getHeaderValue(); // 1x connect(), 2x writeOperations()
}
 
Example 34
Source Project: AndroidProjects   Source File: BasicNetwork.java    License: MIT License 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 35
Source Project: letv   Source File: JsonHttpResponseHandler.java    License: Apache License 2.0 5 votes vote down vote up
protected void sendSuccessMessage(int statusCode, Header[] headers, String responseBody) {
    if (statusCode != LeMessageIds.MSG_MAIN_GO_TO_LIVE_ROOM) {
        try {
            Object jsonResponse = parseResponse(responseBody);
            sendMessage(obtainMessage(100, new Object[]{Integer.valueOf(statusCode), headers, jsonResponse}));
            return;
        } catch (JSONException e) {
            sendFailureMessage((Throwable) e, responseBody);
            return;
        }
    }
    sendMessage(obtainMessage(100, new Object[]{Integer.valueOf(statusCode), new JSONObject()}));
}
 
Example 36
@Test
public void queryParamsSupportEmptyValues() throws Exception {
    final String key = "a";
    final String url = "http://someurl.com?" + key + "=";
    final Multimap<String, String> queryParams = ImmutableListMultimap.of(key, "");

    when(signer.getSignedHeaders(anyString(), anyString(), eq(queryParams), anyMapOf(String.class, Object.class), any(com.google.common.base.Optional.class))).thenReturn(ImmutableMap.of());
    mockRequest(url);

    interceptor.process(request, context);

    verify(request).setHeaders(new Header[]{});
    verify(signer).getSignedHeaders(anyString(), anyString(), eq(queryParams), anyMapOf(String.class, Object.class), any(com.google.common.base.Optional.class));
}
 
Example 37
Source Project: data-prep   Source File: CommandHelper.java    License: Apache License 2.0 5 votes vote down vote up
public static ResponseEntity<StreamingResponseBody> toStreaming(final GenericCommand<InputStream> command) {
    final Observable<InputStream> stream = command.toObservable();
    return stream.map(is -> {
        // Content for the response entity
        final StreamingResponseBody body = outputStream -> {
            try {
                IOUtils.copyLarge(is, outputStream);
                outputStream.flush();
            } catch (IOException e) {
                try {
                    is.close();
                } catch (IOException closingException) {
                    LOGGER.warn("could not close command result, a http connection may be leaked !",
                            closingException);
                }
                LOGGER.error("Unable to fully copy command result '{}'.", command.getClass(), e);
            }
        };
        // copy all headers from the command response so that the mime-type is correctly forwarded. Command has
        // the correct headers due to call to toBlocking() below.
        final MultiValueMap<String, String> headers = new HttpHeaders();
        final HttpStatus status = command.getStatus();
        for (Header header : command.getCommandResponseHeaders()) {
            headers.put(header.getName(), Collections.singletonList(header.getValue()));
        }
        return new ResponseEntity<>(body, headers, status == null ? HttpStatus.OK : status);
    }).toBlocking().first();
}
 
Example 38
@Override
public File execute(String uri, String queryParam) throws WxErrorException, IOException {
  if (queryParam != null) {
    if (uri.indexOf('?') == -1) {
      uri += '?';
    }
    uri += uri.endsWith("?") ? queryParam : '&' + queryParam;
  }

  HttpGet httpGet = new HttpGet(uri);
  if (requestHttp.getRequestHttpProxy() != null) {
    RequestConfig config = RequestConfig.custom().setProxy(requestHttp.getRequestHttpProxy()).build();
    httpGet.setConfig(config);
  }

  try (CloseableHttpResponse response = requestHttp.getRequestHttpClient().execute(httpGet);
       InputStream inputStream = InputStreamResponseHandler.INSTANCE.handleResponse(response)) {
    Header[] contentTypeHeader = response.getHeaders("Content-Type");
    if (contentTypeHeader != null && contentTypeHeader.length > 0) {
      if (contentTypeHeader[0].getValue().startsWith(ContentType.APPLICATION_JSON.getMimeType())) {
        // application/json; encoding=utf-8 下载媒体文件出错
        String responseContent = Utf8ResponseHandler.INSTANCE.handleResponse(response);
        throw new WxErrorException(WxError.fromJson(responseContent));
      }
    }

    String fileName = new HttpResponseProxy(response).getFileName();
    if (StringUtils.isBlank(fileName)) {
      return null;
    }

    return FileUtils.createTmpFile(inputStream, FilenameUtils.getBaseName(fileName), FilenameUtils.getExtension(fileName),
      super.tmpDirFile);

  } finally {
    httpGet.releaseConnection();
  }
}
 
Example 39
Source Project: Tenable.io-SDK-for-Java   Source File: AsyncHttpService.java    License: MIT License 5 votes vote down vote up
/**
 * Makes an HTTP PUT request using the given URI and optional byte array body and headers.
 *
 * @param uri the URI to use for the PUT call
 * @param contentType The content-type. Use helper function org.apache.http.entity.ContentType.create() to generate
 * @param body Optional, can be null. An byte array that will be PUTed as is
 * @param headers Optional, can be null. One or more HTTP headers, typically created by instancing org.apache.http.message.BasicHeader
 * @return the resulting HttpFuture instance
 */
public HttpFuture doPut( URI uri, ContentType contentType, byte[] body, Header[] headers ) {
    HttpPut httpPut = new HttpPut( uri );

    if( body != null ) {
        httpPut.setEntity( new NByteArrayEntity( body, contentType ) );
    }

    if( headers != null && headers.length > 0 )
        httpPut.setHeaders( headers );

    return new HttpFuture( this, httpPut, asyncClient.execute( httpPut, null ), null );
}
 
Example 40
Source Project: PYX-Reloaded   Source File: TwitterAuthHelper.java    License: Apache License 2.0 5 votes vote down vote up
@NotNull
private Response execute(HttpRequestBase request) throws IOException {
    HttpResponse resp = client.execute(request);

    Map<String, String> headers = new HashMap<>();
    for (Header header : request.getAllHeaders())
        headers.put(header.getName(), header.getValue());

    StatusLine sl = resp.getStatusLine();
    return new Response(sl.getStatusCode(), sl.getReasonPhrase(), headers, resp.getEntity().getContent());
}