List of usage examples for org.apache.http.entity ByteArrayEntity ByteArrayEntity
public ByteArrayEntity(byte[] bArr)
From source file:com.opower.rest.client.generator.executors.ApacheHttpClient4Executor.java
public void loadHttpMethod(final ClientRequest request, HttpRequestBase httpMethod) throws Exception { if (httpMethod instanceof HttpGet && request.followRedirects()) { HttpClientParams.setRedirecting(httpMethod.getParams(), true); } else {//from w w w .ja v a 2 s . c om HttpClientParams.setRedirecting(httpMethod.getParams(), false); } if (request.getBody() != null && !request.getFormParameters().isEmpty()) throw new RuntimeException("You cannot send both form parameters and an entity body"); if (!request.getFormParameters().isEmpty()) { commitHeaders(request, httpMethod); HttpPost post = (HttpPost) httpMethod; List<NameValuePair> formparams = new ArrayList<NameValuePair>(); for (Map.Entry<String, List<String>> formParam : request.getFormParameters().entrySet()) { List<String> values = formParam.getValue(); for (String value : values) { formparams.add(new BasicNameValuePair(formParam.getKey(), value)); } } UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams, "UTF-8"); post.setEntity(entity); } else if (request.getBody() != null) { if (httpMethod instanceof HttpGet) throw new RuntimeException("A GET request cannot have a body."); ByteArrayOutputStream baos = new ByteArrayOutputStream(); try { request.writeRequestBody(request.getHeadersAsObjects(), baos); ByteArrayEntity entity = new ByteArrayEntity(baos.toByteArray()) { @Override public Header getContentType() { return new BasicHeader("Content-Type", request.getBodyContentType().toString()); } }; HttpPost post = (HttpPost) httpMethod; commitHeaders(request, httpMethod); post.setEntity(entity); } catch (IOException e) { throw new RuntimeException(e); } } else // no body { commitHeaders(request, httpMethod); } }
From source file:org.wso2.carbon.cloud.back.channel.BackChannelAuthenticator.java
private String jwtAuthentcate(String jwtToken) throws IOException { String jwtAuthenticatorEP = configReader.getProperty(BackChannelAuthConstants.JWT_AUTHENTICATOR_EP); //initialize http client HttpClient httpClient = Util.getHttpClient(jwtAuthenticatorEP); HttpPost httpPost = new HttpPost(jwtAuthenticatorEP); //set headers String authValue = "Bearer " + jwtToken; httpPost.setHeader(BackChannelAuthConstants.CONTENT_TYPE_HEADER, BackChannelAuthConstants.TEXT_XML); httpPost.setHeader(BackChannelAuthConstants.SOAP_ACTION_HEADER, "rn:getUserInfo"); httpPost.setHeader(BackChannelAuthConstants.AUTHORIZATION_HEADER, authValue); //set payload String payload = "<Envelope xmlns=\"http://schemas.xmlsoap.org/soap/envelope/\"><Body/></Envelope>"; HttpEntity entity = new ByteArrayEntity(payload.getBytes("UTF-8")); httpPost.setEntity(entity);// w w w . j av a 2 s. c o m //execute HttpResponse response = httpClient.execute(httpPost); HttpEntity responseEntity = response.getEntity(); Header[] headers = response.getHeaders(BackChannelAuthConstants.SET_COOKIE_HEADER); String jsessionCookie = (headers[0].getValue()).split(";")[0]; return jsessionCookie; }
From source file:de.micromata.genome.tpsb.soapui.DelegateToSoapUiTestBuilderHttpClientRequestTransport.java
private HttpResponse execute(SubmitContext submitContext, ExtendedHttpMethod method, HttpContext httpContext, Map<String, String> httpRequestParameter) throws Exception { boolean passtoremote = false; if (passtoremote == true) { return HttpClientSupport.execute(method, httpContext); }//ww w. j a va 2 s . com byte[] reqData = null; if (method.getRequestEntity() != null && method.getRequestEntity().getContent() != null) { reqData = filterRequestData(IOUtils.toByteArray(method.getRequestEntity().getContent())); } Header[] soaphaedera = method.getHeaders("SOAPAction"); String soapAction = ""; if (soaphaedera != null && soaphaedera.length > 0) { soapAction = method.getHeaders("SOAPAction")[0].getValue(); } String uri = method.getURI().toString(); // testBuilder.initWithUri(uri); testBuilder// .createNewPostRequestIntern(submitContext) // .initWithUri(uri).setRequestMethod(method.getMethod()).setRequestData(reqData); if (StringUtils.isNotBlank(soapAction) == true) { testBuilder.addRequestHeader("SOAPAction", soapAction); } Header[] allHeaders = method.getAllHeaders(); for (Header h : allHeaders) { testBuilder.addRequestHeader(h.getName(), h.getValue()); } httpRequestParameter.forEach((k, v) -> testBuilder.getHttpRequest().addRequestParameter(k, v)); MockHttpServletResponse httpr = testBuilder.executeServletRequest() // .getHttpResponse(); byte[] respData = filterResponseData(httpr.getOutputBytes()); // String outp = httpr.getOutputString(); BasicStatusLine statusLine = new BasicStatusLine(new ProtocolVersion("http", 1, 1), httpr.getStatus(), null); BasicHttpResponse httpResponse = new BasicHttpResponse(statusLine); httpResponse.setEntity(new ByteArrayEntity(respData)); httpResponse = filterBasicHttpResponse(httpResponse); // WsdlSinglePartHttpResponse wsdls = new WsdlSinglePartHttpResponse(); method.setHttpResponse(httpResponse); try { method.setURI(new URI("http://localhost/dummy")); } catch (URISyntaxException ex) { throw new RuntimeException(ex); } return httpResponse; }
From source file:com.github.wnameless.spring.bulkapi.test.BulkApiTest.java
@Test public void testInvalidUrl() throws Exception { BulkRequest req = operationTimes(1); BulkOperation op = new BulkOperation(); op.setMethod("GET"); op.setUrl("http://0:0:0:0:0:0:0:1%0:8080/home"); op.getHeaders().put("Authorization", authHeader); req.getOperations().add(op);//from w w w . ja v a 2 s . c om 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:tr.com.turkcellteknoloji.turkcellupdater.RestRequest.java
/** * Subclasses may override this method to place different object types to request body * @return contents of request./*from w w w. j a v a 2s . c om*/ * @throws JsonConversionException * @throws JSONException */ protected HttpEntity getRequestContents() throws Exception { try { final JSONObject jsonObject; if (inputJsonObject == null) { jsonObject = new JSONObject(); } else { jsonObject = inputJsonObject; } final String string = jsonObject.toString(); final byte[] bytes; bytes = string.getBytes("UTF-8"); final ByteArrayEntity result = new ByteArrayEntity(bytes); result.setContentType("application/json; charset=UTF-8"); return result; } catch (Exception e) { throw new Exception("Couldn't create request contents", e); } }
From source file:com.zrlh.llkc.funciton.Http_Utility.java
/** * Implement a weibo http request and return results . * // w w w.java 2 s . c o m * @param context * context of activity * @param url * @param method * (GET|POST) * @param bm * @return * @throws Exception */ public static String openUrl(Context context, String url, String method, Bitmap bm) throws Exception { String result = ""; try { HttpClient client = getNewHttpClient(context); HttpUriRequest request = null; ByteArrayOutputStream bos = null; if (method.equals("GET")) { } else if (method.equals("POST")) { HttpPost post = new HttpPost(url); byte[] data = null; bos = new ByteArrayOutputStream(1024 * 50); post.setHeader("Content-Type", MULTIPART_FORM_DATA + "; boundary=" + BOUNDARY); Http_Utility.imageContentToUpload(bos, bm); data = bos.toByteArray(); bos.close(); ByteArrayEntity formEntity = new ByteArrayEntity(data); post.setEntity(formEntity); request = post; } 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 = read(response); throw new Exception(); } // parse content stream from response result = read(response); return result; } catch (IOException e) { } return ""; }
From source file:com.linkedin.multitenant.db.ProxyDatabase.java
@Override public DatabaseResult doInsert(Query q) { HttpPut put = new HttpPut(m_connStr + q.getKey()); ByteArrayEntity bae = new ByteArrayEntity(q.getValue()); bae.setContentType("octet-stream"); put.setEntity(bae);//from w ww.j a va 2s.c o m try { @SuppressWarnings("unused") String responseBody = m_client.execute(put, m_handler); return DatabaseResult.OK; } catch (Exception e) { m_log.error("Error in executing doInsert", e); return DatabaseResult.FAIL; } }
From source file:eu.comvantage.dataintegration.SparulSimulationServlet.java
private void simulateEvent(String eventID, String endpoint) { //container for the final SPARUL update command including header information String body = ""; //additional body information for the SPARUL update command //try to encode the SPARUL update command string with UTF-8 String temp = ""; Gson gson = new Gson(); //simulation of a correct request if (eventID.equalsIgnoreCase("sparul1")) { temp = "{ " + "\"Template\" : 1, " + "\"Client\" : 1, " + "\"Params\" : [{\"name\":\"ticket\", \"value\":\"ex:Ticket0070071239swd\"}, " + "{\"name\":\"person\", \"value\":\"ex:nn00110011\"}]" + "}"; }//from www .ja va 2 s .c om //simulation of invalid template id for client else if (eventID.equalsIgnoreCase("sparul2")) { temp = "{ " + "\"Template\" : 8, " + "\"Client\" : 1, " + "\"Params\" : [{\"name\":\"ticket\", \"value\":\"ex:Ticket008008123swd\"}, " + "{\"name\":\"person\", \"value\":\"ex:nn1234567\"}]" + "}"; } //simulation of invalid client id else if (eventID.equalsIgnoreCase("sparul3")) { temp = "{ " + "\"Template\" : 1, " + "\"Client\" : 3, " + "\"Params\" : [{\"name\":\"ticket\", \"value\":\"ex:Ticket000000000swd\"}, " + "{\"name\":\"person\", \"value\":\"ex:nn55555\"}]" + "}"; } //simulation of invalid parameter for specified template else if (eventID.equalsIgnoreCase("sparul4")) { temp = "{ " + "\"Template\" : 1, " + "\"Client\" : 1, " + "\"Params\" : [{\"name\":\"bla\", \"value\":\"ex:Ticket98761234swd\"}, " + "{\"name\":\"person\", \"value\":\"ex:nn223344\"}]" + "}"; } //simulation of invalid parameter for specified template else if (eventID.equalsIgnoreCase("sparul5")) { temp = "{ " + "\"Templates\" : 1, " + "\"Clients\" : 1, " + "\"Param\" : [{\"name\":\"bla\", \"value\":\"ex:Ticket98761234swd\"}, " + "{\"name\":\"person\", \"value\":\"ex:nn223344\"}]" + "}"; } //malformed json else if (eventID.equalsIgnoreCase("sparul6")) { temp = "blabla"; } //simulation of a correct request else if (eventID.equalsIgnoreCase("sparul7")) { temp = "{ " + "\"Template\" : 1, " + "\"Client\" : 1, " + "\"Params\" : [{\"name\":\"templateId\", \"value\":\"tee:Ticket0070071239swd\"}], " + "}"; //test of the long statement parameters of file client1_test0 } else if (eventID.equalsIgnoreCase("sparul8")) { temp = "{ " + "\"Template\" : 1, " + "\"Client\" : 1, " + "\"Params\" : [{\"name\":\"templateId\", \"value\":\"tee:test1\"}, " + "{\"name\":\"reportId\", \"value\":\"1\"}," + "{\"name\":\"device1\", \"value\":\"tee:test2\"}," + "{\"name\":\"device2\", \"value\":\"tee:test3\"}," + "{\"name\":\"device3\", \"value\":\"tee:test4\"}]" + "}"; } //body = gson.toJson(temp); body = temp; //try to execute the SPARUL update command try { //insertion is done by a manual HTTP post HttpPost httpPost = new HttpPost(endpoint); //put SPARUL update command to output stream ByteArrayOutputStream b_out = new ByteArrayOutputStream(); OutputStreamWriter wr = new OutputStreamWriter(b_out); wr.write(body); wr.flush(); //transform output stream and modify header information for HTTP post byte[] bytes = b_out.toByteArray(); AbstractHttpEntity reqEntity = new ByteArrayEntity(bytes); reqEntity.setContentType("application/x-www-form-urlencoded"); reqEntity.setContentEncoding(HTTP.UTF_8); httpPost.setEntity(reqEntity); httpPost.setHeader("role", "http://www.comvantage.eu/ontologies/ac-schema/cv_wp6_comau_employee"); HttpClient httpclient = new DefaultHttpClient(); // //set proxy if defined // if(System.getProperty("http.proxyHost") != null) { // HttpHost proxy = new HttpHost(System.getProperty("http.proxyHost"), Integer.valueOf(System.getProperty("http.proxyPort")), "http"); // httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy); // } try { //execute the HTTP put System.out.println( "SparulSimulationServlet: Event '" + eventID + "' simulated at endpoint " + endpoint); HttpResponse response = httpclient.execute(httpPost); //handle different server responses and failures int responseCode = response.getStatusLine().getStatusCode(); String responseMessage = response.getStatusLine().getReasonPhrase(); System.out.println("SparulSimulationServlet: Response = " + responseCode + ", " + responseMessage); //close the output stream wr.close(); } catch (IOException ex) { throw new Exception(ex); } } catch (Exception e) { e.printStackTrace(); } }
From source file:com.mgmtp.perfload.core.client.web.request.HttpRequestHandler.java
/** * Creates the request object.//from w w w . j a va 2 s. c o m * * @param type * the type of the HTTP request (GET, TRACE, DELETE, OPTIONS, HEAD, POST, PUT) * @param uri * the uri * @param parameters * the request parameters * @param body * the request body * @return the request */ protected HttpRequestBase createRequest(final String type, final URI uri, final List<NameValuePair> parameters, final Body body) throws Exception { HttpRequestBase request = HttpMethod.valueOf(type).create(uri); if (!(request instanceof HttpEntityEnclosingRequest)) { // GET, TRACE, DELETE, OPTIONS, HEAD if (!parameters.isEmpty()) { String query = URLEncodedUtils.format(parameters, "UTF-8"); URI requestURI = new URI( uri.getRawQuery() == null ? uri.toString() + '?' + query : uri.toString() + '&' + query); request.setURI(requestURI); } } else { // POST, PUT final HttpEntityEnclosingRequest entityRequest = (HttpEntityEnclosingRequest) request; if (body != null) { // this only sets the content, header come from the request flow entityRequest.setEntity(new ByteArrayEntity(body.getContent())); } else { checkState(request instanceof HttpPost, "Invalid request: " + request.getMethod() + ". Cannot add post parameters to this kind of request. Please check the request flow."); entityRequest.setEntity(new UrlEncodedFormEntity(parameters, "UTF-8")); } } return request; }