List of usage examples for org.apache.http.entity StringEntity StringEntity
public StringEntity(String str, Charset charset)
From source file:ch.ralscha.extdirectspring_itest.SecuredServiceTest.java
@Test public void callSetDate() throws IOException, JsonParseException, JsonMappingException { CloseableHttpClient client = HttpClientBuilder.create().build(); CloseableHttpResponse response = null; try {/*from w w w .jav a2s .com*/ HttpPost post = new HttpPost("http://localhost:9998/controller/router"); StringEntity postEntity = new StringEntity( "{\"action\":\"securedService\",\"method\":\"setDate\",\"data\":[102,\"26/04/2012\"],\"type\":\"rpc\",\"tid\":1}", "UTF-8"); post.setEntity(postEntity); post.setHeader("Content-Type", "application/json; charset=UTF-8"); response = client.execute(post); HttpEntity entity = response.getEntity(); assertThat(entity).isNotNull(); String responseString = EntityUtils.toString(entity); assertThat(responseString).isNotNull(); assertThat(responseString.startsWith("[") && responseString.endsWith("]")).isTrue(); ObjectMapper mapper = new ObjectMapper(); Map<String, Object> rootAsMap = mapper .readValue(responseString.substring(1, responseString.length() - 1), Map.class); assertThat(rootAsMap).hasSize(5); assertThat(rootAsMap.get("result")).isEqualTo("102,26.04.2012,"); assertThat(rootAsMap.get("method")).isEqualTo("setDate"); assertThat(rootAsMap.get("type")).isEqualTo("rpc"); assertThat(rootAsMap.get("action")).isEqualTo("securedService"); assertThat(rootAsMap.get("tid")).isEqualTo(1); } finally { IOUtils.closeQuietly(response); IOUtils.closeQuietly(client); } }
From source file:cn.hhh.myandroidserver.response.AndServerUploadBootHandler.java
@Override public void handle(HttpRequest request, HttpResponse response, HttpContext context) throws HttpException, IOException { response.setHeader("Content-Type", "text/html"); response.setEntity(new StringEntity("<!DOCTYPE html> \n" + "<meta charset=\"utf-8\" /> \n" + "<title>WebSocket Test</title> \n" + "<script language=\"javascript\"type=\"text/javascript\"> \n" + " function uploadFile(){ \n" + " var fileObj = document.getElementById(\"upload-file\").files[0]; // ? \n" + " var FileController = \"http://" + WifiUtil.getInstance().ipString + ":4477/upload\"; // ??? \n" + " \n" + " if(fileObj){ \n" + " alert(fileObj); \n" + " // FormData \n" + " var form = new FormData(); \n" + " form.append(\"file\", fileObj);// \n" + " \n" + " // XMLHttpRequest \n" + " var xhr = new XMLHttpRequest(); \n" + " xhr.open(\"post\", FileController, true); \n" + " xhr.onload = function () { \n" + " alert(xhr.responseText); \n" + " }; \n" + " xhr.send(form); \n" + " \n" + " }else{ \n" + " alert(\"\"); \n" + " } \n" + "}\n" + "</script> \n" + "<div class=\"input-chunk\"> \n" + " <div></div> \n" + " <input type=\"file\" value=\"\" id=\"upload-file\"> \n" + " <br> \n" + " <a id=\"start-upload\" href=\"javascript:void(0);\" onclick=\"uploadFile();\"></a> \n" + "</div>\n" + "</html>", "utf-8")); }
From source file:juzu.impl.bridge.request.RequestFormContentTypeTestCase.java
@Test public void testWithCharsetOnContentType() throws Exception { HttpClient client = new DefaultHttpClient(); HttpPost httpPost = new HttpPost(applicationURL().toString() + "/foo"); ContentType content = ContentType.create("application/x-www-form-urlencoded", "UTF-8"); HttpEntity entity = new StringEntity("param=" + "test" + EURO, content); httpPost.setEntity(entity);//from w ww . j ava 2 s. c om client.execute(httpPost); assertEquals("test" + EURO, param); }
From source file:LicenseKeyAPI.java
/** * Registers the application with the server * * @param licenseKey The license key to register with the server. * @param appID The application ID to register with the server. * @param userEmail The users email to register the app with the server. * @return The status code returned from the server. **///w w w.ja v a2s .co m public int registerApp(String licenseKey, String appID, String userEmail) { String URLpostFixEndpoint = "api/client/register_application"; // Creates HTTP POST request HttpPost httppost = new HttpPost(baseServerURLAddress + URLpostFixEndpoint); httppost.addHeader("Content-Type", "application/json"); httppost.setHeader("Content-Type", "application/json; charset= utf-8"); httppost.setHeader("Accept", "application/json"); JSONObject json = new JSONObject(); json.put("email", userEmail); json.put("licensekey", licenseKey); json.put("appID", appID); StringEntity entity = new StringEntity(json.toString(), "utf-8"); // Adds the POST params to the request httppost.setEntity(entity); return sendPOST(httppost); }
From source file:com.mashape.unirest.request.body.RequestBodyEntity.java
public HttpEntity getEntity() { try {/* w ww .j ava 2 s .c o m*/ return new StringEntity(body.toString(), UTF_8); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } }
From source file:com.cloudant.client.internal.views.ViewMultipleRequester.java
public List<ViewResponse<K, V>> getViewResponses() throws IOException { //build the queries array of data to POST JsonArray queries = new JsonArray(); ViewQueryParameters<K, V> viewQueryParameters = null; for (ViewQueryParameters<K, V> params : requestParameters) { if (viewQueryParameters == null) { viewQueryParameters = params; }/* w ww . j av a 2 s. c o m*/ queries.add(params.asJson()); } JsonObject queryJson = new JsonObject(); queryJson.add("queries", queries); //construct and execute the POST request HttpPost post = new HttpPost(viewQueryParameters.getViewURIBuilder().buildEncoded()); StringEntity entity = new StringEntity(queryJson.toString(), "UTF-8"); entity.setContentType("application/json"); post.setEntity(entity); JsonObject jsonResponse = ViewRequester.executeRequestWithResponseAsJson(viewQueryParameters, post); //loop the returned array creating the ViewResponse objects List<ViewResponse<K, V>> responses = new ArrayList<ViewResponse<K, V>>(); JsonArray jsonResponses = jsonResponse.getAsJsonArray("results"); if (jsonResponses != null) { int index = 0; for (ViewQueryParameters<K, V> params : requestParameters) { JsonObject response = jsonResponses.get(index).getAsJsonObject(); responses.add(new ViewResponseImpl<K, V>(params, response)); index++; } return responses; } else { return Collections.emptyList(); } }
From source file:org.ligoj.app.http.security.RestAuthenticationProvider.java
@Override public Authentication authenticate(final Authentication authentication) { final String userpassword = StringUtils.defaultString(authentication.getCredentials().toString(), ""); final String userName = StringUtils.lowerCase(authentication.getPrincipal().toString()); // First get the cookie final HttpClientBuilder clientBuilder = HttpClientBuilder.create(); clientBuilder.setDefaultRequestConfig(RequestConfig.custom().setCookieSpec(CookieSpecs.STANDARD).build()); final HttpPost httpPost = new HttpPost(getSsoPostUrl()); // Do the POST try (CloseableHttpClient httpClient = clientBuilder.build()) { final String content = String.format(getSsoPostContent(), userName, userpassword); httpPost.setEntity(new StringEntity(content, StandardCharsets.UTF_8)); httpPost.setHeader("Content-Type", "application/json"); final HttpResponse httpResponse = httpClient.execute(httpPost); if (HttpStatus.SC_NO_CONTENT == httpResponse.getStatusLine().getStatusCode()) { // Succeed authentication, save the cookies data inside the authentication return newAuthentication(userName, userpassword, authentication, httpResponse); }/*from ww w .java 2s. com*/ log.info("Failed authentication of {}[{}] : {}", userName, userpassword.length(), httpResponse.getStatusLine().getStatusCode()); httpResponse.getEntity().getContent().close(); } catch (final IOException e) { log.warn("Remote SSO server is not available", e); } throw new BadCredentialsException("Invalid user or password"); }
From source file:com.github.parisoft.resty.entity.EntityWriterImpl.java
@Override public HttpEntity getEntity() throws IOException { final Object rawEntity = request.entity(); final String rawType = request.headers().containsKey(CONTENT_TYPE) ? request.headers().getFirst(CONTENT_TYPE) : null;/*ww w .ja v a 2 s .co m*/ final HttpEntity entity; try { if (rawEntity == null || rawEntity instanceof HttpEntity) { entity = (HttpEntity) rawEntity; } else if (rawEntity instanceof String || isPrimitive(rawEntity)) { final ContentType contentType = (rawType == null) ? null : ContentType.parse(rawType); entity = new StringEntity(rawEntity.toString(), contentType); } else { final ContentType contentType = ContentType.parse(rawType); final MediaType mediaType = MediaTypeUtils.valueOf(contentType); final String entityAsString = JacksonUtils.write(rawEntity, mediaType); entity = new StringEntity(entityAsString, contentType); } } catch (Exception e) { throw new IOException("Cannot write request entity", e); } return entity; }
From source file:com.ericsson.gerrit.plugins.highavailability.forwarder.rest.HttpSession.java
HttpResult post(String endpoint, String content) throws IOException { HttpPost post = new HttpPost(getPeerInfo().getDirectUrl() + endpoint); if (!Strings.isNullOrEmpty(content)) { post.addHeader("Content-Type", MediaType.JSON_UTF_8.toString()); post.setEntity(new StringEntity(content, StandardCharsets.UTF_8)); }/* w w w . j a va 2 s .c om*/ return httpClient.execute(post, new HttpResponseHandler()); }