List of usage examples for org.apache.http.entity StringEntity StringEntity
public StringEntity(String str, Charset charset)
From source file:com.braffdev.server.core.module.controllerresult.handler.DefaultControllerResultHandler.java
/** * *//*from w w w . j a v a 2 s . c o m*/ @Override public void handle(RequestEnvironment env, String result) { HttpResponse response = env.getHttpResponse(); response.setStatusCode(HttpStatus.SC_OK); response.setEntity(new StringEntity(result, "UTF-8")); }
From source file:HttpClient.HttpCalendarClient.java
private String send_request(JSONObject req, String operation) { String success = null;//from w w w .j a v a 2s .c om //imposto il "contenitore" della risposta JSON CloseableHttpResponse response1 = null; //creo una richiesta di tipo POSTal WS HttpPost r_post = new HttpPost(url + operation); //imposto l'HEADER della richiesta a JSON r_post.addHeader(new BasicHeader("Content-Type", "application/json")); //Creo l'entita' da inserire nella richiesta, ipostandone come contenuto il JSON StringEntity param = new StringEntity(req.toJSONString(), "UTF8"); param.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json")); r_post.setEntity(param); //EFFETTUO LA RICHIESTA try { //EFFETTUO la richiesta ed attendo la risposta dal WS response1 = httpclient.execute(r_post); if (response1.getEntity() != null) { //converto lo stream ottenuto in un oggetto JSON JSONObject risposta = convertStreamToJson(response1.getEntity().getContent()); if (risposta != null) { String result = (String) risposta.get("code"); if (result.equalsIgnoreCase("201")) { success = (String) risposta.get("id"); } } } } catch (IOException ex) { Logger.getLogger(HttpCalendarClient.class.getName()).log(Level.SEVERE, null, ex); } finally { try { response1.close(); } catch (IOException ex) { Logger.getLogger(HttpCalendarClient.class.getName()).log(Level.SEVERE, null, ex); } } return success; }
From source file:com.github.tomakehurst.wiremock.GzipAcceptanceTest.java
@Test public void acceptsGzippedRequest() { wireMockServer.stubFor(any(urlEqualTo("/gzip-request")).withRequestBody(equalTo("request body")) .willReturn(aResponse().withBody("response body"))); HttpEntity compressedBody = new GzipCompressingEntity( new StringEntity("request body", ContentType.TEXT_PLAIN)); WireMockResponse response = testClient.post("/gzip-request", compressedBody); assertThat(response.content(), is("response body")); }
From source file:com.twitter.hbc.core.HttpConstants.java
public static HttpUriRequest constructRequest(String host, Endpoint endpoint, Authentication auth) { String url = host + endpoint.getURI(); if (endpoint.getHttpMethod().equalsIgnoreCase(HttpGet.METHOD_NAME)) { HttpGet get = new HttpGet(url); if (auth != null) auth.signRequest(get, null); return get; } else if (endpoint.getHttpMethod().equalsIgnoreCase(HttpPost.METHOD_NAME)) { HttpPost post = new HttpPost(url); post.setEntity(new StringEntity(endpoint.getPostParamString(), Constants.DEFAULT_CHARSET)); post.setHeader(HttpHeaders.CONTENT_TYPE, "application/x-www-form-urlencoded"); if (auth != null) auth.signRequest(post, endpoint.getPostParamString()); return post; } else {// ww w. j a v a2 s. com throw new IllegalArgumentException("Bad http method: " + endpoint.getHttpMethod()); } }
From source file:com.sonatype.nexus.perftest.maven.ArtifactDeployer.java
/** * Deploys provided pom.xml file under specified groupId, artifactId and version. The contents of the pom is updated * to match specified groupId, artifactId and version. *//*from w w w. j a v a 2s . co m*/ public void deployPom(String groupId, String artifactId, String version, File pomTemplate) throws IOException { final Document pom = XMLParser.parse(pomTemplate); pom.getRootElement().getChild("groupId").setText(groupId); pom.getRootElement().getChild("artifactId").setText(artifactId); pom.getRootElement().getChild("version").setText(version); // pom.getRootElement().getChild( "packaging" ).setText( "pom" ); StringWriter buf = new StringWriter(); XMLWriter writer = new XMLWriter(buf); pom.toXML(writer); HttpEntity pomEntity = new StringEntity(buf.toString(), ContentType.TEXT_XML); deploy(pomEntity, groupId, artifactId, version, ".pom"); }
From source file:com.strato.hidrive.api.connection.httpgateway.request.JSONPostRequest.java
protected HttpRequestBase createHttpRequest(String requestUri, HttpRequestParamsVisitor<?> visitor) throws UnsupportedEncodingException { HttpPost httpPost = new HttpPost(requestUri); String jsonString = ""; if (jsonObject != null) { jsonString = jsonObject.toString(); } else if (jsonArray != null) { jsonString = jsonArray.toString(); }//from ww w . jav a 2 s . com StringEntity stringEntity = new StringEntity(jsonString, "UTF-8"); stringEntity.setContentEncoding("UTF-8"); stringEntity.setContentType(CONTENT_TYPE_APPLICATION_JSON); httpPost.setEntity(stringEntity); return httpPost; }
From source file:org.eclipse.rcptt.internal.testrail.APIClient.java
public String sendPostRequest(String endpoint, String params) { HttpPost request = new HttpPost(url + endpoint); // Full Unicode support was added in TestRail 2.0, // so we use ISO-8859-1 by default, // but if Unicode is needed, it could be enabled in preferences if (useUnicode) { request.setEntity(new StringEntity(params, StandardCharsets.UTF_8)); } else {//from w ww . java2s .com request.setEntity(new StringEntity(params, StandardCharsets.ISO_8859_1)); } TestRailPlugin.logInfo(MessageFormat.format(Messages.APIClient_GeneratedRequest, params)); return sendRequest(request); }
From source file:org.apache.calcite.adapter.elasticsearch.ElasticSearchAdapterTest.java
/** * Used to create {@code zips} index and insert zip data in bulk. * @throws Exception when instance setup failed *//* w w w . ja va2 s . c o m*/ @BeforeClass public static void setupInstance() throws Exception { // hardcoded mapping definition final String mapping = String.format(Locale.ROOT, "{'mappings':{'%s':{'properties':" + "{'city':{'type':'keyword'},'state':{'type':'keyword'},'pop':{'type':'long'}}" + "}}}", ZIPS).replace('\'', '"'); // create index and mapping final HttpEntity entity = new StringEntity(mapping, ContentType.APPLICATION_JSON); NODE.restClient().performRequest("PUT", "/" + ZIPS, Collections.emptyMap(), entity); // load records from file final List<String> bulk = new ArrayList<>(); Resources.readLines(ElasticSearchAdapterTest.class.getResource("/zips-mini.json"), StandardCharsets.UTF_8, new LineProcessor<Void>() { @Override public boolean processLine(String line) throws IOException { bulk.add("{\"index\": {} }"); // index/type will be derived from _bulk URI line = line.replaceAll("_id", "id"); // _id is a reserved attribute in ES bulk.add(line); return true; } @Override public Void getResult() { return null; } }); if (bulk.isEmpty()) { throw new IllegalStateException("No records to index. Empty file ?"); } final String uri = String.format(Locale.ROOT, "/%s/%s/_bulk?refresh", ZIPS, ZIPS); Response response = NODE.restClient().performRequest("POST", uri, Collections.emptyMap(), new StringEntity(String.join("\n", bulk) + "\n", ContentType.APPLICATION_JSON)); if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) { final String error = EntityUtils.toString(response.getEntity()); final String message = String.format(Locale.ROOT, "Couldn't bulk insert %d elements into %s (%s/%s). Error was %s\n%s\n", bulk.size(), ZIPS, response.getHost(), response.getRequestLine(), response.getStatusLine(), error); throw new IllegalStateException(message); } }
From source file:org.elasticsearch.upgrades.IndexAuditUpgradeIT.java
private void assertNumUniqueNodeNameBuckets(int numBuckets) throws Exception { // call API that will hit all nodes assertEquals(200, client().performRequest("GET", "/_nodes").getStatusLine().getStatusCode()); HttpEntity httpEntity = new StringEntity("{\n" + " \"aggs\" : {\n" + " \"nodes\" : {\n" + " \"terms\" : { \"field\" : \"node_name\" }\n" + " }\n" + " }\n" + "}", ContentType.APPLICATION_JSON); Response aggResponse = client().performRequest("GET", "/.security_audit_log*/_search", Collections.singletonMap("pretty", "true"), httpEntity); Map<String, Object> aggResponseMap = entityAsMap(aggResponse); logger.debug("aggResponse {}", aggResponseMap); Map<String, Object> aggregations = (Map<String, Object>) aggResponseMap.get("aggregations"); assertNotNull(aggregations);/* w w w. j av a2 s .c om*/ Map<String, Object> nodesAgg = (Map<String, Object>) aggregations.get("nodes"); assertNotNull(nodesAgg); List<Map<String, Object>> buckets = (List<Map<String, Object>>) nodesAgg.get("buckets"); assertNotNull(buckets); assertEquals("Found node buckets " + buckets, numBuckets, buckets.size()); }
From source file:v2.service.generic.library.utils.HttpClientUtil.java
@Deprecated public static HttpResponsePOJO jsonRequest(String url, String json, String requestType) throws Exception { HttpClient httpclient = createHttpClient(); HttpEntityEnclosingRequestBase request = null; if ("POST".equalsIgnoreCase(requestType)) { request = new HttpPost(url); } else if ("PUT".equalsIgnoreCase(requestType)) { request = new HttpPut(url); }//from ww w . jav a 2s.co m StringEntity params = new StringEntity(json, "UTF-8"); request.setEntity(params); request.addHeader("content-type", "application/json"); HttpResponsePOJO result = invoke(httpclient, request); return result; }