List of usage examples for org.apache.http.entity ByteArrayEntity ByteArrayEntity
public ByteArrayEntity(byte[] bArr)
From source file:test.Http.java
/** * post url :??jsonString???json,?json//from ww w . ja va 2 s .co m * * @date * @param url * @param jsonString * @return * @throws Exception */ public static String httpPost1(String url, String jsonString) throws Exception { String responseBodyData = null; HttpClient httpClient = new DefaultHttpClient(); HttpPost httpPost = new HttpPost(url); // ? // httpPost.addHeader("Content-Type", // "application/x-www-form-urlencoded"); httpPost.addHeader("Content-Type", "text/html"); httpPost.getParams().setParameter("http.socket.timeout", new Integer(60000)); httpClient.getParams().setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 1000 * 5); // Log.i(TAG, jsonString); // byte[] requestStrings = jsonString.getBytes("UTF-8"); ByteArrayEntity byteArrayEntity = new ByteArrayEntity(requestStrings); httpPost.setEntity(byteArrayEntity); HttpResponse response = httpClient.execute(httpPost);// post try { if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) { } HttpEntity entity = response.getEntity(); if (entity != null) { responseBodyData = EntityUtils.toString(entity, "UTF-8"); } } catch (Exception e) { // throw new Exception(e); e.printStackTrace(); } finally { httpPost.abort(); httpClient = null; } return responseBodyData; }
From source file:org.apache.nifi.toolkit.tls.service.client.TlsCertificateSigningRequestPerformer.java
/** * Submits a CSR to the Certificate authority, checks the resulting hmac, and returns the chain if everything succeeds * * @param keyPair the keypair to generate the csr for * @throws IOException if there is a problem during the process * @return the resulting certificate chain *///from w ww . ja v a 2s . c o m public X509Certificate[] perform(KeyPair keyPair) throws IOException { try { List<X509Certificate> certificates = new ArrayList<>(); HttpClientBuilder httpClientBuilder = httpClientBuilderSupplier.get(); SSLContextBuilder sslContextBuilder = SSLContextBuilder.create(); sslContextBuilder.useProtocol("TLSv1.2"); // We will be validating that we are talking to the correct host once we get the response's hmac of the token and public key of the ca sslContextBuilder.loadTrustMaterial(null, new TrustSelfSignedStrategy()); httpClientBuilder.setSSLSocketFactory(new TlsCertificateAuthorityClientSocketFactory( sslContextBuilder.build(), caHostname, certificates)); String jsonResponseString; int responseCode; try (CloseableHttpClient client = httpClientBuilder.build()) { JcaPKCS10CertificationRequest request = TlsHelper.generateCertificationRequest(dn, domainAlternativeNames, keyPair, signingAlgorithm); TlsCertificateAuthorityRequest tlsCertificateAuthorityRequest = new TlsCertificateAuthorityRequest( TlsHelper.calculateHMac(token, request.getPublicKey()), TlsHelper.pemEncodeJcaObject(request)); HttpPost httpPost = new HttpPost(); httpPost.setEntity( new ByteArrayEntity(objectMapper.writeValueAsBytes(tlsCertificateAuthorityRequest))); if (logger.isInfoEnabled()) { logger.info("Requesting certificate with dn " + dn + " from " + caHostname + ":" + port); } try (CloseableHttpResponse response = client.execute(new HttpHost(caHostname, port, "https"), httpPost)) { jsonResponseString = IOUtils.toString( new BoundedInputStream(response.getEntity().getContent(), 1024 * 1024), StandardCharsets.UTF_8); responseCode = response.getStatusLine().getStatusCode(); } } if (responseCode != Response.SC_OK) { throw new IOException( RECEIVED_RESPONSE_CODE + responseCode + " with payload " + jsonResponseString); } if (certificates.size() != 1) { throw new IOException(EXPECTED_ONE_CERTIFICATE); } TlsCertificateAuthorityResponse tlsCertificateAuthorityResponse = objectMapper .readValue(jsonResponseString, TlsCertificateAuthorityResponse.class); if (!tlsCertificateAuthorityResponse.hasHmac()) { throw new IOException(EXPECTED_RESPONSE_TO_CONTAIN_HMAC); } X509Certificate caCertificate = certificates.get(0); byte[] expectedHmac = TlsHelper.calculateHMac(token, caCertificate.getPublicKey()); if (!MessageDigest.isEqual(expectedHmac, tlsCertificateAuthorityResponse.getHmac())) { throw new IOException(UNEXPECTED_HMAC_RECEIVED_POSSIBLE_MAN_IN_THE_MIDDLE); } if (!tlsCertificateAuthorityResponse.hasCertificate()) { throw new IOException(EXPECTED_RESPONSE_TO_CONTAIN_CERTIFICATE); } X509Certificate x509Certificate = TlsHelper .parseCertificate(new StringReader(tlsCertificateAuthorityResponse.getPemEncodedCertificate())); x509Certificate.verify(caCertificate.getPublicKey()); if (logger.isInfoEnabled()) { logger.info("Got certificate with dn " + x509Certificate.getSubjectX500Principal()); } return new X509Certificate[] { x509Certificate, caCertificate }; } catch (IOException e) { throw e; } catch (Exception e) { throw new IOException(e); } }
From source file:org.wso2.cdm.agent.proxy.ServerApiAccess.java
public static Map<String, String> postDataAPI(APIUtilities apiUtilities, Map<String, String> headers) { String httpMethod = apiUtilities.getHttpMethod(); String url = apiUtilities.getEndPoint(); Map<String, String> params = apiUtilities.getRequestParamsMap(); Map<String, String> response_params = new HashMap<String, String>(); HttpClient httpclient = getCertifiedHttpClient(); String payload = buildPayload(params); if (httpMethod.equals("POST")) { HttpPost httpPost = new HttpPost(url); Log.e("url", "" + url); HttpPost httpPostWithHeaders = (HttpPost) buildHeaders(httpPost, headers, httpMethod); byte[] postData = payload.getBytes(); try {/*from www.j ava 2 s . c o m*/ httpPostWithHeaders.setEntity(new ByteArrayEntity(postData)); HttpResponse response = httpclient.execute(httpPostWithHeaders); String status = String.valueOf(response.getStatusLine().getStatusCode()); Log.d(TAG, status); response_params.put("response", getResponseBody(response)); response_params.put("status", status); return response_params; } catch (ClientProtocolException e) { Log.d(TAG, "ClientProtocolException :" + e.toString()); return null; } catch (IOException e) { Log.d(TAG, e.toString()); response_params.put("response", "Internal Server Error"); response_params.put("status", "500"); return response_params; } } return null; }
From source file:com.bigdata.rdf.sail.webapp.client.RemoteRepository.java
/** * Post a GraphML file to the blueprints layer of the remote bigdata instance. *//*from ww w . j a v a 2s.com*/ public long postGraphML(final String path) throws Exception { // TODO Allow client to specify UUID for postGraphML. See #1254. final UUID uuid = UUID.randomUUID(); final ConnectOptions opts = mgr.newConnectOptions(sparqlEndpointURL, uuid, tx); opts.addRequestParam("blueprints"); JettyResponseListener response = null; try { final File file = new File(path); if (!file.exists()) { throw new RuntimeException("cannot locate file: " + file.getAbsolutePath()); } final byte[] data = IOUtil.readBytes(file); final ByteArrayEntity entity = new ByteArrayEntity(data); entity.setContentType(ConnectOptions.MIME_GRAPH_ML); opts.entity = entity; opts.setAcceptHeader(ConnectOptions.MIME_APPLICATION_XML); checkResponseCode(response = doConnect(opts)); final MutationResult result = mutationResults(response); return result.mutationCount; } finally { if (response != null) response.abort(); } }
From source file:org.xwiki.eclipse.storage.rest.XWikiRestClient.java
protected HttpResponse executePostString(URI uri, String content) throws Exception { DefaultHttpClient httpClient = new DefaultHttpClient(); UsernamePasswordCredentials creds = new UsernamePasswordCredentials(username, password); HttpPost request = new HttpPost(uri); request.addHeader(new BasicScheme().authenticate(creds, request)); request.addHeader("Content-type", "text/plain; charset=UTF-8"); request.addHeader("Accept", MediaType.APPLICATION_XML); HttpEntity entity = new ByteArrayEntity(content.getBytes()); request.setEntity(entity);/* w ww. j av a 2 s. com*/ HttpResponse response = httpClient.execute(request); return response; }
From source file:com.olacabs.fabric.processors.httpwriter.HttpWriter.java
private EventSet handleRequest(EventSet eventSet, String httpMethodType) throws ProcessingException { ImmutableList.Builder<Object> builder = ImmutableList.builder(); EventSet.EventFromEventBuilder eventSetBuilder = EventSet.eventFromEventBuilder(); HttpRequestBase request = null;//ww w. j a v a 2 s .c o m boolean entityEnclosable = false; switch (httpMethodType) { case "get": request = createHttpGet(); break; case "post": request = createHttpPost(); entityEnclosable = true; break; case "put": request = createHttpPut(); entityEnclosable = true; break; default: log.error("Method not recognized...{}", this.getHttpMethod()); } request.setHeader("Content-Type", "application/json"); if (null != this.getHeaders()) { this.getHeaders().forEach(request::setHeader); } CloseableHttpResponse response = null; log.debug("Handling Put Request"); for (Event event : eventSet.getEvents()) { try { log.debug("Event in json format : {}", event.getJsonNode()); if (!isBulkSupported()) { if (entityEnclosable) { ((HttpEntityEnclosingRequest) request) .setEntity(new ByteArrayEntity((byte[]) event.getData())); } response = getClient().execute(request); handleResponse(response); if (shouldPublishResponse) { Event e = Event.builder() .jsonNode(getMapper().convertValue( createResponseMap(event, response, httpMethodType), JsonNode.class)) .build(); e.setProperties(event.getProperties()); eventSetBuilder.isAggregate(false).partitionId(eventSet.getPartitionId()).event(e); } } else { builder.add(event.getData()); } } catch (Exception e) { log.error("Error processing data", e); throw new ProcessingException(); } finally { close(response); } } if (isBulkSupported()) { try { log.debug("Making Bulk call as bulk is supported"); if (entityEnclosable) { ((HttpEntityEnclosingRequest) request) .setEntity(new ByteArrayEntity(getMapper().writeValueAsBytes(builder.build()))); } response = client.execute(request); handleResponse(response); } catch (Exception e) { log.error("Exception", e); throw new ProcessingException(); } finally { close(response); } } else { if (shouldPublishResponse) { return eventSetBuilder.build(); } } return null; }
From source file:com.twilio.sdk.AppEngineClientConnection.java
public void receiveResponseEntity(HttpResponse response) throws HttpException, IOException { if (this.response == null) { throw new IOException("receiveResponseEntity() called when closed"); }// www .j av a2 s.c om ByteArrayEntity bae; try { Method getContentMethod = this.response.getClass().getMethod("getContent", new Class[0]); bae = new ByteArrayEntity((byte[]) getContentMethod.invoke(this.response, new Object[0])); bae.setContentType(response.getFirstHeader("Content-Type")); response.setEntity(bae); response = null; } catch (Exception e) { e.printStackTrace(); throw new HttpException("Error occurred while using Google App Engine URL fetch"); } }
From source file:com.investoday.code.util.aliyun.api.gateway.util.HttpUtil.java
/** * HTTP POST /*from www . j ava 2s . c o m*/ * * @param url http://host+path+query * @param headers Http * @param bytes * @param appKey APP KEY * @param appSecret APP * @param timeout * @param signHeaderPrefixList ???Header? * @return * @throws Exception */ public static HttpResponse httpPost(String url, Map<String, String> headers, byte[] bytes, String appKey, String appSecret, int timeout, List<String> signHeaderPrefixList) throws Exception { headers = initialBasicHeader(headers, appKey, appSecret, HttpMethod.POST, url, null, signHeaderPrefixList); HttpClient httpClient = new DefaultHttpClient(); httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, getTimeout(timeout)); HttpPost post = new HttpPost(url); for (Map.Entry<String, String> e : headers.entrySet()) { post.addHeader(e.getKey(), e.getValue()); } if (bytes != null) { post.setEntity(new ByteArrayEntity(bytes)); } return httpClient.execute(post); }
From source file:com.riksof.a320.http.CoreHttpClient.java
/** * This method is used to execute Post Http Request * /*w ww. j a va 2 s .c o m*/ * @param url * @param postMessage * @return */ public String executePost(String url, String postMessage) throws ServerException { HttpParams httpParameters = new BasicHttpParams(); HttpConnectionParams.setConnectionTimeout(httpParameters, connectionTimeOut); HttpConnectionParams.setSoTimeout(httpParameters, socketTimeOut); DefaultHttpClient httpclient = new DefaultHttpClient(httpParameters); HttpPost httppost = new HttpPost(url); httppost.setHeader("Content-Type", "application/json"); // Response String String responseString = null; try { httppost.setEntity(new ByteArrayEntity(postMessage.toString().getBytes("UTF8"))); // Execute HTTP Post Request HttpResponse response = httpclient.execute(httppost); HttpEntity entity = response.getEntity(); // Create and convert stream into string InputStream inStream = entity.getContent(); responseString = convertStreamToString(inStream); } catch (SocketTimeoutException e) { // throw custom server exception in case of Exception Log.e("HttpClient", "Timeout Exception"); throw new ServerException("Request Timeout"); } catch (IOException e) { // throw custom server exception in case of Exception Log.e("HttpClient", "IO Exception"); throw new ServerException("Request Timeout"); } return responseString; }