List of usage examples for org.apache.http.entity ByteArrayEntity ByteArrayEntity
public ByteArrayEntity(byte[] bArr)
From source file:eu.itesla_project.histodb.client.impl.HistoDbHttpClientImpl.java
@Override public InputStream postHttpRequest(HistoDbUrl url, byte[] content) throws IOException { HttpPost httppost = new HttpPost(url.format()); httppost.setEntity(new ByteArrayEntity(content)); return cachedHttpRequest(httppost, url); }
From source file:com.github.wnameless.spring.bulkapi.test.BulkApiTest.java
@Test public void bulkRequestToWrongMapping() throws Exception { BulkRequest req = new BulkRequest(); BulkOperation op = new BulkOperation(); op.setUrl("/home2/BBB/ccc"); op.setMethod("PUT"); op.getHeaders().put("Authorization", "Basic " + Base64Utils.encodeToString("user:password".getBytes())); req.getOperations().add(op);//ww w. ja v a 2 s . co m HttpEntity entity = new ByteArrayEntity(mapper.writeValueAsString(req).getBytes("UTF-8")); post.setEntity(entity); HttpResponse response = client.execute(post); assertTrue(422 == response.getStatusLine().getStatusCode()); }
From source file:photosharing.api.conx.RecommendationDefinition.java
/** * like a file// w w w.j av a 2 s .co m * * Example URL * http://localhost:9080/photoSharing/api/like?r=on&lid=f8ad2a54- * 4d20-4b3b-ba3f-834e0b0cf90b&uid=bec24e93-8165-431d-bf38-0c668a5e6727 maps * to * https://apps.collabservdaily.swg.usma.ibm.com/files/basic/api/library/00c129c9-f3b6-4d22-9988-99e69d16d7a7/document/bf33a9b5-3042-46f0-a96e-b8742fced7a4/feed * * * @param bearer * @param pid * @param lid * @param nonce * @param response */ public void like(String bearer, String pid, String lid, String nonce, HttpServletResponse response) { String apiUrl = getApiUrl() + "/library/" + lid + "/document/" + pid + "/feed"; try { String recommendation = generateRecommendationContent(); logger.info("like -> " + apiUrl + " " + recommendation); // Generate the apiUrl for like Request post = Request.Post(apiUrl); post.addHeader("Authorization", "Bearer " + bearer); post.addHeader("X-Update-Nonce", nonce); post.addHeader("Content-Type", "application/atom+xml"); ByteArrayEntity entity = new ByteArrayEntity(recommendation.getBytes("UTF-8")); post.body(entity); Executor exec = ExecutorUtil.getExecutor(); Response apiResponse = exec.execute(post); HttpResponse hr = apiResponse.returnResponse(); /** * Check the status codes */ int code = hr.getStatusLine().getStatusCode(); logger.info("code " + code); // Session is no longer valid or access token is expired if (code == HttpStatus.SC_FORBIDDEN) { response.sendRedirect("./api/logout"); } // User is not authorized else if (code == HttpStatus.SC_UNAUTHORIZED) { response.setStatus(HttpStatus.SC_UNAUTHORIZED); } // Default to SC_NO_CONTENT (204) else { response.setStatus(HttpStatus.SC_NO_CONTENT); } } catch (IOException e) { response.setHeader("X-Application-Error", e.getClass().getName()); response.setStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR); logger.severe("IOException " + e.toString()); e.printStackTrace(); } }
From source file:org.wso2.dss.integration.test.jira.issues.DS937BoxcarringTestCase.java
public Object[] sendPOST(String endpoint, String content, Map<String, String> headers) throws IOException { HttpClient httpClient = new DefaultHttpClient(); httpClient.getParams().setParameter("http.socket.timeout", 120000); HttpPost httpPost = new HttpPost(endpoint); if (sessionID == null) { sessionID = "11"; }// w w w. jav a 2s . c om headers.put("Cookie", sessionID); for (String headerType : headers.keySet()) { httpPost.setHeader(headerType, headers.get(headerType)); } if (content != null) { HttpEntity httpEntity = new ByteArrayEntity(content.getBytes("UTF-8")); if (headers.get("Content-Type") == null) { httpPost.setHeader("Content-Type", "application/json"); } httpPost.setEntity(httpEntity); } HttpResponse httpResponse = httpClient.execute(httpPost); Header[] responseHeaders = httpResponse.getHeaders("Set-Cookie"); if (responseHeaders != null && responseHeaders.length > 0) { sessionID = responseHeaders[0].getValue(); } if (httpResponse.getEntity() != null) { BufferedReader reader = new BufferedReader( new InputStreamReader(httpResponse.getEntity().getContent())); String inputLine; StringBuilder response = new StringBuilder(); while ((inputLine = reader.readLine()) != null) { response.append(inputLine); } reader.close(); return new Object[] { httpResponse.getStatusLine().getStatusCode(), response.toString() }; } else { return new Object[] { httpResponse.getStatusLine().getStatusCode() }; } }
From source file:uk.co.markfrimston.tasktree.TaskTree.java
public void synchronise(MergeConfirmer mergeConfirmer) throws Exception { if (loadUrl == null) { throw new Exception("No load URL defined"); }/* w w w . j ava 2 s . com*/ if (saveUrl == null) { throw new Exception("No save URL defined"); } if (mergeCommand == null) { throw new Exception("No merge command defined"); } Long newTimestamp = new Date().getTime(); HttpClient client = new DefaultHttpClient(); DocumentBuilderFactory builderFact = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = builderFact.newDocumentBuilder(); // make load request HttpPost post = new HttpPost(loadUrl); HttpResponse response = client.execute(post); if (response.getStatusLine().getStatusCode() != 200) { throw new Exception("Unexpected load response from server: " + response.getStatusLine().getStatusCode() + " " + response.getStatusLine().getReasonPhrase()); } // get timestamp header Header[] tsHeaders = response.getHeaders("Timestamp"); Long timestamp; if (tsHeaders == null || tsHeaders.length < 1) { throw new Exception("Missing timestamp from server"); } try { timestamp = Long.parseLong(tsHeaders[0].getValue()); } catch (NumberFormatException e) { throw new Exception("Invalid timestamp from server \"" + tsHeaders[0].getValue() + "\""); } if (timestamp != 0 && timestamp < lastSyncTime) { throw new Exception("Remote timestamp earlier than local timestamp"); } // parse xml Document doc; try { doc = builder.parse(response.getEntity().getContent()); } catch (Exception e) { throw new Exception("Failed to parse load response from server"); } // if remote version is more up to date if (timestamp > lastSyncTime) { // if local changes made, merge if (unsynchedChanges) { // save local tree save(); // save remote tree to temp file makeFilePath(); FileOutputStream fileStream = new FileOutputStream(filePath + MERGE_FILENAME); writeDocToStream(doc, fileStream); fileStream.close(); // execute merge command to perform merge String commandString = StringUtils.template(mergeCommand, filePath + FILENAME, filePath + MERGE_FILENAME); Process proc = Runtime.getRuntime().exec(commandString); proc.waitFor(); proc.destroy(); if (!mergeConfirmer.confirmMerge()) { throw new Exception("Merge aborted"); } // remove temp file new File(filePath + MERGE_FILENAME).delete(); // load the newly merged local tree load(); } else { // just load xml from remote loadFromDocument(doc); // save to file save(); } } // save back to remote every time, to update remote with new sync timestamp. // write xml to byte array doc = saveToDocument(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); writeDocToStream(doc, baos); baos.close(); // make save request post = new HttpPost(saveUrl); post.addHeader("Timestamp", String.valueOf(newTimestamp)); ByteArrayEntity bare = new ByteArrayEntity(baos.toByteArray()); bare.setContentType("application/xml"); post.setEntity(bare); response = client.execute(post); if (response.getStatusLine().getStatusCode() != 200) { throw new Exception("Unexpected save response from server: " + response.getStatusLine().getStatusCode() + " " + response.getStatusLine().getReasonPhrase()); } // server should echo back same xml to confirm Document echoDoc; try { echoDoc = builder.parse(response.getEntity().getContent()); } catch (Exception e) { throw new Exception("Failed to parse save response from server"); } if (!nodesEqual(doc, echoDoc)) { throw new Exception("Bad save response from server"); } unsynchedChanges = false; lastSyncTime = newTimestamp; // save config saveConfig(); }
From source file:org.jsnap.request.HttpRequest.java
protected void write(byte[] packed) throws CommunicationException, SecurityException { // This function gets called only for the client's writes. Server's // writes are performed by the RequestHandler.doServiceImpl() method. HttpHost host = new HttpHost(this.host, this.port, getScheme()); HttpClientConnection connection = new DefaultHttpClientConnection(host); HttpPost post = new HttpPost(EXECUTE_REQUEST_URI); post.setEntity(new ByteArrayEntity(packed)); HttpRequestExecutor executor = new HttpRequestExecutor(); executor.addInterceptor(new RequestContent()); executor.addInterceptor(new RequestTargetHost()); // This is a very reliable timeout mechanism for the _client_. Recall that // server's timeout mechanism depends on the JDBC driver. if (timeout != 0) { int remaining = new Long((tryUntil + timeout) - System.currentTimeMillis()).intValue(); if (remaining < 0) remaining = 1; // immediately! HttpParams params = new DefaultHttpParams(); params.setIntParameter(HttpConnectionParams.SO_TIMEOUT, remaining); executor.setParams(params);//from w ww . ja va2 s .co m } try { response = executor.execute(post, connection); } catch (IOException e) { throw new CommunicationException(e); } catch (HttpException e) { throw new CommunicationException(e); } }
From source file:com.android.volley.toolbox.http.HttpClientStack.java
private static void setEntityIfNonEmptyBody(HttpEntityEnclosingRequestBase httpRequest, Request<?> request) throws IOException, AuthFailureError { if (request.containsFile()) { /* MultipartEntity multipartEntity = new MultipartEntity(); final Map<String, MultiPartParam> multipartParams = request.getMultiPartParams(); for (String key : multipartParams.keySet()) { multipartEntity.addPart(new StringPart(key, multipartParams.get(key).value)); }// w ww.j a va2 s .c o m final Map<String, File> filesToUpload = request.getFilesToUpload(); if(filesToUpload!=null){ for (String key : filesToUpload.keySet()) { File file = filesToUpload.get(key) ; if (file==null || !file.exists()) { throw new IOException(String.format("File not found: %s",file.getAbsolutePath())); } if (file.isDirectory()) { throw new IOException(String.format("File is a directory: %s", file.getAbsolutePath())); } multipartEntity.addPart(new FilePart(key, file, null, null)); } } httpRequest.setEntity(multipartEntity); */ MultipartEntity multipartEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); final Map<String, MultiPartParam> multipartParams = request.getMultiPartParams(); for (String key : multipartParams.keySet()) { multipartEntity.addPart(key, new StringBody(multipartParams.get(key).value, "text/plain", Charset.forName("UTF-8"))); } final Map<String, File> filesToUpload = request.getFilesToUpload(); if (filesToUpload != null) { for (String key : filesToUpload.keySet()) { File file = filesToUpload.get(key); if (file == null || !file.exists()) { throw new IOException(String.format("File not found: %s", file.getAbsolutePath())); } if (file.isDirectory()) { throw new IOException(String.format("File is a directory: %s", file.getAbsolutePath())); } multipartEntity.addPart(key, new FileBody(file)); } } httpRequest.setEntity(multipartEntity); } else { byte[] body = request.getBody(); if (body != null) { HttpEntity entity = new ByteArrayEntity(body); httpRequest.setEntity(entity); } } }
From source file:com.jaspersoft.ireport.jasperserver.ws.http.JSSCommonsHTTPSender.java
/** * invoke creates a socket connection, sends the request SOAP message and * then reads the response SOAP message back from the SOAP server * * @param msgContext/* www. j a v a 2 s . c o m*/ * the messsage context * * @throws AxisFault */ public void invoke(final MessageContext msgContext) throws AxisFault { if (log.isDebugEnabled()) log.debug(Messages.getMessage("enter00", "CommonsHTTPSender::invoke")); Request req = null; Response response = null; try { if (exec == null) { targetURL = new URL(msgContext.getStrProp(MessageContext.TRANS_URL)); String userID = msgContext.getUsername(); String passwd = msgContext.getPassword(); // if UserID is not part of the context, but is in the URL, use // the one in the URL. if ((userID == null) && (targetURL.getUserInfo() != null)) { String info = targetURL.getUserInfo(); int sep = info.indexOf(':'); if ((sep >= 0) && (sep + 1 < info.length())) { userID = info.substring(0, sep); passwd = info.substring(sep + 1); } else userID = info; } Credentials cred = new UsernamePasswordCredentials(userID, passwd); if (userID != null) { // if the username is in the form "user\domain" // then use NTCredentials instead. int domainIndex = userID.indexOf("\\"); if (domainIndex > 0) { String domain = userID.substring(0, domainIndex); if (userID.length() > domainIndex + 1) { String user = userID.substring(domainIndex + 1); cred = new NTCredentials(user, passwd, NetworkUtils.getLocalHostname(), domain); } } } HttpClient httpClient = HttpClientBuilder.create().setRedirectStrategy(new LaxRedirectStrategy() { public HttpUriRequest getRedirect(final HttpRequest request, final HttpResponse response, final HttpContext context) throws ProtocolException { URI uri = getLocationURI(request, response, context); String method = request.getRequestLine().getMethod(); if (method.equalsIgnoreCase(HttpHead.METHOD_NAME)) return new HttpHead(uri); else if (method.equalsIgnoreCase(HttpPost.METHOD_NAME)) { HttpPost httpPost = new HttpPost(uri); httpPost.addHeader(request.getFirstHeader("Authorization")); httpPost.addHeader(request.getFirstHeader("SOAPAction")); httpPost.addHeader(request.getFirstHeader("Content-Type")); httpPost.addHeader(request.getFirstHeader("User-Agent")); httpPost.addHeader(request.getFirstHeader("SOAPAction")); if (request instanceof HttpEntityEnclosingRequest) httpPost.setEntity(((HttpEntityEnclosingRequest) request).getEntity()); return httpPost; } else if (method.equalsIgnoreCase(HttpGet.METHOD_NAME)) { return new HttpGet(uri); } else { throw new IllegalStateException( "Redirect called on un-redirectable http method: " + method); } } }).build(); exec = Executor.newInstance(httpClient); HttpHost host = new HttpHost(targetURL.getHost(), targetURL.getPort(), targetURL.getProtocol()); exec.auth(host, cred); exec.authPreemptive(host); HttpUtils.setupProxy(exec, targetURL.toURI()); } boolean posting = true; // If we're SOAP 1.2, allow the web method to be set from the // MessageContext. if (msgContext.getSOAPConstants() == SOAPConstants.SOAP12_CONSTANTS) { String webMethod = msgContext.getStrProp(SOAP12Constants.PROP_WEBMETHOD); if (webMethod != null) posting = webMethod.equals(HTTPConstants.HEADER_POST); } HttpHost proxy = HttpUtils.getUnauthProxy(exec, targetURL.toURI()); if (posting) { req = Request.Post(targetURL.toString()); if (proxy != null) req.viaProxy(proxy); Message reqMessage = msgContext.getRequestMessage(); addContextInfo(req, msgContext, targetURL); Iterator<?> it = reqMessage.getAttachments(); if (it.hasNext()) { ByteArrayOutputStream bos = null; try { bos = new ByteArrayOutputStream(); reqMessage.writeTo(bos); req.body(new ByteArrayEntity(bos.toByteArray())); } finally { FileUtils.closeStream(bos); } } else req.body(new StringEntity(reqMessage.getSOAPPartAsString())); } else { req = Request.Get(targetURL.toString()); if (proxy != null) req.viaProxy(proxy); addContextInfo(req, msgContext, targetURL); } response = exec.execute(req); response.handleResponse(new ResponseHandler<String>() { public String handleResponse(final HttpResponse response) throws IOException { HttpEntity en = response.getEntity(); InputStream in = null; try { StatusLine statusLine = response.getStatusLine(); int returnCode = statusLine.getStatusCode(); String contentType = en.getContentType().getValue(); in = new BufferedHttpEntity(en).getContent(); // String str = IOUtils.toString(in); if (returnCode > 199 && returnCode < 300) { // SOAP return is OK - so fall through } else if (msgContext.getSOAPConstants() == SOAPConstants.SOAP12_CONSTANTS) { // For now, if we're SOAP 1.2, fall // through, since the range of // valid result codes is much greater } else if (contentType != null && !contentType.equals("text/html") && ((returnCode > 499) && (returnCode < 600))) { // SOAP Fault should be in here - so // fall through } else { String statusMessage = statusLine.getReasonPhrase(); AxisFault fault = new AxisFault("HTTP", "(" + returnCode + ")" + statusMessage, null, null); fault.setFaultDetailString( Messages.getMessage("return01", "" + returnCode, IOUtils.toString(in))); fault.addFaultDetail(Constants.QNAME_FAULTDETAIL_HTTPERRORCODE, Integer.toString(returnCode)); throw fault; } Header contentEncoding = response.getFirstHeader(HTTPConstants.HEADER_CONTENT_ENCODING); if (contentEncoding != null) { if (contentEncoding.getValue().equalsIgnoreCase(HTTPConstants.COMPRESSION_GZIP)) in = new GZIPInputStream(in); else { AxisFault fault = new AxisFault("HTTP", "unsupported content-encoding of '" + contentEncoding.getValue() + "' found", null, null); throw fault; } } // Transfer HTTP headers of HTTP message // to MIME headers of SOAP // message MimeHeaders mh = new MimeHeaders(); for (Header h : response.getAllHeaders()) mh.addHeader(h.getName(), h.getValue()); Message outMsg = new Message(in, false, mh); outMsg.setMessageType(Message.RESPONSE); msgContext.setResponseMessage(outMsg); if (log.isDebugEnabled()) { log.debug("\n" + Messages.getMessage("xmlRecd00")); log.debug("-----------------------------------------------"); log.debug(outMsg.getSOAPPartAsString()); } } finally { FileUtils.closeStream(in); } return ""; } }); } catch (Exception e) { e.printStackTrace(); log.debug(e); throw AxisFault.makeFault(e); } if (log.isDebugEnabled()) log.debug(Messages.getMessage("exit00", "CommonsHTTPSender::invoke")); }