@Override public HttpResponse post(URL urlObj, byte[] payload, String userName, String password, int timeout) { HttpClient client = new HttpClient(); PostMethod method = new PostMethod(urlObj.toString()); method.setRequestEntity(new ByteArrayRequestEntity(payload)); method.setRequestHeader("Content-type", "application/json"); client.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler()); client.getParams().setSoTimeout(1000 * timeout); client.getParams().setConnectionManagerTimeout(1000 * timeout); if (userName != null && password != null) { setBasicAuthorization(method, userName, password); } try { int response = client.executeMethod(method); return new HttpResponse(response, method.getResponseBody()); } catch (IOException e) { throw new RuntimeException("Failed to process post request URL: " + urlObj, e); } finally { method.releaseConnection(); } }
/** * Creates the request entity that makes up the POST message body. * * @param message message to be sent * @param charset character set used for the message * * @return request entity that makes up the POST message body * * @throws SOAPClientException thrown if the message could not be marshalled */ protected RequestEntity createRequestEntity(Envelope message, Charset charset) throws SOAPClientException { try { Marshaller marshaller = Configuration.getMarshallerFactory().getMarshaller(message); ByteArrayOutputStream arrayOut = new ByteArrayOutputStream(); OutputStreamWriter writer = new OutputStreamWriter(arrayOut, charset); if (log.isDebugEnabled()) { log.debug("Outbound SOAP message is:\n" + XMLHelper.prettyPrintXML(marshaller.marshall(message))); } XMLHelper.writeNode(marshaller.marshall(message), writer); return new ByteArrayRequestEntity(arrayOut.toByteArray(), "text/xml"); } catch (MarshallingException e) { throw new SOAPClientException("Unable to marshall SOAP envelope", e); } }
public HttpResponse post(final RequestContext rq, final String scope, final int version, final String entityCollectionName, final Object entityId, final String relationCollectionName, final Object relationshipEntityId, final byte[] body, String contentType) throws IOException { RestApiEndpoint endpoint = new RestApiEndpoint(rq.getNetworkId(), scope, version, entityCollectionName, entityId, relationCollectionName, relationshipEntityId, null); String url = endpoint.getUrl(); PostMethod req = new PostMethod(url.toString()); if (body != null) { if (contentType == null || contentType.isEmpty()) { contentType = "application/octet-stream"; } ByteArrayRequestEntity requestEntity = new ByteArrayRequestEntity(body, contentType); req.setRequestEntity(requestEntity); } return submitRequest(req, rq); }
/** * 处理Put请求 * @param url * @param headers * @param object * @param property * @return */ public static JSONObject doPut(String url, Map<String, String> headers,String jsonString) { HttpClient httpClient = new HttpClient(); PutMethod putMethod = new PutMethod(url); //设置header setHeaders(putMethod,headers); //设置put传递的json数据 if(jsonString!=null&&!"".equals(jsonString)){ putMethod.setRequestEntity(new ByteArrayRequestEntity(jsonString.getBytes())); } String responseStr = ""; try { httpClient.executeMethod(putMethod); responseStr = putMethod.getResponseBodyAsString(); } catch (Exception e) { log.error(e); responseStr="{status:0}"; } return JSONObject.parseObject(responseStr); }
@Override public void addPrinterHW(final PrinterHWList printerHWList) { final byte[] data = beanEncoder.encode(printerHWList); final URL url = getURL(PRTRestServiceConstants.PATH_AddPrinterHW); final PostMethod httpPost = new PostMethod(url.toString()); final RequestEntity entity = new ByteArrayRequestEntity(data, beanEncoder.getContentType()); httpPost.setRequestEntity(entity); int result = -1; try { result = executeHttpPost(httpPost); } catch (final Exception e) { throw new PrintConnectionEndpointException("Cannot POST to " + url, e); } if (result != 200) { throw new PrintConnectionEndpointException("Error " + result + " while posting on " + url); } }
@Override public ClientHttpResponse executeInternal(HttpHeaders headers, byte[] output) throws IOException { for (Map.Entry<String, List<String>> entry : headers.entrySet()) { String headerName = entry.getKey(); for (String headerValue : entry.getValue()) { httpMethod.addRequestHeader(headerName, headerValue); } } if (this.httpMethod instanceof EntityEnclosingMethod) { EntityEnclosingMethod entityEnclosingMethod = (EntityEnclosingMethod) this.httpMethod; RequestEntity requestEntity = new ByteArrayRequestEntity(output); entityEnclosingMethod.setRequestEntity(requestEntity); } this.httpClient.executeMethod(this.httpMethod); return new CommonsClientHttpResponse(this.httpMethod); }
public PutMethod getSendByteArrayMethod(byte[] content, String service) throws Exception { // Prepare HTTP put // String urlString = constructUrl(service); log.logDebug(toString(), Messages.getString("SlaveServer.DEBUG_ConnectingTo", urlString)); //$NON-NLS-1$ PutMethod putMethod = new PutMethod(urlString); // Request content will be retrieved directly from the input stream // RequestEntity entity = new ByteArrayRequestEntity(content); putMethod.setRequestEntity(entity); putMethod.setDoAuthentication(true); putMethod.addRequestHeader(new Header("Content-Type", "text/xml;charset=" + Const.XML_ENCODING)); return putMethod; }
public PostMethod getSendByteArrayMethod(byte[] content, String service) throws Exception { // Prepare HTTP put // String urlString = constructUrl(service); log.logDebug(BaseMessages.getString(PKG, "SlaveServer.DEBUG_ConnectingTo", urlString)); //$NON-NLS-1$ PostMethod postMethod = new PostMethod(urlString); // Request content will be retrieved directly from the input stream // RequestEntity entity = new ByteArrayRequestEntity(content); postMethod.setRequestEntity(entity); postMethod.setDoAuthentication(true); postMethod.addRequestHeader(new Header("Content-Type", "text/xml;charset=" + Const.XML_ENCODING)); return postMethod; }
public PostMethod getSendByteArrayMethod(byte[] content, String service) throws Exception { // Prepare HTTP put // String urlString = constructUrl(service); if(log.isDebug()) log.logDebug(BaseMessages.getString(PKG, "SlaveServer.DEBUG_ConnectingTo", urlString)); //$NON-NLS-1$ PostMethod postMethod = new PostMethod(urlString); // Request content will be retrieved directly from the input stream // RequestEntity entity = new ByteArrayRequestEntity(content); postMethod.setRequestEntity(entity); postMethod.setDoAuthentication(true); postMethod.addRequestHeader(new Header("Content-Type", "text/xml;charset=" + Const.XML_ENCODING)); return postMethod; }
@Override public void setRequestAuthentication(HttpMethod method, byte[] message) throws IOException { if (method instanceof PostMethod) { // encrypt body Pair<byte[], AlgorithmParameters> encrypted = encryptor.encrypt(KeyProvider.ALIAS_SOLR, null, message); setRequestAlgorithmParameters(method, encrypted.getSecond()); ((PostMethod) method).setRequestEntity(new ByteArrayRequestEntity(encrypted.getFirst(), "application/octet-stream")); } long requestTimestamp = System.currentTimeMillis(); // add MAC header byte[] mac = macUtils.generateMAC(KeyProvider.ALIAS_SOLR, new MACInput(message, requestTimestamp, getLocalIPAddress())); if (logger.isDebugEnabled()) { logger.debug("Setting MAC " + mac + " on HTTP request " + method.getPath()); logger.debug("Setting timestamp " + requestTimestamp + " on HTTP request " + method.getPath()); } if (overrideMAC) { mac[0] += (byte) 1; } setRequestMac(method, mac); if (overrideTimestamp) { requestTimestamp += 60000; } // prevent replays setRequestTimestamp(method, requestTimestamp); }
/** * Send a PUT 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 put(Cluster cluster, String path, Header[] headers, byte[] content) throws IOException { PutMethod method = new PutMethod(); try { method.setRequestEntity(new ByteArrayRequestEntity(content)); int code = execute(cluster, method, headers, path); headers = method.getResponseHeaders(); content = method.getResponseBody(); return new Response(code, headers, content); } finally { method.releaseConnection(); } }
/** * 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 { PostMethod method = new PostMethod(); try { method.setRequestEntity(new ByteArrayRequestEntity(content)); int code = execute(cluster, method, headers, path); headers = method.getResponseHeaders(); content = method.getResponseBody(); return new Response(code, headers, content); } finally { method.releaseConnection(); } }
private PostMethod executePost(String uri, byte[] body) throws IOException { HttpClient cli = new HttpClient(); final PostMethod post = new PostMethod(URI + ":" + source.port + uri); post.setRequestEntity(new ByteArrayRequestEntity(body)); cli.executeMethod(post); return post; }
protected static PostMethod httpPost(String path, String body) throws IOException { LOG.info("Connecting to {}", url + path); HttpClient httpClient = new HttpClient(); PostMethod postMethod = new PostMethod(url + path); postMethod.addRequestHeader("Origin", url); RequestEntity entity = new ByteArrayRequestEntity(body.getBytes("UTF-8")); postMethod.setRequestEntity(entity); httpClient.executeMethod(postMethod); LOG.info("{} - {}", postMethod.getStatusCode(), postMethod.getStatusText()); return postMethod; }
protected static PutMethod httpPut(String path, String body) throws IOException { LOG.info("Connecting to {}", url + path); HttpClient httpClient = new HttpClient(); PutMethod putMethod = new PutMethod(url + path); putMethod.addRequestHeader("Origin", url); RequestEntity entity = new ByteArrayRequestEntity(body.getBytes("UTF-8")); putMethod.setRequestEntity(entity); httpClient.executeMethod(putMethod); LOG.info("{} - {}", putMethod.getStatusCode(), putMethod.getStatusText()); return putMethod; }
/** * 处理Post请求 * @param url * @param params post请求参数 * @param jsonString post传递json数据 * @return * @throws HttpException * @throws IOException */ public static JSONObject doPost(String url,Map<String,String> headers,Map<String,String> params,String jsonString) { HttpClient client = new HttpClient(); //post请求 PostMethod postMethod = new PostMethod(url); //设置header setHeaders(postMethod,headers); //设置post请求参数 setParams(postMethod,params); //设置post传递的json数据 if(jsonString!=null&&!"".equals(jsonString)){ postMethod.setRequestEntity(new ByteArrayRequestEntity(jsonString.getBytes())); } String responseStr = ""; try { client.executeMethod(postMethod); responseStr = postMethod.getResponseBodyAsString(); } catch (Exception e) { log.error(e); e.printStackTrace(); responseStr="{status:0}"; } return JSONObject.parseObject(responseStr); }
protected LoginResponse sendLoginRequest(final LoginRequest loginRequest) throws LoginFailedPrintConnectionEndpointException { final byte[] data = beanEncoder.encode(loginRequest); final Map<String, String> params = new HashMap<>(); params.put(Context.CTX_SessionId, "0"); // no session final URL url = getURL(PRTRestServiceConstants.PATH_Login, params); final PostMethod httpPost = new PostMethod(url.toString()); final RequestEntity entity = new ByteArrayRequestEntity(data, beanEncoder.getContentType()); httpPost.setRequestEntity(entity); int result = -1; InputStream in = null; try { result = executeHttpPost(httpPost); in = httpPost.getResponseBodyAsStream(); if (result != 200) { final String errorMsg = in == null ? "code " + result : Util.toString(in); throw new PrintConnectionEndpointException("Error " + result + " while posting on " + url + ": " + errorMsg); } final LoginResponse loginResponse = beanEncoder.decodeStream(in, LoginResponse.class); return loginResponse; } catch (final Exception e) { throw e instanceof LoginFailedPrintConnectionEndpointException ? (LoginFailedPrintConnectionEndpointException)e : new LoginFailedPrintConnectionEndpointException("Cannot POST to " + url, e); } finally { Util.close(in); in = null; } }
private <T> T executePost(final String path, final Map<String, String> params, final Object request, final Class<T> responseClass) { final URL url = getURL(path, params); final PostMethod httpPost = new PostMethod(url.toString()); final byte[] data = beanEncoder.encode(request); final RequestEntity entity = new ByteArrayRequestEntity(data, beanEncoder.getContentType()); httpPost.setRequestEntity(entity); int result = -1; InputStream in = null; try { result = executeHttpPost(httpPost); in = httpPost.getResponseBodyAsStream(); if (result != 200) { final String errorMsg = in == null ? "code " + result : StreamUtils.toString(in); throw new AdempiereException("Error " + result + " while posting on " + url + ": " + errorMsg); } if (responseClass != null) { final T response = beanEncoder.decodeStream(in, responseClass); return response; } } catch (final Exception e) { throw new AdempiereException(e); } finally { StreamUtils.close(in); in = null; } return null; }
protected static PutMethod httpPut(String path, String body, String user, String pwd) throws IOException { LOG.info("Connecting to {}", url + path); HttpClient httpClient = new HttpClient(); PutMethod putMethod = new PutMethod(url + path); putMethod.addRequestHeader("Origin", url); RequestEntity entity = new ByteArrayRequestEntity(body.getBytes("UTF-8")); putMethod.setRequestEntity(entity); if (userAndPasswordAreNotBlank(user, pwd)) { putMethod.setRequestHeader("Cookie", "JSESSIONID="+ getCookie(user, pwd)); } httpClient.executeMethod(putMethod); LOG.info("{} - {}", putMethod.getStatusCode(), putMethod.getStatusText()); return putMethod; }
/** * Main method for sending a TclRega script and parsing the XML result. */ @SuppressWarnings("unchecked") private synchronized <T> T sendScript(String script, Class<T> clazz) throws HomematicClientException { PostMethod post = null; try { script = StringUtils.trim(script); if (StringUtils.isEmpty(script)) { throw new RuntimeException("Homematic TclRegaScript is empty!"); } if (TRACE_ENABLED) { logger.trace("TclRegaScript: {}", script); } post = new PostMethod(context.getConfig().getTclRegaUrl()); RequestEntity re = new ByteArrayRequestEntity(script.getBytes("ISO-8859-1")); post.setRequestEntity(re); httpClient.executeMethod(post); String result = post.getResponseBodyAsString(); result = StringUtils.substringBeforeLast(result, "<xml><exec>"); if (TRACE_ENABLED) { logger.trace("Result TclRegaScript: {}", result); } Unmarshaller um = JAXBContext.newInstance(clazz).createUnmarshaller(); um.setListener(new CommonUnmarshallerListener()); return (T) um.unmarshal(new StringReader(result)); } catch (Exception ex) { throw new HomematicClientException(ex.getMessage(), ex); } finally { if (post != null) { post.releaseConnection(); } } }
public void sendLogs(String url, byte[] msg, String sumoName, String sumoCategory){ PostMethod post = null; if (StringUtils.isBlank(url)) { LOG.warning("Trying to send logs with blank url. Update config first!"); return; } try { post = new PostMethod(url); post.addRequestHeader("X-Sumo-Host", getHost()); if (StringUtils.isNotBlank(sumoName)) { post.addRequestHeader("X-Sumo-Name", sumoName); } if (StringUtils.isNotBlank(sumoCategory)) { post.addRequestHeader("X-Sumo-Category", sumoCategory); } post.addRequestHeader("Content-Encoding", "gzip"); byte[] compressedData = compress(msg); post.setRequestEntity(new ByteArrayRequestEntity(compressedData)); httpClient.executeMethod(post); int statusCode = post.getStatusCode(); if (statusCode != 200) { LOG.warning(String.format("Received HTTP error from Sumo Service: %d", statusCode)); } } catch (IOException e) { LOG.warning(String.format("Could not send log to Sumo Logic: %s", e.toString())); } finally { if (post != null) { post.releaseConnection(); } } }
/** * Test * * @throws Exception * Any exception */ @Test public void createBinaryRequestContentWithDataTest() throws Exception { HTTPRequest httpRequest=new HTTPRequest(); byte[] data=IOHelper.convertStringToBinary("TEST_DATA",null); httpRequest.setContent(data); RequestEntity output=this.client.createBinaryRequestContent(httpRequest); Assert.assertNotNull(output); Assert.assertEquals(ByteArrayRequestEntity.class,output.getClass()); Assert.assertArrayEquals(data,((ByteArrayRequestEntity)output).getContent()); }
/** * Test * * @throws Exception * Any exception */ @Test public void setRequestContentBinaryDataTest() throws Exception { HTTPRequest httpRequest=new HTTPRequest(); byte[] data=IOHelper.convertStringToBinary("TEST_DATA",null); httpRequest.setContent(data); PostMethod method=(PostMethod)this.client.createMethod("http://fax4j.org",HTTPMethod.POST); this.client.setRequestContent(httpRequest,method); RequestEntity output=method.getRequestEntity(); Assert.assertNotNull(output); Assert.assertEquals(ByteArrayRequestEntity.class,output.getClass()); Assert.assertArrayEquals(data,((ByteArrayRequestEntity)output).getContent()); }
private static RequestEntity toRequestEntity(Object value) throws PageException { if(value instanceof RequestEntity) return (RequestEntity) value; else if(value instanceof InputStream) { return new InputStreamRequestEntity((InputStream)value,"application/octet-stream"); } else if(Decision.isCastableToBinary(value,false)){ return new ByteArrayRequestEntity(Caster.toBinary(value)); } else { return new StringRequestEntity(Caster.toString(value)); } }
private void recordEntity(HttpMethod httpMethod, Trace trace) { if (httpMethod instanceof EntityEnclosingMethod) { final EntityEnclosingMethod entityEnclosingMethod = (EntityEnclosingMethod)httpMethod; final RequestEntity entity = entityEnclosingMethod.getRequestEntity(); if (entity != null && entity.isRepeatable() && entity.getContentLength() > 0) { if (entitySampler.isSampling()) { try { String entityValue; String charSet = entityEnclosingMethod.getRequestCharSet(); if (charSet == null || charSet.isEmpty()) { charSet = HttpConstants.DEFAULT_CONTENT_CHARSET; } if (entity instanceof ByteArrayRequestEntity) { entityValue = readByteArray((ByteArrayRequestEntity)entity, charSet); } else if (entity instanceof StringRequestEntity) { entityValue = readString((StringRequestEntity)entity); } else { entityValue = entity.getClass() + " (ContentType:" + entity.getContentType() + ")"; } trace.recordAttribute(AnnotationKey.HTTP_PARAM_ENTITY, entityValue); } catch (Exception e) { logger.debug("HttpEntityEnclosingRequest entity record fail. Caused:{}", e.getMessage(), e); } } } } }
private String readByteArray(ByteArrayRequestEntity entity, String charSet) throws UnsupportedEncodingException { if (entity.getContent() == null) { return ""; } final int length = entity.getContent().length > MAX_READ_SIZE ? MAX_READ_SIZE : entity.getContent().length; if (length <= 0) { return ""; } return new String(entity.getContent(), 0, length, charSet); }
public String getSpokenText(byte[] buffer) { // pass the byte array out to Wit.AI PostMethod post = new PostMethod("https://api.wit.ai/speech"); post.setRequestHeader("Authorization", "Bearer " + API_KEY); post.setRequestHeader("Content-Type", "audio/raw;encoding=signed-integer;bits=16;rate=8000;endian=little"); post.setRequestHeader("Content-Length", ""+WIT_BUFFER_SIZE); post.setRequestEntity(new ByteArrayRequestEntity(buffer)); String messageID = null; try { int resultCode = this.client.executeMethod(post); Log.d("SPACEOUT", "POST response code: " + resultCode); byte[] responseBody = post.getResponseBody(); post.releaseConnection(); if (responseBody == null) { Log.d("SPACEOUT", "no POST response received from Wit.AI"); // TODO -- show error on android GUI return null; } String response = new String(responseBody); Log.d("SPACEOUT", "response was: " + response); // parse the JSON response try { JSONObject result = new JSONObject(response); return result.getString("msg_body"); } catch (JSONException jsEx) { Log.e("SPACEOUT", "Failed to parse POST result from Wit.AI!"); Log.e("SPACEOUT", jsEx.getMessage()); } } catch (IOException ex) { // TODO -- show error on android GUI Log.e("SPACEOUT", "Failed to connect to Wit.AI!"); Log.e("SPACEOUT", ex.getMessage()); } return null; }