String url = "http://yourserver"; File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath(), "yourfile"); try { HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost(url); InputStreamEntity reqEntity = new InputStreamEntity( new FileInputStream(file), -1); reqEntity.setContentType("binary/octet-stream"); reqEntity.setChunked(true); // Send in multiple parts if needed httppost.setEntity(reqEntity); HttpResponse response = httpclient.execute(httppost); //Do something with response... } catch (Exception e) { // show error }
/** * Returns true if the underlying InputStream supports marking/reseting or * if the underlying InputStreamRequestEntity is repeatable (i.e. its * content length has been set to * {@link InputStreamRequestEntity#CONTENT_LENGTH_AUTO} and therefore its * entire contents will be buffered in memory and can be repeated). * * @see org.apache.commons.httpclient.methods.RequestEntity#isRepeatable() */ @Override public boolean isRepeatable() { return content.markSupported() || inputStreamRequestEntity.isRepeatable(); }
/** * Resets the underlying InputStream if this isn't the first attempt to * write out the request, otherwise simply delegates to * InputStreamRequestEntity to write out the data. * <p> * If an error is encountered the first time we try to write the request * entity, we remember the original exception, and report that as the root * cause if we continue to encounter errors, rather than masking the * original error. * * @see org.apache.commons.httpclient.methods.RequestEntity#writeRequest(java.io.OutputStream) */ @Override public void writeTo(OutputStream output) throws IOException { try { if (!firstAttempt && isRepeatable()) content.reset(); firstAttempt = false; inputStreamRequestEntity.writeTo(output); } catch (IOException ioe) { if (originalException == null) originalException = ioe; throw originalException; } }
public static void toHttpResponse(InputStream stream, HttpResponse response, String contentType, long streamLength) throws IOException { InputStreamEntity body = new InputStreamEntity(stream, streamLength); body.setContentType(contentType); response.setEntity(body); response.setStatusCode(HttpStatus.SC_OK); }
private static HttpResponse transformResponse(Response response) { int code = response.code(); String message = response.message(); BasicHttpResponse httpResponse = new BasicHttpResponse(HTTP_1_1, code, message); ResponseBody body = response.body(); InputStreamEntity entity = new InputStreamEntity(body.byteStream(), body.contentLength()); httpResponse.setEntity(entity); Headers headers = response.headers(); for (int i = 0, size = headers.size(); i < size; i++) { String name = headers.name(i); String value = headers.value(i); httpResponse.addHeader(name, value); if ("Content-Type".equalsIgnoreCase(name)) { entity.setContentType(value); } else if ("Content-Encoding".equalsIgnoreCase(name)) { entity.setContentEncoding(value); } } return httpResponse; }
HttpPost post = new HttpPost(url + "/api/v1/datapoints"); FileInputStream zipStream = new FileInputStream(zipFile); post.setHeader("Content-Type", "application/gzip"); post.setEntity(new InputStreamEntity(zipStream, zipFile.length())); try (CloseableHttpResponse response = client.execute(post)) zipStream.close(); if (response.getStatusLine().getStatusCode() == 204)
HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost("http://localhost/upload"); File file = new File("/path/to/myfile"); FileInputStream fileInputStream = new FileInputStream(file); InputStreamEntity reqEntity = new InputStreamEntity(fileInputStream, file.length()); httppost.setEntity(reqEntity); reqEntity.setContentType("binary/octet-stream"); HttpResponse response = httpclient.execute(httppost); HttpEntity responseEntity = response.getEntity(); if (responseEntity != null) { responseEntity.consumeContent(); } httpclient.getConnectionManager().shutdown();
InputStreamEntity reqEntity = new InputStreamEntity( new FileInputStream(file), -1); reqEntity.setContentType("binary/octet-stream"); reqEntity.setChunked(true); httppost.setEntity(reqEntity);
entity = new InputStreamEntity(in, in.available()); } else if (data instanceof InputStream) { entity = new InputStreamEntity((InputStream) data, -1); } else if (data instanceof File) { FileInputStream fileInputStream; File file = (File) data; try { fileInputStream = new FileInputStream(file); } catch (FileNotFoundException e) { throw new RuntimeException("File " + file.getPath() + " not found", e); entity = new InputStreamEntity(fileInputStream, file.length()); } else if (data instanceof byte[]) { byte[] out = ((byte[]) data); entity = new InputStreamEntity(new ByteArrayInputStream( out), out.length); } else if (data instanceof ByteArrayOutputStream) { ByteArrayOutputStream out = ((ByteArrayOutputStream) data); entity = new InputStreamEntity(new ByteArrayInputStream( out.toByteArray()), out.size()); } else if (data instanceof Closure) { ByteArrayOutputStream out = new ByteArrayOutputStream(); entity = new InputStreamEntity(new ByteArrayInputStream( out.toByteArray()), out.size()); entity.setContentType(contentTypeToString(contentType)); return entity;
HttpPost post = new HttpPost( uriBuilder.build() ); post.setHeader( CONTENT_TYPE, CONTENT_TYPE_TEXT_XML ); if ( isDebug() ) { logDebug( BaseMessages.getString( PKG, "HTTPPOST.Log.HeaderValue", CONTENT_TYPE, CONTENT_TYPE_TEXT_XML ) ); post.setHeader( CONTENT_TYPE, CONTENT_TYPE_TEXT_XML + "; " + data.realEncoding ); if ( isDebug() ) { logDebug( BaseMessages.getString( PKG, "HTTPPOST.Log.HeaderValue", CONTENT_TYPE, CONTENT_TYPE_TEXT_XML post.setEntity( ( new StringEntity( bodyParams, ContentType.TEXT_XML.withCharset( "US-ASCII" ) ) ) ); fis = new FileInputStream( input ); post.setEntity( new InputStreamEntity( fis, input.length() ) ); } else { byte[] bytes;
/** * Add attachment to an existing test execution. * * @param testExecutionId Test execution id * @param file File to upload * @param mimeType Mime type * @param fileNameInRepo The name the attachment will have in the perf repo. * @return Id of the new attachment * @throws Exception */ public Long uploadAttachment(Long testExecutionId, File file, String mimeType, String fileNameInRepo) throws Exception { InputStreamEntity entity = new InputStreamEntity(new FileInputStream(file), file.length()); return uploadAttachment(testExecutionId, entity, mimeType, fileNameInRepo); }
post = new HttpPost(postAcceptorURL); String path = req.getContextPath(); if (path == null) { ServletUtils.copy(req, reqBuffer.asOutputStream()); reqBuffer.flip(); post.setEntity(new InputStreamEntity(reqBuffer.asInputStream(), reqContentLength)); post.addHeader("Content-Type", REQUEST_TYPE); post.addHeader("Tunnel-request", path); HttpResponse response = client.execute(post); int code = response.getStatusLine().getStatusCode(); log.debug("HTTP response code: {}", code); if (code == HttpStatus.SC_OK) { HttpEntity entity = response.getEntity(); if (entity != null) { resp.setContentType(REQUEST_TYPE);
public DCContentUploader upload() throws IOException { HttpClient client = HttpClients.createDefault(); HttpPost post = new HttpPost(url); post.setHeader("Content-Type", "application/octet-stream"); post.setEntity(new InputStreamEntity(content)); HttpResponse httpResponse = client.execute(post); status = httpResponse.getStatusLine().getStatusCode(); ByteArrayOutputStream os = new ByteArrayOutputStream(); StreamUtils.copy(httpResponse.getEntity().getContent(), os); response = os.toString("UTF-8"); headers = new HttpHeaders(); for(Header header : httpResponse.getAllHeaders()) { headers.add(header.getName(), header.getValue()); } post.releaseConnection(); return this; }
/** * 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(); } }
public static void addPackageToServlet( String urlString, InputStream is, String authentication ) throws Exception { HttpPost method = new HttpPost( urlString ); method.setEntity( new InputStreamEntity( is ) ); HttpClientContext context = HttpClientUtil.createPreemptiveBasicAuthentication( host, port, user, password ); method.addHeader( new BasicHeader( "Content-Type", "binary/zip" ) ); //adding authorization token if ( authentication != null ) { method.addHeader( new BasicHeader( "Authorization", authentication ) ); } //executing method HttpClient client = HttpClientManager.getInstance().createDefaultClient(); HttpResponse httpResponse = context != null ? client.execute( method, context ) : client.execute( method ); int code = httpResponse.getStatusLine().getStatusCode(); String response = HttpClientUtil.responseToString( httpResponse ); method.releaseConnection(); if ( code >= HttpStatus.SC_BAD_REQUEST ) { System.out.println( "Error occurred during export submission." ); } System.out.println( "Server response:" ); System.out.println( response ); }
+ "&f=" + fd.toUrlParam(); HttpPost method = new HttpPost(url); InputStreamEntity entity = new InputStreamEntity(is, -1); method.setEntity(entity); HttpClient client = new DefaultHttpClient(); try { HttpResponse coreResponse = client.execute(method); int statusCode = coreResponse.getStatusLine().getStatusCode(); if (statusCode == HttpStatus.SC_OK) { break; } else { log.debug("Unable to upload file to " + url + "\n" + coreResponse.getStatusLine()); selectedUrl = failAndGetNextUrl(context); if (selectedUrl == null) throw new FileStorageException(FileStorageException.Type.IO_EXCEPTION, fd.getName(), e); } finally { client.getConnectionManager().shutdown();
protected void _testAuthenticationHttpClient(Authenticator authenticator, boolean doPost) throws Exception { start(); try { SystemDefaultHttpClient httpClient = getHttpClient(); doHttpClientRequest(httpClient, new HttpGet(getBaseURL())); // Always do a GET before POST to trigger the SPNego negotiation if (doPost) { HttpPost post = new HttpPost(getBaseURL()); byte [] postBytes = POST.getBytes(); ByteArrayInputStream bis = new ByteArrayInputStream(postBytes); InputStreamEntity entity = new InputStreamEntity(bis, postBytes.length); // Important that the entity is not repeatable -- this means if // we have to renegotiate (e.g. b/c the cookie wasn't handled properly) // the test will fail. Assert.assertFalse(entity.isRepeatable()); post.setEntity(entity); doHttpClientRequest(httpClient, post); } } finally { stop(); } } }
public void mockConnection(String responseBody) throws Exception { HttpResponse response = mock(HttpResponse.class); this.httpClientMock = mock(HttpClient.class); InputStream is = new ByteArrayInputStream(responseBody.getBytes()); InputStreamEntity entity = new InputStreamEntity(is, responseBody.length()); StatusLine statusLine = new BasicStatusLine(new ProtocolVersion("HTTP", 1, 1), 200, "OK"); when(response.getStatusLine()).thenReturn(statusLine); when(response.getEntity()).thenReturn(entity); when(httpClientMock.execute(Mockito.any(HttpUriRequest.class))).thenReturn(response); } }
@Override public HttpResponse post(String uri, InputStream content) { InputStreamEntity e = new InputStreamEntity(content, -1); e.setContentType("application/json"); HttpPost post = new HttpPost(uri); post.setEntity(e); return executeRequest(post, true); }
HttpPost buildSendExportMethod( String type, String load, InputStream is ) throws UnsupportedEncodingException { String serviceUrl = RegisterPackageServlet.CONTEXT_PATH; if ( type != null && load != null ) { serviceUrl += "/?" + RegisterPackageServlet.PARAMETER_TYPE + "=" + type + "&" + RegisterPackageServlet.PARAMETER_LOAD + "=" + URLEncoder.encode( load, "UTF-8" ); } String urlString = constructUrl( serviceUrl ); if ( log.isDebug() ) { log.logDebug( BaseMessages.getString( PKG, "SlaveServer.DEBUG_ConnectingTo", urlString ) ); } HttpPost method = new HttpPost( urlString ); method.setEntity( new InputStreamEntity( is ) ); method.addHeader( new BasicHeader( "Content-Type", "binary/zip" ) ); return method; }