List of usage examples for org.apache.http.client.fluent Request bodyString
public Request bodyString(final String s, final ContentType contentType)
From source file:edu.jhuapl.dorset.http.apache.ApacheHttpClient.java
private Response post(HttpRequest request) throws IOException { Request apacheRequest = Request.Post(request.getUrl()); if (request.getBody() != null) { ContentType ct = ContentType.create(request.getContentType().getMimeType(), request.getContentType().getCharset()); apacheRequest.bodyString(request.getBody(), ct); } else if (request.getBodyForm() != null) { apacheRequest.bodyForm(buildFormBody(request.getBodyForm())); }/*from www .j ava 2 s .co m*/ prepareRequest(apacheRequest); return apacheRequest.execute(); }
From source file:org.ow2.proactive.addons.webhook.service.JsonRestApacheRequestService.java
public RestResponse doRequest(String restMethod, String jsonHeader, String url, String content) throws IOException { Request request = apacheHttpClientRequestGetter.getHttpRequestByString(restMethod, url); for (Map.Entry<String, String> entry : jsonStringToHeaderMap.convert(jsonHeader).entrySet()) { request.addHeader(entry.getKey(), entry.getValue()); }/* w ww . j a va 2 s. co m*/ if (content != null && !content.isEmpty()) { request.bodyString(content, ContentType.TEXT_PLAIN); } return executeRequest(request); }
From source file:com.ibm.watson.ta.retail.DemoServlet.java
/** * Create and POST a request to the Watson service * * @param req//from w w w. j a va 2s . c om * the Http Servlet request * @param resp * the Http Servlet response * @throws ServletException * the servlet exception * @throws IOException * Signals that an I/O exception has occurred. */ @Override protected void doPost(final HttpServletRequest req, final HttpServletResponse resp) throws ServletException, IOException { req.setCharacterEncoding("UTF-8"); try { String queryStr = req.getQueryString(); String url = baseURL + "/v1/dilemmas"; if (queryStr != null) { url += "?" + queryStr; } URI uri = new URI(url).normalize(); logger.info("posting to " + url); Request newReq = Request.Post(uri); newReq.addHeader("Accept", "application/json"); InputStreamEntity entity = new InputStreamEntity(req.getInputStream()); newReq.bodyString(EntityUtils.toString(entity, "UTF-8"), ContentType.APPLICATION_JSON); Executor executor = this.buildExecutor(uri); Response response = executor.execute(newReq); HttpResponse httpResponse = response.returnResponse(); resp.setStatus(httpResponse.getStatusLine().getStatusCode()); ServletOutputStream servletOutputStream = resp.getOutputStream(); httpResponse.getEntity().writeTo(servletOutputStream); servletOutputStream.flush(); servletOutputStream.close(); logger.info("post done"); } catch (Exception e) { // Log something and return an error message logger.log(Level.SEVERE, "got error: " + e.getMessage(), e); resp.setStatus(HttpStatus.SC_BAD_GATEWAY); } }
From source file:com.qwazr.utils.json.client.JsonClientAbstract.java
private Request setBodyString(Request request, Object bodyObject) throws JsonProcessingException { if (bodyObject == null) return request; if (bodyObject instanceof String) return request.bodyString(bodyObject.toString(), ContentType.TEXT_PLAIN); else if (bodyObject instanceof InputStream) return request.bodyStream((InputStream) bodyObject, ContentType.APPLICATION_OCTET_STREAM); else// w w w. j a v a 2s . c o m return request.bodyString(JsonMapper.MAPPER.writeValueAsString(bodyObject), ContentType.APPLICATION_JSON); }
From source file:org.schedulesdirect.api.json.DefaultJsonRequest.java
private HttpResponse submitRaw(Object reqData) throws IOException { if (!valid)/*from ww w . j ava 2 s . c om*/ throw new IllegalStateException("Cannot submit a partially constructed request!"); try { targetUrl = baseUrl.toString(); audit.append(String.format(">>>target: %s%n>>>verb: %s%n", targetUrl, action)); Executor exe = Executor.newInstance(new DecompressingHttpClient(new DefaultHttpClient())); Request req = initRequest(); if (hash != null) req.addHeader(new BasicHeader("token", hash)); if (reqData != null) req.bodyString(reqData.toString(), ContentType.APPLICATION_JSON); audit.append(String.format(">>>req_headers:%n%s", HttpUtils.prettyPrintHeaders(HttpUtils.scrapeHeaders(req), "\t"))); if (action == Action.PUT || action == Action.POST) audit.append(String.format(">>>input: %s%n", reqData)); HttpResponse resp = exe.execute(req).returnResponse(); if (LOG.isDebugEnabled()) { Header h = resp.getFirstHeader("Schedulesdirect-Serverid"); String val = h != null ? h.getValue() : "[Unknown]"; LOG.debug(String.format("Request to '%s' handled by: %s", targetUrl, val)); } StatusLine status = resp.getStatusLine(); audit.append(String.format("<<<resp_status: %s%n", status)); audit.append(String.format("<<<resp_headers:%n%s", HttpUtils.prettyPrintHeaders(resp.getAllHeaders(), "\t"))); if (LOG.isDebugEnabled() && status.getStatusCode() >= 400) LOG.debug(String.format("%s returned error! [rc=%d]", req, status.getStatusCode())); return resp; } catch (IOException e) { audit.append(String.format("*** REQUEST FAILED! ***%n%s", e.getMessage())); throw e; } }
From source file:net.bluemix.newsaggregator.api.AuthenticationServlet.java
private String getAccessTokenFromCodeResponse(String id, String secret, String redirect, String code) { String output = null;//w ww .ja v a2 s . c o m try { configureSSL(); org.apache.http.client.fluent.Request req = Request .Post("https://idaas.ng.bluemix.net/sps/oauth20sp/oauth20/token"); String body = "client_secret=" + secret + "&grant_type=authorization_code" + "&redirect_uri=" + redirect + "&code=" + code + "&client_id=" + id; req.bodyString(body, ContentType.create("application/x-www-form-urlencoded")); org.apache.http.client.fluent.Response res = req.execute(); output = res.returnContent().asString(); output = output.substring(output.indexOf("access_token") + 15, output.indexOf("access_token") + 35); } catch (IOException e) { e.printStackTrace(); } return output; }
From source file:com.jaspersoft.studio.server.protocol.restv2.RestV2Connection.java
@Override public ResourceDescriptor addOrModifyResource(IProgressMonitor monitor, ResourceDescriptor rd, File inputFile) throws Exception { URIBuilder ub = new URIBuilder(url("resources" + rd.getUriString())); ub.addParameter("createFolders", "true"); ub.addParameter("overwrite", "true"); Request req = HttpUtils.put(ub.build().toASCIIString(), sp); String rtype = WsTypes.INST().toRestType(rd.getWsType()); ContentType ct = ContentType.create("application/repository." + rtype + "+" + FORMAT); req.bodyString(mapper.writeValueAsString(Soap2Rest.getResource(this, rd)), ct); ClientResource<?> crl = toObj(req, WsTypes.INST().getType(rtype), monitor); if (crl != null) return Rest2Soap.getRD(this, crl, rd); return null;/*from ww w. j a v a 2 s . co m*/ }
From source file:com.ibm.watson.ta.retail.TAProxyServlet.java
/** * Create and POST a request to the Watson service * * @param req/* w ww . java2 s . c o m*/ * the Http Servlet request * @param resp * the Http Servlet response * @throws ServletException * the servlet exception * @throws IOException * Signals that an I/O exception has occurred. */ @Override protected void doPost(final HttpServletRequest req, final HttpServletResponse resp) throws ServletException, IOException { req.setCharacterEncoding("UTF-8"); try { String reqURI = req.getRequestURI(); String endpoint = reqURI.substring(reqURI.lastIndexOf('/') + 1); String url = baseURL + "/v1/" + endpoint; // concatenate query params String queryStr = req.getQueryString(); if (queryStr != null) { url += "?" + queryStr; } URI uri = new URI(url).normalize(); logger.info("posting to " + url); Request newReq = Request.Post(uri); newReq.addHeader("Accept", "application/json"); String metadata = req.getHeader("x-watson-metadata"); if (metadata != null) { metadata += "client-ip:" + req.getRemoteAddr(); newReq.addHeader("x-watson-metadata", metadata); } InputStreamEntity entity = new InputStreamEntity(req.getInputStream()); newReq.bodyString(EntityUtils.toString(entity, "UTF-8"), ContentType.APPLICATION_JSON); Executor executor = this.buildExecutor(uri); Response response = executor.execute(newReq); HttpResponse httpResponse = response.returnResponse(); resp.setStatus(httpResponse.getStatusLine().getStatusCode()); ServletOutputStream servletOutputStream = resp.getOutputStream(); httpResponse.getEntity().writeTo(servletOutputStream); servletOutputStream.flush(); servletOutputStream.close(); logger.info("post done"); } catch (Exception e) { // Log something and return an error message logger.log(Level.SEVERE, "got error: " + e.getMessage(), e); resp.setStatus(HttpStatus.SC_BAD_GATEWAY); } }
From source file:be.fedict.dcat.datagovbe.Drupal.java
/** * Add a dataset to the Drupal website./*from w w w . j a v a2 s .c o m*/ * * @param uri identifier of the dataset * @throws RepositoryException */ private void add(IRI uri) throws RepositoryException { Map<IRI, ListMultimap<String, String>> dataset = store.queryProperties(uri); if (dataset.isEmpty()) { logger.warn("Empty dataset for {}", uri.stringValue()); return; } for (String lang : langs) { if (!hasLang(dataset, lang)) { continue; } JsonObjectBuilder builder = Json.createObjectBuilder(); addDataset(builder, dataset, lang); // Get DCAT distributions List<String> dists = getMany(dataset, DCAT.DISTRIBUTION, ""); addDists(builder, dists, lang); // Add new or update existing dataset ? String id = getOne(dataset, DCTERMS.IDENTIFIER, ""); String node = checkExistsTrans(builder, id, lang); // Build the JSON array JsonObject obj = builder.build(); logger.debug(obj.toString()); Request r = node.isEmpty() ? prepare(Drupal.POST, Drupal.NODE) : prepare(Drupal.PUT, Drupal.NODE + "/" + node); r.bodyString(obj.toString(), ContentType.APPLICATION_JSON); try { StatusLine status = exec.authPreemptive(host).execute(r).returnResponse().getStatusLine(); logger.debug(status.toString()); } catch (IOException ex) { logger.error("Could not update {}", uri.toString(), ex); } } }
From source file:eu.trentorise.opendata.jackan.ckan.CkanClient.java
/** * * @param <T>//w w w . j a va2s. co m * @param responseType a descendant of CkanResponse * @param path something like 1/api/3/action/package_create * @param body the body of the POST * @param the content type, i.e. * @param params list of key, value parameters. They must be not be url * encoded. i.e. "id","laghi-monitorati-trento" * @throws JackanException on error */ <T extends CkanResponse> T postHttp(Class<T> responseType, String path, String body, ContentType contentType, Object... params) { checkNotNull(responseType); checkNotNull(path); checkNotNull(body); checkNotNull(contentType); String fullUrl = calcFullUrl(path, params); try { logger.log(Level.FINE, "posting to url {0}", fullUrl); Request request = Request.Post(fullUrl); if (proxy != null) { request.viaProxy(proxy); } Response response = request.bodyString(body, contentType).addHeader("Authorization", ckanToken) .execute(); Content out = response.returnContent(); String json = out.asString(); T dr = getObjectMapper().readValue(json, responseType); if (!dr.success) { // monkey patching error type throw new JackanException("posting to catalog " + catalogURL + " was not successful. Reason: " + CkanError.read(getObjectMapper().readTree(json).get("error").asText())); } return dr; } catch (Exception ex) { throw new JackanException("Error while performing a POST! Request url is:" + fullUrl, ex); } }