List of usage examples for org.apache.http.entity ByteArrayEntity ByteArrayEntity
public ByteArrayEntity(byte[] bArr)
From source file:com.subgraph.vega.internal.http.proxy.ProxyRequestHandler.java
private HttpEntity copyEntity(HttpEntity entity) { try {//w w w. j a v a2s .c om if (entity == null) { return null; } final ByteArrayEntity newEntity = new ByteArrayEntity(EntityUtils.toByteArray(entity)); newEntity.setContentEncoding(entity.getContentEncoding()); newEntity.setContentType(entity.getContentType()); return newEntity; } catch (IOException e) { return null; } }
From source file:CB_Core.GCVote.GCVote.java
public static Boolean SendVotes(String User, String password, int vote, String url, String waypoint) { String guid = url.substring(url.indexOf("guid=") + 5).trim(); String data = "userName=" + User + "&password=" + password + "&voteUser=" + String.valueOf(vote / 100.0) + "&cacheId=" + guid + "&waypoint=" + waypoint; try {//from w w w . jav a 2 s . com HttpPost httppost = new HttpPost("http://dosensuche.de/GCVote/setVote.php"); httppost.setEntity(new ByteArrayEntity(data.getBytes("UTF8"))); // Execute HTTP Post Request String responseString = Execute(httppost); return responseString.equals("OK\n"); } catch (Exception ex) { return false; } }
From source file:net.lamp.support.HttpManager.java
/** * ? URL ?? * //from ww w.j a v a 2 s. c om * @param url ?? * @param method "GET" or "POST" * @param params ?? * @param file ?????? SdCard ? * * @return ? * @throws WeiboException ? */ public static String openUrl(String url, String method, WeiboParameters params, String file) throws WeiboException { String result = ""; try { HttpClient client = getNewHttpClient(); HttpUriRequest request = null; ByteArrayOutputStream bos = null; client.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, NetStateManager.getAPN()); if (method.equals(HTTPMETHOD_GET)) { url = url + "?" + Utility.encodeUrl(params); HttpGet get = new HttpGet(url); request = get; } else if (method.equals(HTTPMETHOD_POST)) { HttpPost post = new HttpPost(url); request = post; byte[] data = null; String _contentType = params.getValue("content-type"); bos = new ByteArrayOutputStream(); if (!TextUtils.isEmpty(file)) { paramToUpload(bos, params); post.setHeader("Content-Type", MULTIPART_FORM_DATA + "; boundary=" + BOUNDARY); // ? // Utility.UploadImageUtils.revitionPostImageSize(file); imageContentToUpload(bos, file); } else { if (_contentType != null) { params.remove("content-type"); post.setHeader("Content-Type", _contentType); } else { post.setHeader("Content-Type", "application/x-www-form-urlencoded"); } String postParam = Utility.encodeParameters(params); data = postParam.getBytes("UTF-8"); bos.write(data); } data = bos.toByteArray(); bos.close(); ByteArrayEntity formEntity = new ByteArrayEntity(data); post.setEntity(formEntity); } else if (method.equals("DELETE")) { request = new HttpDelete(url); } HttpResponse response = client.execute(request); StatusLine status = response.getStatusLine(); int statusCode = status.getStatusCode(); if (statusCode != 200) { result = readHttpResponse(response); // throw new WeiboHttpException(result, statusCode); } result = readHttpResponse(response); return result; } catch (IOException e) { throw new WeiboException(e); } }
From source file:org.cloudsmith.stackhammer.api.client.StackHammerClient.java
private void assignJSONContent(HttpEntityEnclosingRequestBase request, Object params) { if (params != null) { request.addHeader(HttpHeaders.CONTENT_TYPE, CONTENT_TYPE_JSON + "; charset=" + UTF_8.name()); //$NON-NLS-1$ byte[] data = toJson(params).getBytes(UTF_8); request.setEntity(new ByteArrayEntity(data)); }/* w w w.j a v a2 s .c o m*/ }
From source file:com.supremainc.biostar2.sdk.volley.toolbox.HttpClientStack.java
/** * Creates the appropriate subclass of HttpUriRequest for passed in request. *///from w w w .j ava2s. c o m @SuppressWarnings("deprecation") /* protected */static HttpUriRequest createHttpRequest(Request<?> request, Map<String, String> additionalHeaders) throws AuthFailureError { switch (request.getMethod()) { case Method.DEPRECATED_GET_OR_POST: { // This is the deprecated way that needs to be handled for // backwards compatibility. // If the request's post body is null, then the assumption is // that the request is // GET. Otherwise, it is assumed that the request is a POST. byte[] postBody = request.getPostBody(); if (postBody != null) { HttpPost postRequest = new HttpPost(request.getUrl()); postRequest.addHeader(HEADER_CONTENT_TYPE, request.getPostBodyContentType()); HttpEntity entity; entity = new ByteArrayEntity(postBody); postRequest.setEntity(entity); return postRequest; } else { return new HttpGet(request.getUrl()); } } case Method.GET: return new HttpGet(request.getUrl()); case Method.DELETE: return new HttpDelete(request.getUrl()); case Method.POST: { HttpPost postRequest = new HttpPost(request.getUrl()); postRequest.addHeader(HEADER_CONTENT_TYPE, request.getBodyContentType()); setEntityIfNonEmptyBody(postRequest, request); return postRequest; } case Method.PUT: { HttpPut putRequest = new HttpPut(request.getUrl()); putRequest.addHeader(HEADER_CONTENT_TYPE, request.getBodyContentType()); setEntityIfNonEmptyBody(putRequest, request); return putRequest; } case Method.HEAD: return new HttpHead(request.getUrl()); case Method.OPTIONS: return new HttpOptions(request.getUrl()); case Method.TRACE: return new HttpTrace(request.getUrl()); case Method.PATCH: { HttpPatch patchRequest = new HttpPatch(request.getUrl()); patchRequest.addHeader(HEADER_CONTENT_TYPE, request.getBodyContentType()); setEntityIfNonEmptyBody(patchRequest, request); return patchRequest; } default: throw new IllegalStateException("Unknown request method."); } }
From source file:wsattacker.plugin.dos.dosExtension.requestSender.RequestSenderImpl.java
private HttpPost createHttpPostMethod(RequestObject requestObject) { Map<String, String> httpHeaderMap = requestObject.getHttpHeaderMap(); String strUrl = requestObject.getEndpoint(); String strXml = requestObject.getXmlMessage(); byte[] compressedXml = requestObject.getCompressedXML(); RequestSenderImpl.disableExtensiveLogging(); HttpPost post = null;//from w w w .j a v a 2s .c o m try { // Prepare HTTP post post = new HttpPost(strUrl); AbstractHttpEntity entity = null; // set Request content if (compressedXml != null) { entity = new ByteArrayEntity(compressedXml); } else { try { entity = new StringEntity(strXml, "text/xml; charset=UTF-8", null); } catch (UnsupportedEncodingException ex) { Logger.getLogger(RequestSenderImpl.class.getName()).log(Level.SEVERE, null, ex); } } // setRequestHeader (if already existent -> will be overwritten!) post.setHeader("Content-type", "text/xml; UTF-8;"); if (httpHeaderMap != null) { for (Map.Entry<String, String> entry : httpHeaderMap.entrySet()) { // Content-Length is automatically set by HTTPClient if (!entry.getKey().equalsIgnoreCase("Content-Length")) { post.setHeader(entry.getKey(), entry.getValue()); } } } post.setEntity(entity); // set for safety reason, just in case not set! // post.setHeader("Content-Length", // String.valueOf(strXml.length())); } catch (Exception e) { // TODO [CHAL 2014-01-03] Not really clear why we have to catch an // exception here, but without the catch we got an error by eclipse // that an exception will not been caught Logger.getLogger(RequestSenderImpl.class.getName()).log(Level.SEVERE, null, e); } return post; }
From source file:org.camunda.bpm.engine.rest.standalone.AbstractEmptyBodyFilterTest.java
@Test public void testBodyIsEmpty() throws IOException { evaluatePostRequest(new ByteArrayEntity("".getBytes("UTF-8")), ContentType.create(MediaType.APPLICATION_JSON).toString(), 200, true); }
From source file:org.dataconservancy.access.connector.AbstractHttpConnectorTest.java
@BeforeClass public static void setUp() throws Exception { XMLUnit.setIgnoreComments(true);/*from ww w . ja v a 2 s. c o m*/ XMLUnit.setIgnoreWhitespace(true); final BasicHttpProcessor httpProc = new BasicHttpProcessor(); testServer = new LocalTestServer(httpProc, null); testServer.register("/entity/*", new HttpRequestHandler() { @Override public void handle(HttpRequest request, HttpResponse response, HttpContext context) throws HttpException, IOException { final String requestURI = request.getRequestLine().getUri(); final String requestedEntity = requestURI.substring(requestURI.lastIndexOf("/") + 1); log.trace("processing request for entity {}", requestedEntity); final File requestedEntityFile = new File(entitiesDir, requestedEntity + ".xml"); if (!requestedEntityFile.exists()) { response.setStatusCode(HttpStatus.SC_NOT_FOUND); } else { response.setStatusCode(HttpStatus.SC_OK); response.setHeader("content-type", "application/xml"); response.setEntity(new InputStreamEntity(new FileInputStream(requestedEntityFile), -1)); } } }); testServer.register("/query/*", new HttpRequestHandler() { @Override public void handle(HttpRequest request, HttpResponse response, HttpContext context) throws HttpException, IOException { final String requestURI = request.getRequestLine().getUri(); final String query = requestURI.substring(requestURI.lastIndexOf("/") + 1); int max = -1; int offset = 0; //For some reason request.getParams wasn't working so parse the string String[] params = query.split("&"); for (String param : params) { String name = param.split("=")[0]; if (name.equalsIgnoreCase("max")) { max = Integer.parseInt(param.split("=")[1]); } else if (name.equalsIgnoreCase("offset")) { offset = Integer.parseInt(param.split("=")[1]); } } if (max == -1) { max = allTestEntities.size(); } log.trace( "processing request for query {} (note that the query itself is ignored and the response is hardcoded)", query); // basically we iterate over all the entities in the file system and return a DCP of Files. The actual query is ignored final Dcp dcp = new Dcp(); int count = 0; for (DcsEntity e : allTestEntities) { if (e instanceof DcsFile) { if (count >= offset) { dcp.addFile((DcsFile) e); } count++; if (count == max) { break; } } } count = dcp.getFiles().size(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); mb.buildSip(dcp, baos); response.setStatusCode(HttpStatus.SC_OK); response.setHeader("content-type", "application/xml"); response.setHeader("X-TOTAL-MATCHES", String.valueOf(count)); response.setEntity(new BufferedHttpEntity(new ByteArrayEntity(baos.toByteArray()))); } }); testServer.register("/deposit/file", new HttpRequestHandler() { @Override public void handle(HttpRequest request, HttpResponse response, HttpContext context) throws HttpException, IOException { log.trace("file upload"); response.setStatusCode(HttpStatus.SC_ACCEPTED); response.setHeader("content-type", "application/atom+xml;type=entry"); response.setHeader("Location", "http://dataconservancy.org/deposit/003210.atom"); response.setHeader("X-dcs-src", "http://dataconservancy.org/deposit/003210.file"); response.setEntity(new StringEntity("<?xml version='1.0'?>" + "<entry xmlns='http://www.w3.org/2005/Atom' xmlns:dc='http://dataconservancy.org/ns/'>" + "</entry>", "UTF-8")); } }); testServer.register("/deposit/sip", new HttpRequestHandler() { @Override public void handle(HttpRequest request, HttpResponse response, HttpContext context) throws HttpException, IOException { log.trace("sip upload"); response.setStatusCode(HttpStatus.SC_ACCEPTED); response.setHeader("content-type", "application/atom+xml;type=entry"); response.setHeader("Location", "http://dcservice.moo.org:8080/dcs/content/sipDeposit/4331419"); response.setEntity(new StringEntity("<?xml version='1.0'?>" + "<entry xmlns='http://www.w3.org/2005/Atom' xmlns:sword='http://purl.org/net/sword/'><id>deposit:/sipDeposit/4331419</id><content type='application/xml' src='http://dcservice.moo.org:8080/dcs/content/sipDeposit/4331419' /><title type='text'>Deposit 4331419</title><updated>2011-10-28T18:12:50.171Z</updated><author><name>Depositor</name></author><summary type='text'>ingesting</summary><link href='http://dcservice.moo.org:8080/dcs/status/sipDeposit/4331419' type='application/atom+xml; type=feed' rel='alternate' title='Processing Status' /><sword:treatment>Deposit processing</sword:treatment></entry>")); } }); testServer.start(); log.info("Test HTTP server listening on {}:{}", testServer.getServiceHostName(), testServer.getServicePort()); }
From source file:cn.edu.mju.Thriphoto.net.HttpManager.java
/** * ? URL ?// ww w . jav a 2s . c o m * * @param url ? * @param method "GET" or "POST" * @param params ? * @param file ????? SdCard ? * * @return ? * @throws com.sina.weibo.sdk.exception.WeiboException ? */ public static String openUrl(String url, String method, WeiboParameters params, String file) throws WeiboException { String result = ""; try { HttpClient client = getNewHttpClient(); HttpUriRequest request = null; ByteArrayOutputStream bos = null; client.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, NetStateManager.getAPN()); if (method.equals(HTTPMETHOD_GET)) { url = url + "?" + Utility.encodeUrl(params); HttpGet get = new HttpGet(url); request = get; } else if (method.equals(HTTPMETHOD_POST)) { HttpPost post = new HttpPost(url); request = post; byte[] data = null; String _contentType = params.getValue("content-type"); bos = new ByteArrayOutputStream(); if (!TextUtils.isEmpty(file)) { paramToUpload(bos, params); post.setHeader("Content-Type", MULTIPART_FORM_DATA + "; boundary=" + BOUNDARY); // ? // Utility.UploadImageUtils.revitionPostImageSize(file); imageContentToUpload(bos, file); } else { if (_contentType != null) { params.remove("content-type"); post.setHeader("Content-Type", _contentType); } else { post.setHeader("Content-Type", "application/x-www-form-urlencoded"); } String postParam = Utility.encodeParameters(params); data = postParam.getBytes("UTF-8"); bos.write(data); } data = bos.toByteArray(); bos.close(); ByteArrayEntity formEntity = new ByteArrayEntity(data); post.setEntity(formEntity); } else if (method.equals("DELETE")) { request = new HttpDelete(url); } HttpResponse response = client.execute(request); StatusLine status = response.getStatusLine(); int statusCode = status.getStatusCode(); if (statusCode != 200) { result = readHttpResponse(response); throw new WeiboHttpException(result, statusCode); } result = readHttpResponse(response); return result; } catch (IOException e) { throw new WeiboException(e); } }
From source file:com.overture.questdroid.utility.ExtHttpClientStack.java
/** * Creates the appropriate subclass of HttpUriRequest for passed in request. *//*from w w w. j a v a2s. c o m*/ @SuppressWarnings("deprecation") /* protected */static HttpUriRequest createHttpRequest(Request<?> request, Map<String, String> additionalHeaders) throws AuthFailureError { switch (request.getMethod()) { case Method.DEPRECATED_GET_OR_POST: { // This is the deprecated way that needs to be handled for backwards compatibility. // If the request's post body is null, then the assumption is that the request is // GET. Otherwise, it is assumed that the request is a POST. byte[] postBody = request.getPostBody(); if (postBody != null) { HttpPost postRequest = new HttpPost(request.getUrl()); postRequest.addHeader(HEADER_CONTENT_TYPE, request.getPostBodyContentType()); HttpEntity entity; entity = new ByteArrayEntity(postBody); postRequest.setEntity(entity); return postRequest; } else { return new HttpGet(request.getUrl()); } } case Method.GET: return new HttpGet(request.getUrl()); case Method.DELETE: return new HttpDelete(request.getUrl()); case Method.POST: { HttpPost postRequest = new HttpPost(request.getUrl()); postRequest.addHeader(HEADER_CONTENT_TYPE, request.getBodyContentType()); setEntityIfNonEmptyBody(postRequest, request); return postRequest; } case Method.PUT: { HttpPut putRequest = new HttpPut(request.getUrl()); putRequest.addHeader(HEADER_CONTENT_TYPE, request.getBodyContentType()); setEntityIfNonEmptyBody(putRequest, request); return putRequest; } default: throw new IllegalStateException("Unknown request method."); } }