List of usage examples for org.apache.http.entity StringEntity setChunked
public void setChunked(boolean z)
From source file:com.spokenpic.net.RestClientPut.java
@Override protected RestResult doPost() { HttpPut httpPut = new HttpPut(getSchemeServer() + this.uri); setupHttp(httpPut);/*from ww w. j a v a 2s . com*/ try { StringEntity data = new StringEntity(this.data, "UTF-8"); data.setChunked(false); httpPut.setEntity(data); httpPut.setHeader("Content-type", "application/json"); HttpResponse httpResponse = HttpManager.execute(httpPut); return returnResponse(httpResponse); } catch (Exception e) { Log.d("RestClientFilePUT", "Error doPost: " + e.toString()); return errorResponse("Fatal error during PUT"); } }
From source file:qhindex.servercomm.ServerDataCache.java
public JSONObject sendRequest(JSONObject data, String url, boolean sentAdminNotification) { JSONObject obj = new JSONObject(); final RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(AppHelper.connectionTimeOut) .setConnectionRequestTimeout(AppHelper.connectionTimeOut) .setSocketTimeout(AppHelper.connectionTimeOut).setStaleConnectionCheckEnabled(true).build(); final CloseableHttpClient httpclient = HttpClients.custom().setDefaultRequestConfig(requestConfig).build(); HttpPost httpPost = new HttpPost(url); String dataStr = data.toJSONString(); dataStr = dataStr.replaceAll("null", "\"\""); if (sentAdminNotification == true) { try {/*www . j a v a 2 s .c o m*/ AdminMail adminMail = new AdminMail(); adminMail.sendMailToAdmin("Data to send to the server.", dataStr); } catch (Exception ex) { // Catch any problem during this step and continue Debug.print("Could not send admin notification e-mail: " + ex); } } Debug.print("DATA REQUEST: " + dataStr); StringEntity jsonData = new StringEntity(dataStr, ContentType.create("plain/text", Consts.UTF_8)); jsonData.setChunked(true); httpPost.addHeader("content-type", "application/json"); httpPost.addHeader("accept", "application/json"); httpPost.setEntity(jsonData); try (CloseableHttpResponse response = httpclient.execute(httpPost)) { StatusLine statusLine = response.getStatusLine(); if (statusLine.getStatusCode() >= 300) { Debug.print("Exception while sending http request: " + statusLine.getStatusCode() + " : " + statusLine.getReasonPhrase()); resultsMsg += "Exception while sending http request: " + statusLine.getStatusCode() + " : " + statusLine.getReasonPhrase() + "\n"; } BufferedReader br = new BufferedReader(new InputStreamReader((response.getEntity().getContent()))); String output = new String(); String line; while ((line = br.readLine()) != null) { output += line; } output = output.substring(output.indexOf('{')); try { obj = (JSONObject) new JSONParser().parse(output); } catch (ParseException pEx) { Debug.print( "Could not parse internet response. It is possible the cache server fail to deliver the content: " + pEx.toString()); resultsMsg += "Could not parse internet response. It is possible the cache server fail to deliver the content.\n"; } } catch (IOException ioEx) { Debug.print("Could not handle the internet request: " + ioEx.toString()); resultsMsg += "Could not handle the internet request.\n"; } return obj; }
From source file:PayHost.Utilities.java
/** * Make an HTTP POST REQUEST/* w w w . j av a 2 s. c o m*/ * * @param url Url of the request * @param soapAction Action Name * @param soapEnvBody Soap Message Body * @return Http Post Respsone as String * @throws ParserConfigurationException ParserConfigurationException * @throws SAXException SAXException * @throws IOException IOException */ public String callWebService(String url, String soapAction, String soapEnvBody) throws IOException, ParserConfigurationException, SAXException { // Create a StringEntity for the SOAP XML. String body = envelope(soapEnvBody); StringEntity stringEntity = new StringEntity(body, "UTF-8"); stringEntity.setChunked(true); // Request parameters and other properties. HttpPost httpPost = new HttpPost(url); httpPost.setEntity(stringEntity); httpPost.addHeader("Accept", "text/xml"); httpPost.addHeader("Content-type", "text/xml"); httpPost.addHeader("SOAPAction", soapAction); // Execute and get the response. HttpClient httpClient = new DefaultHttpClient(); HttpResponse response = httpClient.execute(httpPost); HttpEntity entity = response.getEntity(); String strResponse = null; if (entity != null) { strResponse = EntityUtils.toString(entity); } /*if (getStatus(strResponse).getProperty("StatusName").equals("Error")) { System.out.println("Error : " + getStatus(strResponse).getProperty("ResultDescription")); } else { System.out.println("No Error"); }*/ return strResponse; }
From source file:com.spokenpic.net.RestClient.java
protected RestResult doPost() { HttpPost httpPost = new HttpPost(getSchemeServer() + this.uri); setupHttp(httpPost);// w w w.j a v a 2s .c o m try { StringEntity data = new StringEntity(this.data, "UTF-8"); data.setChunked(false); httpPost.setEntity(data); httpPost.setHeader("Content-type", "application/json"); HttpResponse httpResponse = HttpManager.execute(httpPost); return returnResponse(httpResponse); } catch (Exception e) { Log.d("RestClient", "Error doPost " + e.toString()); return errorResponse("Fatal error during POST"); } }
From source file:com.nirima.jenkins.SimpleArtifactCopier.java
protected List<String> fetchFiles(Artifact art) throws IOException, URISyntaxException, UnsupportedEncodingException, UnknownHostException, HttpException, TransformerException, SAXException, ParserConfigurationException { List<String> entries = null; URL url = new URL(host, art.getGroupId().replace('.', '/') + "/" + art.getArtifactId() + "/" + art.getVersion() + "/"); //url = new URL(url, "LastSuccessful/repository"); BasicHttpEntityEnclosingRequest httpget = new BasicHttpEntityEnclosingRequest("PROPFIND", url.toURI().getPath());//from ww w. j av a 2s . com //System.out.println("url=" + url); // HEADER String s = "<propget><allprop/></propget>"; StringEntity se = new StringEntity(s, "US-ASCII"); se.setChunked(false); httpget.setEntity(se); // Start if (!conn.isOpen()) { Socket socket = new Socket(targetHost.getHostName(), targetHost.getPort() > 0 ? targetHost.getPort() : 80); conn.bind(socket, params); } context.setAttribute(ExecutionContext.HTTP_CONNECTION, conn); context.setAttribute(ExecutionContext.HTTP_TARGET_HOST, targetHost); httpexecutor.preProcess(httpget, httpproc, context); HttpResponse response = httpexecutor.execute(httpget, conn, context); httpexecutor.postProcess(response, httpproc, context); HttpEntity entity = response.getEntity(); if (entity != null) { InputStream instream = entity.getContent(); try { if (instream != null) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); IOUtils.copy(instream, baos); entries = getEntries(baos.toByteArray()); } } catch (IOException ex) { conn.shutdown(); } finally { instream.close(); } } if (!connStrategy.keepAlive(response, context)) { conn.close(); } // End return entries; }
From source file:ua.kiev.doctorvera.utils.SMSGateway.java
@SuppressWarnings("deprecation") public ArrayList<String> send(String phone, String sms) { ArrayList<String> result = new ArrayList<String>(); final String MESSAGE = "<message><service id='single' source='" + FROM + "'/><to>" + phone + "</to><body content-type='text/plain'>" + sms + "</body></message>"; @SuppressWarnings("resource") HttpClient httpclient = new DefaultHttpClient(); String xml = null;/*from w ww . j a v a2 s . c om*/ try { HttpPost httpPost = new HttpPost(SMS_SEND_URL); StringEntity entity = new StringEntity(MESSAGE, "UTF-8"); entity.setContentType("text/xml"); entity.setChunked(true); httpPost.setEntity(entity); httpPost.addHeader( BasicScheme.authenticate(new UsernamePasswordCredentials(LOGIN, PASS), "UTF-8", false)); HttpResponse response = httpclient.execute(httpPost); HttpEntity resEntity = response.getEntity(); LOG.info("Sending SMS: " + (response.getStatusLine().getStatusCode() == 200)); xml = EntityUtils.toString(resEntity); } catch (Exception e) { LOG.severe("" + e.getStackTrace()); } finally { httpclient.getConnectionManager().shutdown(); } //parsing xml result Document doc = loadXMLFromString(xml); NodeList nl = doc.getElementsByTagName("status"); Element status = (Element) nl.item(0); result.add(0, status.getAttribute("id").toString()); //tracking id at position 0 result.add(1, status.getAttribute("date").toString()); //date at position 1 result.add(2, getElementValue(status.getFirstChild())); //state at position 2 return result; }
From source file:com.example.restexpmongomvn.controller.VehicleControllerTest.java
/** * Test of create method, of class VehicleController. * * @throws java.io.IOException/* w w w .ja v a 2 s . co m*/ */ @Test public void testCreate() throws IOException { System.out.println("create"); Vehicle testVehicle = new Vehicle(2015, "Test", "Vehicle", Color.Red, "4-Door Sedan"); ObjectMapper objectMapper = new ObjectMapper(); objectMapper.setSerializationInclusion(Include.NON_EMPTY); String testVehicleString = objectMapper.writeValueAsString(testVehicle); // System.out.println(testVehicleString); StringEntity postEntity = new StringEntity(testVehicleString, ContentType.create("application/json", "UTF-8")); postEntity.setChunked(true); // System.out.println(postEntity.getContentType()); // System.out.println(postEntity.getContentLength()); // System.out.println(EntityUtils.toString(postEntity)); // System.out.println(EntityUtils.toByteArray(postEntity).length); CloseableHttpClient httpclient = HttpClients.createDefault(); HttpPost httppost = new HttpPost(BASE_URL + "/restexpress/vehicles"); httppost.setEntity(postEntity); CloseableHttpResponse response = httpclient.execute(httppost); String responseString = new BasicResponseHandler().handleResponse(response); assertEquals(parseMongoId(responseString), true); }
From source file:com.example.restexpmongomvn.controller.VehicleControllerTest.java
/** * Test of read method, of class VehicleController. * @throws com.fasterxml.jackson.core.JsonProcessingException * @throws java.io.IOException/*from w w w . ja va2 s . c o m*/ */ @Test public void testRead() throws JsonProcessingException, IOException { System.out.println("read"); Vehicle testVehicle = new Vehicle(2015, "Test", "Vehicle", Color.Red, "4-Door Sedan"); ObjectMapper objectMapper = new ObjectMapper(); objectMapper.setSerializationInclusion(Include.NON_EMPTY); String testVehicleString = objectMapper.writeValueAsString(testVehicle); StringEntity postEntity = new StringEntity(testVehicleString, ContentType.create("application/json", "UTF-8")); postEntity.setChunked(true); CloseableHttpClient httpclient = HttpClients.createDefault(); HttpPost httppost = new HttpPost(BASE_URL + "/restexpress/vehicles"); httppost.setEntity(postEntity); CloseableHttpResponse response = httpclient.execute(httppost); String responseString = new BasicResponseHandler().handleResponse(response); responseString = responseString.replaceAll("^\"|\"$", ""); // Get vehicle based on MongoDB id HttpGet httpget = new HttpGet(BASE_URL + "/restexpress/vehicle/" + responseString); CloseableHttpResponse response2 = httpclient.execute(httpget); String responseString2 = new BasicResponseHandler().handleResponse(response2); ResponseHandler<Vehicle> rh = new ResponseHandler<Vehicle>() { @Override public Vehicle handleResponse(final HttpResponse response) throws IOException { StatusLine statusLine = response.getStatusLine(); HttpEntity entity = response.getEntity(); if (statusLine.getStatusCode() >= 300) { throw new HttpResponseException(statusLine.getStatusCode(), statusLine.getReasonPhrase()); } if (entity == null) { throw new ClientProtocolException("Response contains no content"); } Gson gson = new GsonBuilder().setPrettyPrinting().setDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'") .create(); ContentType contentType = ContentType.getOrDefault(entity); Charset charset = contentType.getCharset(); Reader reader = new InputStreamReader(entity.getContent(), "UTF-8"); // String inputStreamString = new Scanner(entity.getContent(), "UTF-8").useDelimiter("\\A").next(); // System.out.println(inputStreamString); return gson.fromJson(reader, Vehicle.class); } }; Vehicle vehicle = httpclient.execute(httpget, rh); System.out.println("b"); // MongodbEntityRepository<Vehicle> vehicleRepository; // VehicleController instance = new VehicleController(vehicleRepository); // Vehicle result = instance.read(request, response); // assertEquals(parseMongoId(responseString), true); }
From source file:co.cask.cdap.gateway.handlers.ProcedureHandlerTest.java
/** * Test big content in Post request is not chunked. The content length is char[1423]. *//*from w ww . j a v a 2s . c o m*/ @Test public void testPostBigContentProcedureCall() throws Exception { Map<String, String> content = new ImmutableMap.Builder<String, String>() .put("key1", "valvalvalvalvalvalvalvalvalvalvalvalvalvalvalvalvalvalvalvalvalvalvalvalvalvalvalva1") .put("key2", "valvalvalvalvalvalvalvalvalvalvalvalvalvalvalvalvalvalvalvalvalvalvalvalvalvalvalva2") .put("key3", "valvalvalvalvalvalvalvalvalvalvalvalvalvalvalvalvalvalvalvalvalvalvalvalvalvalvalva3") .put("key4", "valvalvalvalvalvalvalvalvalvalvalvalvalvalvalvalvalvalvalvalvalvalvalvalvalvalvalva4") .put("key5", "valvalvalvalvalvalvalvalvalvalvalvalvalvalvalvalvalvalvalvalvalvalvalvalvalvalvalva5") .put("key6", "valvalvalvalvalvalvalvalvalvalvalvalvalvalvalvalvalvalvalvalvalvalvalvalvalvalvalva6") .put("key7", "valvalvalvalvalvalvalvalvalvalvalvalvalvalvalvalvalvalvalvalvalvalvalvalvalvalvalva7") .put("key8", "valvalvalvalvalvalvalvalvalvalvalvalvalvalvalvalvalvalvalvalvalvalvalvalvalvalvalva8") .put("key9", "valvalvalvalvalvalvalvalvalvalvalvalvalvalvalvalvalvalvalvalvalvalvalvalvalvalvalva9") .put("key10", "valvalvalvalvalvalvalvalvalvalvalvalvalvalvalvalvalvalvalvalvalvalvalvalvalvalvalva10") .put("key11", "valvalvalvalvalvalvalvalvalvalvalvalvalvalvalvalvalvalvalvalvalvalvalvalvalvalvalva11") .put("key12", "valvalvalvalvalvalvalvalvalvalvalvalvalvalvalvalvalvalvalvalvalvalvalvalvalvalvalva12") .put("key13", "valvalvalvalvalvalvalvalvalvalvalvalvalvalvalvalvalvalvalvalvalvalvalvalvalvalvalva13") .put("key14", "valvalvalvalvalvalvalvalvalvalvalvalvalvalvalvalvalvalvalvalvalvalvalvalvalvalvalva14") .put("key15", "valvalvalvalvalvalvalvalvalvalvalvalvalvalvalvalvalvalvalvalvalvalvalvalvalvalvalva15") .build(); Type type = MAP_STRING_STRING_TYPE; String contentStr = GSON.toJson(content, type); Assert.assertNotNull(contentStr); Assert.assertFalse(contentStr.isEmpty()); // Set entity chunked StringEntity entity = new StringEntity(contentStr); entity.setChunked(true); HttpPost post = GatewayFastTestsSuite.getPost("/v2/apps/testApp1/procedures/testProc1/methods/testMethod1"); post.setHeader("Expect", "100-continue"); post.setEntity(entity); HttpResponse response = GatewayFastTestsSuite.doPost(post); Assert.assertEquals(HttpResponseStatus.OK.getCode(), response.getStatusLine().getStatusCode()); String responseStr = EntityUtils.toString(response.getEntity()); Assert.assertEquals(content, GSON.fromJson(responseStr, type)); }
From source file:org.openhim.mediator.e2e.E2EBase.java
private HttpUriRequest buildUriRequest(String method, String body, URI uri) throws UnsupportedEncodingException { HttpUriRequest uriReq;//from w w w . j a v a2 s. co m switch (method) { case "GET": uriReq = new HttpGet(uri); break; case "POST": uriReq = new HttpPost(uri); StringEntity entity = new StringEntity(body); if (body.length() > 1024) { //always test big requests chunked entity.setChunked(true); } ((HttpPost) uriReq).setEntity(entity); break; case "PUT": uriReq = new HttpPut(uri); StringEntity putEntity = new StringEntity(body); ((HttpPut) uriReq).setEntity(putEntity); break; case "DELETE": uriReq = new HttpDelete(uri); break; default: throw new UnsupportedOperationException(method + " requests not supported"); } return uriReq; }