List of usage examples for org.apache.http.message BasicHeader BasicHeader
public BasicHeader(String str, String str2)
From source file:org.myframe.http.HttpConnectStack.java
@Override public HttpResponse performRequest(Request<?> request, Map<String, String> additionalHeaders) throws IOException { String url = request.getUrl(); HashMap<String, String> map = new HashMap<String, String>(); map.putAll(request.getHeaders());/*from w w w . ja v a 2 s . c o m*/ 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); ProtocolVersion protocolVersion = new ProtocolVersion("HTTP", 1, 1); int responseCode = connection.getResponseCode(); if (responseCode == -1) { 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) { String value = ""; for (String v : header.getValue()) { value += (v + "; "); } Header h = new BasicHeader(header.getKey(), value); response.addHeader(h); } } return response; }
From source file:org.obm.sync.push.client.XMLOPClient.java
@Override public Document postXml(String namespace, Document doc, String cmd, String policyKey, boolean multipart) throws TransformerException, WBXmlException, IOException, HttpRequestException { DOMUtils.logDom(doc);//ww w.j a v a2s . c o m ByteArrayEntity requestEntity = getRequestEntity(doc); HttpPost request = new HttpPost(ai.getUrl() + "?User=" + ai.getLogin()); request.setHeaders( new Header[] { new BasicHeader("Content-Type", requestEntity.getContentType().getValue()), new BasicHeader("Authorization", ai.authValue()), new BasicHeader("Accept", "*/*"), new BasicHeader("Accept-Language", "fr-fr"), new BasicHeader("Connection", "keep-alive") }); request.setEntity(requestEntity); try { HttpResponse response = hc.execute(request); StatusLine statusLine = response.getStatusLine(); Header[] hs = response.getAllHeaders(); for (Header h : hs) { logger.error("head[" + h.getName() + "] => " + h.getValue()); } int statusCode = statusLine.getStatusCode(); if (statusCode != HttpStatus.SC_OK) { logger.error("method failed:{}\n{}\n", statusLine, response.getEntity()); throw new HttpRequestException(statusCode); } else { InputStream in = response.getEntity().getContent(); Document docResponse = DOMUtils.parse(in); DOMUtils.logDom(docResponse); return docResponse; } } catch (SAXException e) { throw new TransformerException(e); } catch (FactoryConfigurationError e) { throw new TransformerException(e); } finally { request.releaseConnection(); } }
From source file:net.java.sip.communicator.service.httputil.HttpUtils.java
/** * Opens a connection to the <tt>address</tt>. * @param address the address to contact. * @param usernamePropertyName the property to use to retrieve/store * username value if protected site is hit, for username * ConfigurationService service is used. * @param passwordPropertyName the property to use to retrieve/store * password value if protected site is hit, for password * CredentialsStorageService service is used. * @param headerParamNames additional header name to include * @param headerParamValues corresponding header value to include * @return the result if any or null if connection was not possible * or canceled by user./*from w w w. j av a 2s . co m*/ */ public static HTTPResponseResult openURLConnection(String address, String usernamePropertyName, String passwordPropertyName, String[] headerParamNames, String[] headerParamValues) { try { HttpGet httpGet = new HttpGet(address); DefaultHttpClient httpClient = getHttpClient(usernamePropertyName, passwordPropertyName, httpGet.getURI().getHost(), null); /* add additional HTTP header */ if (headerParamNames != null && headerParamValues != null) { for (int i = 0; i < headerParamNames.length; i++) { httpGet.addHeader(new BasicHeader(headerParamNames[i], headerParamValues[i])); } } HttpEntity result = executeMethod(httpClient, httpGet, null, null); if (result == null) return null; return new HTTPResponseResult(result, httpClient); } catch (Throwable t) { logger.error("Cannot open connection to:" + address, t); } return null; }
From source file:br.com.intercomex.ws.GnreConfigUF.java
/** * This is a sample web service operation *///from w w w .j a v a2 s.c o m @WebMethod(operationName = "consultar") public String consultar(@WebParam(name = "gnreDadosMsg") TConsultaConfigUf gnreDadosMsg) { String retorno = null; loadConfig(); try { //<TConsultaConfigUf xmlns=\"http://www.gnre.pe.gov.br\"><ambiente>1</ambiente><uf>MG</uf><receita>100048</receita></TConsultaConfigUf> String XML_DATA = "<soap:Envelope xmlns:soap=\"http://www.w3.org/2003/05/soap-envelope\" xmlns:gnr=\"http://www.gnre.pe.gov.br/webservice/GnreConfigUF\">" + "<soap:Header><gnr:gnreCabecMsg><gnr:versaoDados>1.00</gnr:versaoDados></gnr:gnreCabecMsg></soap:Header>" + " <soap:Body><gnr:gnreDadosMsg>" + gnreDadosMsg + "</gnr:gnreDadosMsg></soap:Body></soap:Envelope>"; System.out.println("PARAMETRO envio ==== " + gnreDadosMsg); HttpPost httpPost = new HttpPost(url); httpPost.setHeader(new BasicHeader("Content-Type", "application/soap+xml;charset=UTF-8")); httpPost.setHeader(new BasicHeader("SOAPAction", action)); StringEntity s = new StringEntity(XML_DATA, "UTF-8"); httpPost.setEntity(s); FileInputStream instream = null; FileInputStream instreamTrust = null; KeyStore keyStore = KeyStore.getInstance("PKCS12"); instream = new FileInputStream(new File(caminhoDoCertificadoDoCliente)); keyStore.load(instream, senhaDoCertificadoDoCliente.toCharArray()); KeyStore trustStore = KeyStore.getInstance("JKS"); instreamTrust = new FileInputStream(new File(arquivoCacertsGeradoParaCadaEstado)); trustStore.load(instreamTrust, senhaDoCertificadoDoCliente.toCharArray()); SSLContextBuilder builder = SSLContexts.custom().loadTrustMaterial(trustStore); builder.loadKeyMaterial(keyStore, senhaDoCertificadoDoCliente.toCharArray()); SSLContext sslcontext = builder.build(); SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext, SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER); CloseableHttpClient httpclientSLL = HttpClients.custom().setSSLSocketFactory(sslsf).build(); System.out.println("executing request" + httpPost.getRequestLine()); HttpResponse response = httpclientSLL.execute(httpPost); HttpEntity entity = response.getEntity(); System.out.println("----------------------------------------"); System.out.println(response.getStatusLine()); if (entity != null) { System.out.println("Response content length: " + entity.getContentLength()); retorno = EntityUtils.toString(response.getEntity()); System.out.println(retorno); } if (entity != null) { entity.consumeContent(); } httpclient.getConnectionManager().shutdown(); } catch (UnsupportedEncodingException ex) { Logger.getLogger(GnreConfigUF.class.getName()).log(Level.SEVERE, null, ex); } catch (KeyStoreException ex) { Logger.getLogger(GnreConfigUF.class.getName()).log(Level.SEVERE, null, ex); } catch (FileNotFoundException ex) { Logger.getLogger(GnreConfigUF.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(GnreConfigUF.class.getName()).log(Level.SEVERE, null, ex); } catch (NoSuchAlgorithmException ex) { Logger.getLogger(GnreConfigUF.class.getName()).log(Level.SEVERE, null, ex); } catch (CertificateException ex) { Logger.getLogger(GnreConfigUF.class.getName()).log(Level.SEVERE, null, ex); } catch (UnrecoverableKeyException ex) { Logger.getLogger(GnreConfigUF.class.getName()).log(Level.SEVERE, null, ex); } catch (KeyManagementException ex) { Logger.getLogger(GnreConfigUF.class.getName()).log(Level.SEVERE, null, ex); } return retorno; }
From source file:com.joyent.manta.http.EncryptedHttpHelperTest.java
/** * Builds a fully mocked {@link EncryptionHttpHelper} that is setup to * be configured for one cipher/mode and executes requests in another * cipher/mode.//from w w w.j a va 2 s . co m */ private static EncryptionHttpHelper fakeEncryptionHttpHelper(String path) throws Exception { MantaConnectionContext connectionContext = mock(MantaConnectionContext.class); StandardConfigContext config = new StandardConfigContext(); SupportedCipherDetails cipherDetails = AesCbcCipherDetails.INSTANCE_192_BIT; config.setClientEncryptionEnabled(true) .setEncryptionPrivateKeyBytes(SecretKeyUtils.generate(cipherDetails).getEncoded()) .setEncryptionAlgorithm(cipherDetails.getCipherId()); EncryptionHttpHelper httpHelper = new EncryptionHttpHelper(connectionContext, new MantaHttpRequestFactory(UnitTestConstants.UNIT_TEST_URL), config); URI uri = URI.create(DEFAULT_MANTA_URL + "/" + path); CloseableHttpResponse fakeResponse = mock(CloseableHttpResponse.class); StatusLine statusLine = new BasicStatusLine(HttpVersion.HTTP_1_1, HttpStatus.SC_OK, "OK"); SupportedCipherDetails objectCipherDetails = AesGcmCipherDetails.INSTANCE_128_BIT; Header[] headers = new Header[] { // Notice this is a different cipher than the one set in config new BasicHeader(MantaHttpHeaders.ENCRYPTION_CIPHER, objectCipherDetails.getCipherId()) }; when(fakeResponse.getAllHeaders()).thenReturn(headers); when(fakeResponse.getStatusLine()).thenReturn(statusLine); BasicHttpEntity fakeEntity = new BasicHttpEntity(); InputStream source = IOUtils.toInputStream("I'm a stream", StandardCharsets.US_ASCII); EofSensorInputStream stream = new EofSensorInputStream(source, null); fakeEntity.setContent(stream); when(fakeResponse.getEntity()).thenReturn(fakeEntity); when(connectionContext.getHttpClient()).thenReturn(new FakeCloseableHttpClient(fakeResponse)); return httpHelper; }
From source file:com.samebug.clients.search.api.client.RawClient.java
RawClient(@NotNull final Config config) { HttpClientBuilder httpBuilder = HttpClientBuilder.create(); requestConfigBuilder = RequestConfig.custom(); CredentialsProvider provider = new BasicCredentialsProvider(); requestConfigBuilder.setConnectTimeout(config.connectTimeout).setSocketTimeout(config.requestTimeout) .setConnectionRequestTimeout(500); try {/*from w ww .j a va 2 s . c o m*/ IdeHttpClientHelpers.ApacheHttpClient4.setProxyForUrlIfEnabled(requestConfigBuilder, config.serverRoot); IdeHttpClientHelpers.ApacheHttpClient4.setProxyCredentialsForUrlIfEnabled(provider, config.serverRoot); } catch (Throwable e) { // fallback to traditional proxy config for backward compatiblity try { final HttpConfigurable proxySettings = HttpConfigurable.getInstance(); final ProxyCredentialsFacade facade = new ProxyCredentialsFacade(proxySettings); if (proxySettings != null && proxySettings.USE_HTTP_PROXY && !StringUtil.isEmptyOrSpaces(proxySettings.PROXY_HOST)) { requestConfigBuilder.setProxy(new HttpHost(proxySettings.PROXY_HOST, proxySettings.PROXY_PORT)); if (proxySettings.PROXY_AUTHENTICATION) { provider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(facade.getLogin(), facade.getPassword())); } } } catch (Throwable ignored) { // if even that fails, we cannot do more } } defaultRequestConfig = requestConfigBuilder.build(); trackingConfig = requestConfigBuilder.setSocketTimeout(TrackingRequestTimeout_Millis).build(); List<BasicHeader> defaultHeaders = new ArrayList<BasicHeader>(); defaultHeaders.add(new BasicHeader("User-Agent", USER_AGENT)); if (config.apiKey != null) defaultHeaders.add(new BasicHeader("X-Samebug-ApiKey", config.apiKey)); if (config.workspaceId != null) defaultHeaders.add(new BasicHeader("X-Samebug-WorkspaceId", config.workspaceId.toString())); httpClient = httpBuilder.setDefaultRequestConfig(defaultRequestConfig).setMaxConnTotal(MaxConnections) .setMaxConnPerRoute(MaxConnections).setDefaultCredentialsProvider(provider) .setDefaultHeaders(defaultHeaders).build(); if (config.isApacheLoggingEnabled) enableApacheLogging(); }
From source file:org.elasticsearch.xpack.ssl.SSLClientAuthTests.java
public void testThatHttpWorksWithSslClientAuth() throws IOException { SSLIOSessionStrategy sessionStrategy = new SSLIOSessionStrategy(getSSLContext(), NoopHostnameVerifier.INSTANCE); try (RestClient restClient = createRestClient( httpClientBuilder -> httpClientBuilder.setSSLStrategy(sessionStrategy), "https")) { Response response = restClient.performRequest("GET", "/", new BasicHeader("Authorization", basicAuthHeaderValue(transportClientUsername(), transportClientPassword()))); assertThat(response.getStatusLine().getStatusCode(), equalTo(200)); assertThat(EntityUtils.toString(response.getEntity()), containsString("You Know, for Search")); }/*w w w . j ava2s. c o m*/ }
From source file:com.momock.service.JsonService.java
@Override public void put(String url, String json, Header[] headers, final IEventHandler<JsonEventArgs> handler) { Logger.check(httpService != null, "The httpService must not be null!"); StringEntity entity = null;//from w ww . j a va2s.co m if (headers == null) headers = new Header[] { new BasicHeader(JSON_HEADER_KEY, JSON_HEADER_VAL) }; try { entity = new StringEntity(json, "UTF-8"); } catch (UnsupportedEncodingException e) { } final HttpSession session = httpService.put(url, headers, entity); session.getStateChangedEvent().addEventHandler(new IEventHandler<StateChangedEventArgs>() { @Override public void process(Object sender, StateChangedEventArgs args) { if (args.getState() == HttpSession.STATE_FINISHED) { JsonEventArgs a = new JsonEventArgs(session.getResultAsString(null), session.getError()); handler.process(session, a); } } }); session.start(); }
From source file:org.openscore.content.httpclient.build.auth.AuthSchemeProviderLookupBuilder.java
public Lookup<AuthSchemeProvider> buildAuthSchemeProviderLookup() { RegistryBuilder<AuthSchemeProvider> registryBuilder = RegistryBuilder.create(); for (String type : authTypes) { switch (type.trim()) { case "NTLM": registryBuilder.register(AuthSchemes.NTLM, new AuthSchemeProvider() { @Override//from w w w.j av a 2 s . c o m public AuthScheme create(HttpContext httpContext) { return new NTLMScheme(new JCIFSEngine()); } }); break; case "BASIC": registryBuilder.register(AuthSchemes.BASIC, new BasicSchemeFactory(Charset.forName("UTF-8"))); String value = username + ":" + password; byte[] encodedValue = Base64.encodeBase64(value.getBytes(StandardCharsets.UTF_8)); headers.add(new BasicHeader("Authorization", "Basic " + new String(encodedValue))); break; case "DIGEST": registryBuilder.register(AuthSchemes.DIGEST, new DigestSchemeFactory()); break; case "KERBEROS": if (getSettingsKey().equals(System.getProperty("oohttpclient.krb.last.settings"))) { break; } if (kerberosConfigFile != null) { System.setProperty("java.security.krb5.conf", kerberosConfigFile); } else { File krb5Config; String domain = host.replaceAll(".*\\.(?=.*\\.)", ""); try { krb5Config = createKrb5Configuration(domain); } catch (IOException e) { throw new RuntimeException("could not create the krb5 config file" + e.getMessage(), e); } System.setProperty("java.security.krb5.conf", krb5Config.toURI().toString()); } if (kerberosLoginConfigFile != null) { System.setProperty("java.security.auth.login.config", kerberosLoginConfigFile); } else { File loginConfig; try { loginConfig = createLoginConfig(); } catch (IOException e) { throw new RuntimeException( "could not create the kerberos login config file" + e.getMessage(), e); } System.setProperty("java.security.auth.login.config", loginConfig.toURI().toString()); } //todo fix security issue if (password != null) { System.setProperty(KrbHttpLoginModule.PAS, password); } if (username != null) { System.setProperty(KrbHttpLoginModule.USR, username); } System.setProperty("javax.security.auth.useSubjectCredsOnly", "false"); boolean skipPort = Boolean.parseBoolean(skipPortAtKerberosDatabaseLookup); registryBuilder.register(AuthSchemes.KERBEROS, new KerberosSchemeFactory(skipPort)); registryBuilder.register(AuthSchemes.SPNEGO, new SPNegoSchemeFactory(skipPort)); System.setProperty("oohttpclient.krb.last.settings", getSettingsKey()); break; default: throw new IllegalStateException( "Unsupported '" + HttpClientInputs.AUTH_TYPE + "'authentication scheme: " + type); } } return registryBuilder.build(); }