List of usage examples for org.apache.http.entity InputStreamEntity setContentType
public void setContentType(Header header)
From source file:org.deegree.protocol.ows.http.OwsHttpClientImpl.java
@Override public OwsHttpResponse doPost(URL endPoint, String contentType, StreamBufferStore body, Map<String, String> headers) throws IOException { OwsHttpResponse response = null;// w ww . ja va 2 s. c om try { HttpPost httpPost = new HttpPost(endPoint.toURI()); DefaultHttpClient httpClient = getInitializedHttpClient(endPoint); LOG.debug("Performing POST request on " + endPoint); LOG.debug("post size: " + body.size()); InputStreamEntity entity = new InputStreamEntity(body.getInputStream(), (long) body.size()); entity.setContentType(contentType); httpPost.setEntity(entity); HttpResponse httpResponse = httpClient.execute(httpPost); response = new OwsHttpResponseImpl(httpResponse, httpClient.getConnectionManager(), endPoint.toString()); } catch (Throwable e) { String msg = "Error performing POST request on '" + endPoint + "': " + e.getMessage(); throw new IOException(msg); } return response; }
From source file:com.ibm.stocator.fs.swift.SwiftOutputStream.java
/** * Default constructor/*from w ww . jav a 2 s . c o m*/ * * @param account JOSS account object * @param url URL connection * @param contentType content type * @param metadata input metadata * @param connectionManager SwiftConnectionManager * @throws IOException if error */ public SwiftOutputStream(JossAccount account, URL url, final String contentType, Map<String, String> metadata, SwiftConnectionManager connectionManager) throws IOException { mUrl = url; totalWritten = 0; mAccount = account; client = connectionManager.createHttpConnection(); request = new HttpPut(mUrl.toString()); request.addHeader("X-Auth-Token", account.getAuthToken()); if (metadata != null && !metadata.isEmpty()) { for (Map.Entry<String, String> entry : metadata.entrySet()) { request.addHeader("X-Object-Meta-" + entry.getKey(), entry.getValue()); } } PipedOutputStream out = new PipedOutputStream(); final PipedInputStream in = new PipedInputStream(); out.connect(in); execService = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors()); mOutputStream = out; Callable<Void> task = new Callable<Void>() { @Override public Void call() throws Exception { InputStreamEntity entity = new InputStreamEntity(in, -1); entity.setChunked(true); entity.setContentType(contentType); request.setEntity(entity); LOG.debug("HTTP PUT request {}", mUrl.toString()); HttpResponse response = client.execute(request); int responseCode = response.getStatusLine().getStatusCode(); LOG.debug("HTTP PUT response {}. Response code {}", mUrl.toString(), responseCode); if (responseCode == 401) { // Unauthorized error mAccount.authenticate(); request.removeHeaders("X-Auth-Token"); request.addHeader("X-Auth-Token", mAccount.getAuthToken()); LOG.warn("Token recreated for {}. Retry request", mUrl.toString()); response = client.execute(request); responseCode = response.getStatusLine().getStatusCode(); } if (responseCode >= 400) { // Code may have changed from retrying throw new IOException("HTTP Error: " + responseCode + " Reason: " + response.getStatusLine().getReasonPhrase()); } return null; } }; futureTask = execService.submit(task); }
From source file:ru.phsystems.irisx.voice.httpPOST.java
/** * This file will post the flac file to google and store the Json String in jsonResponse data member *//*w w w. java2 s.c o m*/ private void postFLAC() { try { //long start = System.currentTimeMillis(); // Load the file stream from the given filename File file = new File(FLACFileName); InputStreamEntity reqEntity = new InputStreamEntity(new FileInputStream(file), -1); // Set the content type of the request entity to binary octet stream.. Taken from the chunked post example HTTPClient reqEntity.setContentType("binary/octet-stream"); //reqEntity.setChunked(true); // Uncomment this line, but I feel it slows stuff down... Quick Tests show no difference // set the POST request entity... httppost.setEntity(reqEntity); //System.out.println("executing request " + httppost.getRequestLine()); // Create an httpResponse object and execute the POST HttpResponse response = httpclient.execute(httppost); // Capture the Entity and get content HttpEntity resEntity = response.getEntity(); //System.out.println(System.currentTimeMillis()-start); String buffer; jsonResponse = ""; br = new BufferedReader(new InputStreamReader(resEntity.getContent())); while ((buffer = br.readLine()) != null) { jsonResponse += buffer; } //System.out.println("Content: "+jsonResponse); // Close Buffered Reader and content stream. EntityUtils.consume(resEntity); br.close(); } catch (Exception ee) { // In the event this POST Request FAILED //ee.printStackTrace(); jsonResponse = "_failed_"; } finally { // Finally shut down the client httpclient.getConnectionManager().shutdown(); } }
From source file:com.kolich.http.common.HttpClient4ClosureBase.java
public T post(final HttpPost post, final InputStream is, final long length, final String contentType, final HttpContext context) { if (is != null) { final InputStreamEntity entity = new InputStreamEntity(is, length); if (contentType != null) { entity.setContentType(contentType); }/*from w w w . j a v a 2 s. c o m*/ post.setEntity(entity); } return request(post, context); }
From source file:com.kolich.http.common.HttpClient4ClosureBase.java
public T put(final HttpPut put, final InputStream is, final long length, final String contentType, final HttpContext context) { if (is != null) { final InputStreamEntity entity = new InputStreamEntity(is, length); if (contentType != null) { entity.setContentType(contentType); }//from ww w . j a va 2 s .c o m put.setEntity(entity); } return request(put, context); }
From source file:org.graphity.core.util.jena.DatasetGraphAccessorHTTP.java
private HttpEntity graphToHttpEntity(final Graph graph) { ByteArrayOutputStream out = new ByteArrayOutputStream(); Model model = ModelFactory.createModelForGraph(graph); model.write(out, getSendLang().getName()); //model.write(out, WebContent.langNTriples) ; byte[] bytes = out.toByteArray(); ByteArrayInputStream in = new ByteArrayInputStream(out.toByteArray()); InputStreamEntity reqEntity = new InputStreamEntity(in, bytes.length); reqEntity.setContentType(getSendLang().getContentType().getContentType()); reqEntity.setContentEncoding("UTF-8"); HttpEntity entity = reqEntity;//from w w w .ja v a 2 s.c o m return entity; //((HttpEntityEnclosingRequestBase)httpRequest).setEntity(entity) ; /* ContentProducer producer = new ContentProducer() { @Override public void writeTo(OutputStream out) throws IOException { RDFDataMgr.write(out, graph, sendLang) ; } } ; EntityTemplate entity = new EntityTemplate(producer) ; String ct = sendLang.getLang().getContentType().getContentType() ; entity.setContentType(ct) ; return entity ; */ }
From source file:de.spqrinfo.cups4j.operations.IppOperation.java
/** * Sends a request to the provided url//from w w w. j av a 2 s . c o m * * @param url * @param ippBuf * * @param documentStream * @return result * @throws Exception */ private IppResult sendRequest(URL url, ByteBuffer ippBuf, InputStream documentStream) throws Exception { IppResult ippResult = null; if (ippBuf == null) { return null; } if (url == null) { return null; } HttpClient client = new DefaultHttpClient(); // will not work with older versions of CUPS! client.getParams().setParameter("http.protocol.version", HttpVersion.HTTP_1_1); client.getParams().setParameter("http.socket.timeout", new Integer(10000)); client.getParams().setParameter("http.connection.timeout", new Integer(10000)); client.getParams().setParameter("http.protocol.content-charset", "UTF-8"); client.getParams().setParameter("http.method.response.buffer.warnlimit", new Integer(8092)); // probabaly not working with older CUPS versions client.getParams().setParameter("http.protocol.expect-continue", Boolean.valueOf(true)); HttpPost httpPost = new HttpPost(new URI("http://" + url.getHost() + ":" + ippPort) + url.getPath()); httpPost.getParams().setParameter("http.socket.timeout", new Integer(10000)); byte[] bytes = new byte[ippBuf.limit()]; ippBuf.get(bytes); ByteArrayInputStream headerStream = new ByteArrayInputStream(bytes); // If we need to send a document, concatenate InputStreams InputStream inputStream = headerStream; if (documentStream != null) { inputStream = new SequenceInputStream(headerStream, documentStream); } // set length to -1 to advice the entity to read until EOF InputStreamEntity requestEntity = new InputStreamEntity(inputStream, -1); requestEntity.setContentType(IPP_MIME_TYPE); httpPost.setEntity(requestEntity); httpStatusLine = null; ResponseHandler<byte[]> handler = new ResponseHandler<byte[]>() { public byte[] handleResponse(HttpResponse response) throws ClientProtocolException, IOException { HttpEntity entity = response.getEntity(); httpStatusLine = response.getStatusLine().toString(); if (entity != null) { return EntityUtils.toByteArray(entity); } else { return null; } } }; byte[] result = client.execute(httpPost, handler); IppResponse ippResponse = new IppResponse(); ippResult = ippResponse.getResponse(ByteBuffer.wrap(result)); ippResult.setHttpStatusResponse(httpStatusLine); // IppResultPrinter.print(ippResult); client.getConnectionManager().shutdown(); return ippResult; }
From source file:com.nominanuda.web.http.ServletHelper.java
@SuppressWarnings("unchecked") private HttpEntity buildEntity(HttpServletRequest servletRequest, final InputStream is, long contentLength, String ct, String cenc) throws IOException { if (ServletFileUpload.isMultipartContent(servletRequest)) { FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); List<FileItem> items; try {/*from w ww .j av a 2s . c o m*/ items = upload.parseRequest(new HttpServletRequestWrapper(servletRequest) { public ServletInputStream getInputStream() throws IOException { return new ServletInputStream() { public int read() throws IOException { return is.read(); } public int read(byte[] arg0) throws IOException { return is.read(arg0); } public int read(byte[] b, int off, int len) throws IOException { return is.read(b, off, len); } //@Override @SuppressWarnings("unused") public boolean isFinished() { Check.illegalstate.fail(NOT_IMPLEMENTED); return false; } //@Override @SuppressWarnings("unused") public boolean isReady() { Check.illegalstate.fail(NOT_IMPLEMENTED); return false; } //@Override @SuppressWarnings("unused") public void setReadListener(ReadListener arg0) { Check.illegalstate.fail(NOT_IMPLEMENTED); } }; } }); } catch (FileUploadException e) { throw new IOException(e); } MultipartEntity multipartEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); for (FileItem i : items) { multipartEntity.addPart(i.getFieldName(), new InputStreamBody(i.getInputStream(), i.getName())); } return multipartEntity; } else { InputStreamEntity entity = new InputStreamEntity(is, contentLength); entity.setContentType(ct); if (cenc != null) { entity.setContentEncoding(cenc); } return entity; } }
From source file:com.hoccer.api.FileCache.java
public String store(StreamableContent data, int secondsUntilExipred) throws ClientProtocolException, IOException, Exception { String url = ClientConfig.getFileCacheBaseUri() + "/" + UUID.randomUUID() + "/?expires_in=" + secondsUntilExipred;/*from w w w.ja va2 s. co m*/ LOG.finest("put uri = " + url); HttpPut request = new HttpPut(sign(url)); InputStreamEntity entity = new InputStreamEntity(data.openNewInputStream(), data.getNewStreamLength()); request.addHeader("Content-Disposition", " attachment; filename=\"" + data.getFilename() + "\""); entity.setContentType(data.getContentType()); request.setEntity(entity); request.addHeader("Content-Type", data.getContentType()); HttpResponse response = getHttpClient().execute(request); String responseString = convertResponseToString(response, false); LOG.finest("response = " + responseString); return responseString; }
From source file:org.apache.jena.fuseki.http.DatasetGraphAccessorHTTP.java
private Graph exec(String targetStr, Graph graphToSend, HttpUriRequest httpRequest, boolean processBody) { HttpClient httpclient = new SystemDefaultHttpClient(httpParams); if (graphToSend != null) { // ??? httpRequest isa Post // Impedence mismatch - is there a better way? ByteArrayOutputStream out = new ByteArrayOutputStream(); Model model = ModelFactory.createModelForGraph(graphToSend); model.write(out, "RDF/XML"); byte[] bytes = out.toByteArray(); ByteArrayInputStream in = new ByteArrayInputStream(out.toByteArray()); InputStreamEntity reqEntity = new InputStreamEntity(in, bytes.length); reqEntity.setContentType(WebContent.contentTypeRDFXML); reqEntity.setContentEncoding(WebContent.charsetUTF8); HttpEntity entity = reqEntity;/*from w w w . ja va 2 s . co m*/ ((HttpEntityEnclosingRequestBase) httpRequest).setEntity(entity); } TypedInputStream ts = null; // httpclient.getParams().setXXX try { HttpResponse response = httpclient.execute(httpRequest); int responseCode = response.getStatusLine().getStatusCode(); String responseMessage = response.getStatusLine().getReasonPhrase(); if (HttpSC.isRedirection(responseCode)) // Not implemented yet. throw FusekiRequestException.create(responseCode, responseMessage); // Other 400 and 500 - errors if (HttpSC.isClientError(responseCode) || HttpSC.isServerError(responseCode)) throw FusekiRequestException.create(responseCode, responseMessage); if (responseCode == HttpSC.NO_CONTENT_204) return null; if (responseCode == HttpSC.CREATED_201) return null; if (responseCode != HttpSC.OK_200) { Log.warn(this, "Unexpected status code"); throw FusekiRequestException.create(responseCode, responseMessage); } // May not have a body. String ct = getHeader(response, HttpNames.hContentType); if (ct == null) { HttpEntity entity = response.getEntity(); if (entity != null) { InputStream instream = entity.getContent(); // Read to completion? instream.close(); } return null; } // Tidy. See ConNeg / MediaType. String x = getHeader(response, HttpNames.hContentType); String y[] = x.split(";"); String contentType = null; if (y[0] != null) contentType = y[0].trim(); String charset = null; if (y.length > 1 && y[1] != null) charset = y[1].trim(); // Get hold of the response entity HttpEntity entity = response.getEntity(); if (entity != null) { InputStream instream = entity.getContent(); // String mimeType = ConNeg.chooseContentType(request, rdfOffer, ConNeg.acceptRDFXML).getAcceptType() ; // String charset = ConNeg.chooseCharset(request, charsetOffer, ConNeg.charsetUTF8).getAcceptType() ; ts = new TypedInputStream(instream, contentType, charset, null); } Graph graph = GraphFactory.createGraphMem(); if (processBody) readGraph(graph, ts, null); if (ts != null) ts.close(); Graph graph2 = new UnmodifiableGraph(graph); return graph2; } catch (IOException ex) { httpRequest.abort(); return null; } }