List of usage examples for org.apache.http.client.methods HttpEntityEnclosingRequestBase setEntity
public void setEntity(final HttpEntity entity)
From source file:org.eclipse.rdf4j.http.client.RDF4JProtocolSession.java
protected void upload(HttpEntity reqEntity, String baseURI, boolean overwrite, boolean preserveNodeIds, Action action, Resource... contexts) throws IOException, RDFParseException, RepositoryException, UnauthorizedException { OpenRDFUtil.verifyContextNotNull(contexts); checkRepositoryURL();/* w ww.j ava 2s .c om*/ boolean useTransaction = transactionURL != null; try { String baseLocation = useTransaction ? transactionURL : Protocol.getStatementsLocation(getQueryURL()); URIBuilder url = new URIBuilder(baseLocation); // Set relevant query parameters for (String encodedContext : Protocol.encodeContexts(contexts)) { url.addParameter(Protocol.CONTEXT_PARAM_NAME, encodedContext); } if (baseURI != null && baseURI.trim().length() != 0) { String encodedBaseURI = Protocol.encodeValue(SimpleValueFactory.getInstance().createIRI(baseURI)); url.setParameter(Protocol.BASEURI_PARAM_NAME, encodedBaseURI); } if (preserveNodeIds) { url.setParameter(Protocol.PRESERVE_BNODE_ID_PARAM_NAME, "true"); } if (useTransaction) { if (action == null) { throw new IllegalArgumentException("action can not be null on transaction operation"); } url.setParameter(Protocol.ACTION_PARAM_NAME, action.toString()); } // Select appropriate HTTP method HttpEntityEnclosingRequestBase method = null; try { if (overwrite || useTransaction) { method = new HttpPut(url.build()); } else { method = new HttpPost(url.build()); } // Set payload method.setEntity(reqEntity); // Send request try { executeNoContent((HttpUriRequest) method); } catch (RepositoryException e) { throw e; } catch (RDFParseException e) { throw e; } catch (RDF4JException e) { throw new RepositoryException(e); } } finally { if (method != null) { method.reset(); } } } catch (URISyntaxException e) { throw new AssertionError(e); } }
From source file:com.fujitsu.dc.test.jersey.DcRestAdapter.java
/** * GET/POST/PUT/DELETE ?./*from ww w.ja va2 s . co m*/ * @param method Http * @param url URL * @param body * @param headers ?? * @return DcResponse * @throws DcException DAO */ public DcResponse request(final String method, String url, String body, HashMap<String, String> headers) throws DcException { HttpEntityEnclosingRequestBase req = new HttpEntityEnclosingRequestBase() { @Override public String getMethod() { return method; } }; req.setURI(URI.create(url)); for (Map.Entry<String, String> entry : headers.entrySet()) { req.setHeader(entry.getKey(), entry.getValue()); } req.addHeader("X-Dc-Version", DcCoreTestConfig.getCoreVersion()); if (body != null) { HttpEntity httpEntity = null; try { String bodyStr = toUniversalCharacterNames(body); httpEntity = new StringEntity(bodyStr); } catch (UnsupportedEncodingException e) { throw DcException.create("error while request body encoding : " + e.getMessage(), 0); } req.setEntity(httpEntity); } debugHttpRequest(req, body); return this.request(req); }
From source file:co.cask.cdap.internal.app.services.http.AppFabricTestBase.java
/** * Deploys an application with (optionally) a defined app name and app version *///from w ww. j a va 2 s .com protected HttpResponse deploy(Class<?> application, @Nullable String apiVersion, @Nullable String namespace, @Nullable String appVersion, @Nullable Config appConfig) throws Exception { namespace = namespace == null ? Id.Namespace.DEFAULT.getId() : namespace; apiVersion = apiVersion == null ? Constants.Gateway.API_VERSION_3_TOKEN : apiVersion; appVersion = appVersion == null ? String.format("1.0.%d", System.currentTimeMillis()) : appVersion; Manifest manifest = new Manifest(); manifest.getMainAttributes().put(ManifestFields.BUNDLE_VERSION, appVersion); File artifactJar = buildAppArtifact(application, application.getSimpleName(), manifest); File expandDir = tmpFolder.newFolder(); BundleJarUtil.unJar(Locations.toLocation(artifactJar), expandDir); // Add webapp File webAppFile = new File(expandDir, "webapp/default/netlens/src/1.txt"); webAppFile.getParentFile().mkdirs(); Files.write("dummy data", webAppFile, Charsets.UTF_8); BundleJarUtil.createJar(expandDir, artifactJar); HttpEntityEnclosingRequestBase request; String versionedApiPath = getVersionedAPIPath("apps/", apiVersion, namespace); request = getPost(versionedApiPath); request.setHeader(Constants.Gateway.API_KEY, "api-key-example"); request.setHeader("X-Archive-Name", String.format("%s-%s.jar", application.getSimpleName(), appVersion)); if (appConfig != null) { request.setHeader("X-App-Config", GSON.toJson(appConfig)); } request.setEntity(new FileEntity(artifactJar)); return execute(request); }
From source file:org.dasein.cloud.azure.AzureMethod.java
public String invoke(@Nonnull String method, @Nonnull String account, @Nonnull String resource, @Nonnull String body) throws CloudException, InternalException { if (logger.isTraceEnabled()) { logger.trace("enter - " + AzureMethod.class.getName() + ".post(" + account + "," + resource + ")"); }//from w ww.j a v a 2s . com if (wire.isDebugEnabled()) { wire.debug("POST --------------------------------------------------------> " + endpoint + account + resource); wire.debug(""); } String requestId = null; try { HttpClient client = getClient(); String url = endpoint + account + resource; HttpRequestBase httpMethod = getMethod(method, url); //If it is networking configuration services if (httpMethod instanceof HttpPut) { if (url.endsWith("/services/networking/media")) { httpMethod.addHeader("Content-Type", "text/plain"); } else { httpMethod.addHeader("Content-Type", "application/xml;charset=UTF-8"); } } else { httpMethod.addHeader("Content-Type", "application/xml;charset=UTF-8"); } //dmayne version is older for anything to do with images and for disk deletion if (url.indexOf("/services/images") > -1 || (httpMethod instanceof HttpDelete && url.indexOf("/services/disks") > -1)) { httpMethod.addHeader("x-ms-version", "2012-08-01"); } else { httpMethod.addHeader("x-ms-version", "2012-03-01"); } if (wire.isDebugEnabled()) { wire.debug(httpMethod.getRequestLine().toString()); for (Header header : httpMethod.getAllHeaders()) { wire.debug(header.getName() + ": " + header.getValue()); } wire.debug(""); if (body != null) { wire.debug(body); wire.debug(""); } } if (httpMethod instanceof HttpEntityEnclosingRequestBase) { HttpEntityEnclosingRequestBase entityEnclosingMethod = (HttpEntityEnclosingRequestBase) httpMethod; if (body != null) { try { entityEnclosingMethod.setEntity(new StringEntity(body, "application/xml", "utf-8")); } catch (UnsupportedEncodingException e) { throw new CloudException(e); } } } HttpResponse response; StatusLine status; try { response = client.execute(httpMethod); status = response.getStatusLine(); } catch (IOException e) { logger.error("post(): Failed to execute HTTP request due to a cloud I/O error: " + e.getMessage()); if (logger.isTraceEnabled()) { e.printStackTrace(); } throw new CloudException(e); } if (logger.isDebugEnabled()) { logger.debug("post(): HTTP Status " + status); } Header[] headers = response.getAllHeaders(); if (wire.isDebugEnabled()) { wire.debug(status.toString()); for (Header h : headers) { if (h.getValue() != null) { wire.debug(h.getName() + ": " + h.getValue().trim()); if (h.getName().equalsIgnoreCase("x-ms-request-id")) { requestId = h.getValue().trim(); } } else { wire.debug(h.getName() + ":"); } } wire.debug(""); } if (status.getStatusCode() == HttpServletResponse.SC_TEMPORARY_REDIRECT) { logger.warn("Expected OK, got " + status.getStatusCode()); String responseBody = ""; HttpEntity entity = response.getEntity(); if (entity == null) { throw new AzureException(CloudErrorType.GENERAL, status.getStatusCode(), status.getReasonPhrase(), "An error was returned without explanation"); } try { responseBody = EntityUtils.toString(entity); } catch (IOException e) { throw new AzureException(CloudErrorType.GENERAL, status.getStatusCode(), status.getReasonPhrase(), e.getMessage()); } logger.debug(responseBody); logger.debug("https: char " + responseBody.indexOf("https://")); logger.debug("account number: char " + responseBody.indexOf(account)); String tempEndpoint = responseBody.substring(responseBody.indexOf("https://"), responseBody.indexOf(account) - responseBody.indexOf("https://")); logger.debug("temp redirect location: " + tempEndpoint); tempRedirectInvoke(tempEndpoint, method, account, resource, body); } else if (status.getStatusCode() != HttpServletResponse.SC_OK && status.getStatusCode() != HttpServletResponse.SC_CREATED && status.getStatusCode() != HttpServletResponse.SC_ACCEPTED) { logger.error("post(): Expected OK for GET request, got " + status.getStatusCode()); HttpEntity entity = response.getEntity(); if (entity == null) { throw new AzureException(CloudErrorType.GENERAL, status.getStatusCode(), status.getReasonPhrase(), "An error was returned without explanation"); } try { body = EntityUtils.toString(entity); } catch (IOException e) { throw new AzureException(CloudErrorType.GENERAL, status.getStatusCode(), status.getReasonPhrase(), e.getMessage()); } if (wire.isDebugEnabled()) { wire.debug(body); } wire.debug(""); AzureException.ExceptionItems items = AzureException.parseException(status.getStatusCode(), body); if (items == null) { throw new CloudException(CloudErrorType.GENERAL, status.getStatusCode(), "Unknown", "Unknown"); } logger.error("post(): [" + status.getStatusCode() + " : " + items.message + "] " + items.details); throw new AzureException(items); } } finally { if (logger.isTraceEnabled()) { logger.trace("exit - " + AzureMethod.class.getName() + ".post()"); } if (wire.isDebugEnabled()) { wire.debug(""); wire.debug("POST --------------------------------------------------------> " + endpoint + account + resource); } } return requestId; }
From source file:co.cask.cdap.internal.app.services.http.AppFabricTestBase.java
protected HttpResponse addArtifact(Id.Artifact artifactId, InputStream artifactContents, Set<ArtifactRange> parents) throws Exception { String path = getVersionedAPIPath("artifacts/" + artifactId.getName(), artifactId.getNamespace().getId()); HttpEntityEnclosingRequestBase request = getPost(path); request.setHeader(Constants.Gateway.API_KEY, "api-key-example"); request.setHeader("Artifact-Version", artifactId.getVersion().getVersion()); if (parents != null && !parents.isEmpty()) { request.setHeader("Artifact-Extends", Joiner.on('/').join(parents)); }//w ww . j av a 2 s . c o m ByteArrayOutputStream bos = new ByteArrayOutputStream(); ByteStreams.copy(artifactContents, bos); bos.close(); request.setEntity(new ByteArrayEntity(bos.toByteArray())); return execute(request); }
From source file:io.personium.test.jersey.PersoniumRestAdapter.java
/** * GET/POST/PUT/DELETE ?.//from ww w . j a va2 s .c o m * @param method Http * @param url URL * @param body * @param headers ?? * @return DcResponse * @throws PersoniumException DAO */ public PersoniumResponse request(final String method, String url, String body, HashMap<String, String> headers) throws PersoniumException { HttpEntityEnclosingRequestBase req = new HttpEntityEnclosingRequestBase() { @Override public String getMethod() { return method; } }; req.setURI(URI.create(url)); for (Map.Entry<String, String> entry : headers.entrySet()) { req.setHeader(entry.getKey(), entry.getValue()); } req.addHeader("X-Personium-Version", PersoniumCoreTestConfig.getCoreVersion()); if (body != null) { HttpEntity httpEntity = null; try { String bodyStr = toUniversalCharacterNames(body); httpEntity = new StringEntity(bodyStr); } catch (UnsupportedEncodingException e) { throw PersoniumException.create("error while request body encoding : " + e.getMessage(), 0); } req.setEntity(httpEntity); } debugHttpRequest(req, body); return this.request(req); }
From source file:com.adobe.acs.commons.adobeio.service.impl.EndpointServiceImpl.java
private JsonObject processRequestWithBody(@NotNull final HttpEntityEnclosingRequestBase base, @NotNull final JsonObject payload, String[] headers) throws IOException { StopWatch stopWatch = new StopWatch(); LOGGER.debug("STARTING STOPWATCH processRequestWithBody"); stopWatch.start();//from w w w.j av a 2 s . c om base.setHeader(AUTHORIZATION, BEARER + integrationService.getAccessToken()); base.setHeader(CACHE_CONTRL, NO_CACHE); base.setHeader(X_API_KEY, integrationService.getApiKey()); base.setHeader(CONTENT_TYPE, CONTENT_TYPE_APPLICATION_JSON); if (headers == null || headers.length == 0) { addHeaders(base, specificServiceHeaders); } else { addHeaders(base, convertServiceSpecificHeaders(headers)); } StringEntity input = new StringEntity(payload.toString()); input.setContentType(CONTENT_TYPE_APPLICATION_JSON); if (!base.getClass().isInstance(HttpGet.class)) { base.setEntity(input); } LOGGER.debug("Process call. uri = {}. payload = {}", base.getURI().toString(), payload); try (CloseableHttpClient httpClient = helper.getHttpClient(integrationService.getTimeoutinMilliSeconds())) { CloseableHttpResponse response = httpClient.execute(base); final JsonObject result = responseAsJson(response); LOGGER.debug("STOPPING STOPWATCH processRequestWithBody"); stopWatch.stop(); LOGGER.debug("Stopwatch time processRequestWithBody: {}", stopWatch); stopWatch.reset(); return result; } }
From source file:com.corebase.android.framework.http.client.AsyncHttpClient.java
private HttpEntityEnclosingRequestBase addEntityToRequestBase(HttpEntityEnclosingRequestBase requestBase, HttpEntity entity) {//from ww w . ja va 2s . c om if (entity != null) { requestBase.setEntity(entity); } return requestBase; }
From source file:aajavafx.VisitorController.java
@FXML private void handleSave(ActionEvent event) { if (imageFile != null) { String visitorId = visitorIDField.getText(); visitorIDField.clear();//from w ww. ja v a 2 s .c om String firstName = firstNameField.getText(); firstNameField.clear(); String lastName = lastNameField.getText(); lastNameField.clear(); String email = emailField.getText(); emailField.clear(); String phoneNumber = phoneNumberField.getText(); phoneNumberField.clear(); Integer companyId = getCompanyIDFromName(companyBox.getValue().toString()); try { Gson gson = new Gson(); HttpClient httpClient = HttpClientBuilder.create().build(); HttpEntityEnclosingRequestBase HttpEntity = null; //this is the superclass for post, put, get, etc if (visitorIDField.isEditable()) { //then we are posting a new record HttpEntity = new HttpPost(VisitorsRootURL); //so make a http post object } else { //we are editing a record HttpEntity = new HttpPut(VisitorsRootURL); //so make a http put object } Company company = getCompany(companyId); Visitors visitor = new Visitors(visitorId, firstName, lastName, email, phoneNumber, company); String jsonString = new String(gson.toJson(visitor)); System.out.println("json string: " + jsonString); StringEntity postString = new StringEntity(jsonString); HttpEntity.setEntity(postString); HttpEntity.setHeader("Content-type", "application/json"); HttpResponse response = httpClient.execute(HttpEntity); int statusCode = response.getStatusLine().getStatusCode(); if (statusCode == 204) { System.out.println("New visitor posted successfully"); } else { System.out.println("Server error: " + response.getStatusLine()); } visitorIDField.setEditable(false); firstNameField.setEditable(false); lastNameField.setEditable(false); emailField.setEditable(false); phoneNumberField.setEditable(false); companyBox.setEditable(false); visitorIDField.clear(); firstNameField.clear(); lastNameField.clear(); emailField.clear(); tableVisitors.setItems(getVisitors()); } catch (UnsupportedEncodingException ex) { System.out.println(ex); } catch (IOException e) { System.out.println(e); } catch (JSONException je) { System.out.println("JSON error: " + je); } FileInputStream fis = null; try { fis = new FileInputStream(imageFile); HttpClient httpClient = HttpClientBuilder.create().build(); MultipartEntityBuilder builder = MultipartEntityBuilder.create(); FileBody fileBody = new FileBody(new File(imageFile.getName())); //image should be a String builder.addPart("file", new InputStreamBody(fis, imageFile.getName())); //builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); // server back-end URL HttpPost httppost = new HttpPost(postHTML); //MultipartEntity entity = new MultipartEntity(); // set the file input stream and file name as arguments //entity.addPart("file", new InputStreamBody(fis, inFile.getName())); HttpEntity entity = builder.build(); httppost.setEntity(entity); // execute the request HttpResponse response = httpClient.execute(httppost); int statusCode = response.getStatusLine().getStatusCode(); HttpEntity responseEntity = response.getEntity(); String responseString = EntityUtils.toString(responseEntity, "UTF-8"); System.out.println("[" + statusCode + "] " + responseString); } catch (ClientProtocolException e) { System.err.println("Unable to make connection"); e.printStackTrace(); } catch (IOException e) { System.err.println("Unable to read file"); e.printStackTrace(); } finally { try { if (fis != null) fis.close(); } catch (IOException e) { } } } else { errorLabel.setText("Record Not Saved: Please attach a photo for this visitor"); errorLabel.setVisible(true); } }