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: BasicNetwork.java From android-common-utils with Apache License 2.0 | 6 votes |
/** * 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 #2
Source File: NodeFragment.java From v2ex-daily-android with Apache License 2.0 | 6 votes |
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 #3
Source File: MockHttpServletRequestBuilder.java From esigate with Apache License 2.0 | 6 votes |
/** * 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 #4
Source File: ClientCertRenegotiationTestCase.java From quarkus-http with Apache License 2.0 | 6 votes |
@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 #5
Source File: RangeFileAsyncHttpResponseHandler.java From android-project-wo2b with Apache License 2.0 | 6 votes |
@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 #6
Source File: FHIRToolingClient.java From org.hl7.fhir.core with Apache License 2.0 | 6 votes |
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 #7
Source File: FedoraProvider.java From fcrepo-camel-toolbox with Apache License 2.0 | 6 votes |
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 #8
Source File: HttpClientConfigTests.java From vividus with Apache License 2.0 | 6 votes |
@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
Source File: FHIRToolingClient.java From org.hl7.fhir.core with Apache License 2.0 | 6 votes |
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 #10
Source File: NUHttpOptions.java From neembuu-uploader with GNU General Public License v3.0 | 6 votes |
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 #11
Source File: ApacheGatewayConnectionTest.java From vespa with Apache License 2.0 | 5 votes |
@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 #12
Source File: GoogleApacheHttpResponse.java From PYX-Reloaded with Apache License 2.0 | 5 votes |
@Override public String getContentType() { HttpEntity entity = response.getEntity(); if (entity != null) { Header contentTypeHeader = entity.getContentType(); if (contentTypeHeader != null) { return contentTypeHeader.getValue(); } } return null; }
Example #13
Source File: AbstractRestApiUnitTest.java From deprecated-security-advanced-modules with Apache License 2.0 | 5 votes |
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 #14
Source File: SettingFirmwareActivity$SettingFirmwareFragment$DownloadFirmwareHandler.java From MiBandDecompiled with Apache License 2.0 | 5 votes |
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 #15
Source File: AsyncHttpClient.java From MiBandDecompiled with Apache License 2.0 | 5 votes |
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 #16
Source File: HTTPMethod.java From netcdf-java with BSD 3-Clause "New" or "Revised" License | 5 votes |
@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 #17
Source File: BasicNetwork.java From AndroidProjects with MIT License | 5 votes |
/** * 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 #18
Source File: AsyncHttpService.java From Tenable.io-SDK-for-Java with MIT License | 5 votes |
/** * 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 #19
Source File: WarcRecord.java From BUbiNG with Apache License 2.0 | 5 votes |
/** * 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 #20
Source File: AWSSigningRequestInterceptorTest.java From aws-signing-request-interceptor with MIT License | 5 votes |
@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 #21
Source File: AppEngineHttpFetcher.java From openid4java with Apache License 2.0 | 5 votes |
private static Header getResponseHeader(HTTPResponse httpResponse, String headerName) { Header[] allHeaders = getResponseHeaders(httpResponse, headerName); if (allHeaders.length == 0) { return null; } else { return allHeaders[0]; } }
Example #22
Source File: Client.java From hbase with Apache License 2.0 | 5 votes |
/** * 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 #23
Source File: RandomTestMocks.java From BUbiNG with Apache License 2.0 | 5 votes |
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 #24
Source File: Cookies.java From api-layer with Eclipse Public License 2.0 | 5 votes |
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 #25
Source File: TokenDemo.java From ais-sdk with Apache License 2.0 | 5 votes |
/** * 身份证识别,使用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 #26
Source File: TestGzipFilter.java From hbase with Apache License 2.0 | 5 votes |
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 #27
Source File: CMODataAbapClient.java From devops-cm-client with Apache License 2.0 | 5 votes |
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 #28
Source File: HttpClientTests.java From vividus with Apache License 2.0 | 5 votes |
@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 #29
Source File: RestClient.java From nbp with Apache License 2.0 | 5 votes |
private String getAuthToken(Header[] headers) { for (Header header : headers) { if(header.getName().equals("X-Subject-Token")) { return header.getValue(); } } return null; }
Example #30
Source File: GraphqlDataServiceImpl.java From commerce-cif-connector with Apache License 2.0 | 5 votes |
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); }