List of usage examples for org.apache.http.client.methods HttpPut setEntity
public void setEntity(final HttpEntity entity)
From source file:org.changhong.sync.web.AnonymousConnection.java
@Override public String put(String uri, String data) throws UnknownHostException { // Prepare a request object HttpPut httpPut = new HttpPut(uri); try {/* www. j ava2 s . co m*/ // The default http content charset is ISO-8859-1, JSON requires UTF-8 httpPut.setEntity(new StringEntity(data, "UTF-8")); } catch (UnsupportedEncodingException e1) { e1.printStackTrace(); return null; } httpPut.setHeader("Content-Type", "application/json"); httpPut.addHeader("X-Tomboy-Client", Tomdroid.HTTP_HEADER); HttpResponse response = execute(httpPut); return parseResponse(response); }
From source file:com.servioticy.restclient.RestClient.java
public FutureRestResponse restRequest(String url, String body, int method, Map<String, String> headers) throws RestClientException, RestClientErrorCodeException { HttpRequestBase httpMethod;// w ww .j a v a2 s. c o m StringEntity input; switch (method) { case POST: try { input = new StringEntity(body); } catch (UnsupportedEncodingException e) { logger.error(e.getMessage()); throw new RestClientException(e.getMessage()); } input.setContentType("application/json"); HttpPost httpPost = new HttpPost(url); httpPost.setEntity(input); httpMethod = httpPost; break; case PUT: try { input = new StringEntity(body); } catch (UnsupportedEncodingException e) { logger.error(e.getMessage()); throw new RestClientException(e.getMessage()); } input.setContentType("application/json"); HttpPut httpPut = new HttpPut(url); httpPut.setEntity(input); httpMethod = httpPut; break; case DELETE: httpMethod = new HttpDelete(url); break; case GET: httpMethod = new HttpGet(url); break; default: return null; } if (headers != null) { for (Map.Entry<String, String> header : headers.entrySet()) { httpMethod.addHeader(header.getKey(), header.getValue()); } } Future<HttpResponse> response; try { response = httpClient.execute(httpMethod, null); } catch (Exception e) { logger.error(e.getMessage()); throw new RestClientException(e.getMessage()); } // TODO Check the errors nicely FutureRestResponse rr = new FutureRestResponse(response); return rr; }
From source file:com.spotify.helios.serviceregistration.skydns.MiniEtcdClient.java
Future<HttpResponse> set(final String key, final String value, final Integer ttl) { final List<BasicNameValuePair> data = Lists.newArrayList(); data.add(new BasicNameValuePair("value", value)); if (ttl != null) { data.add(new BasicNameValuePair("ttl", Integer.toString(ttl))); }/*from w w w. j a v a 2 s . co m*/ final URI uri = URI.create(baseUri + key); final HttpPut request = new HttpPut(uri); request.setEntity(new UrlEncodedFormEntity(data, Charsets.UTF_8)); return httpClient.execute(request, new FutureCallback<HttpResponse>() { @Override public void cancelled() { log.warn("Attempt to set {} to {} was cancelled", key, value); } @Override public void completed(HttpResponse arg0) { log.info("Succeeded setting {} to {}", key, value); } @Override public void failed(Exception e) { log.warn("Failed setting {} to {}", key, value, e); } }); }
From source file:org.apache.camel.component.cxf.jaxrs.CxfRsConsumerWithBeanTest.java
private void sendPutRequest(String uri) throws Exception { HttpPut put = new HttpPut(uri); StringEntity entity = new StringEntity("string"); entity.setContentType("text/plain"); put.setEntity(entity); CloseableHttpClient httpclient = HttpClientBuilder.create().build(); try {// w w w . j av a 2s . co m HttpResponse response = httpclient.execute(put); assertEquals(200, response.getStatusLine().getStatusCode()); assertEquals("c20string", EntityUtils.toString(response.getEntity())); } finally { httpclient.close(); } }
From source file:revServTest.IoTTestForPUT.java
public String testPut(String url0, StringEntity input) { String result;/*from w w w .j ava 2 s .c om*/ HttpResponse response = null; try { DefaultHttpClient httpClient = new DefaultHttpClient(); HttpPut putRequest = new HttpPut(url0); input.setContentType("application/xml"); putRequest.setEntity(input); response = httpClient.execute(putRequest); if (response.getStatusLine().getStatusCode() != 409 && response.getStatusLine().getStatusCode() != 201 && response.getStatusLine().getStatusCode() != 400 && response.getStatusLine().getStatusCode() != 200 && response.getStatusLine().getStatusCode() != 404 && response.getStatusLine().getStatusCode() != 500) { throw new RuntimeException( "Failed : HTTP error code : " + response.getStatusLine().getStatusCode()); } BufferedReader br = new BufferedReader(new InputStreamReader((response.getEntity().getContent()))); String output; System.out.println("Output from Server .... \n"); while ((output = br.readLine()) != null) { System.out.println(output); } httpClient.getConnectionManager().shutdown(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } // if (response.getStatusLine().getStatusCode() == 409 || response.getStatusLine().getStatusCode() == 201 || response.getStatusLine().getStatusCode() == 400 // || response.getStatusLine().getStatusCode() == 200 || response.getStatusLine().getStatusCode() == 404 || response.getStatusLine().getStatusCode() == 500) { // // result = RevocationOutCome.code; // // } else { // String res = Integer.toString(response.getStatusLine().getStatusCode()); // result = res; // } // return result; return RevocationOutCome.code; }
From source file:org.sonatype.spice.zapper.client.hc4.Hc4Client.java
@Override public State upload(final Payload payload, final Hc4Track track) throws IOException { final String url = getRemoteUrl() + payload.getPath().stringValue(); final HttpPut put = new HttpPut(url); if (payload instanceof SegmentPayload) { put.setEntity(new ZapperEntity(payload, getParameters().getCodecSelector() .selectCodecs(SegmentPayload.class.cast(payload).getSegment().getZFile()))); } else {//from w w w.ja va 2 s .c om put.setEntity(new ZapperEntity(payload)); } put.addHeader("X-Zapper-Transfer-ID", payload.getTransferIdentifier().stringValue()); if (track != null) { put.addHeader("X-Zapper-Track-ID", track.getIdentifier().stringValue()); } final HttpClientContext context = new HttpClientContext(); if (preemptiveCredentialsProvider != null) { context.setCredentialsProvider(preemptiveCredentialsProvider); context.setAuthCache(new BasicAuthCache()); context.getAuthCache().put( new HttpHost(put.getURI().getHost(), put.getURI().getPort(), put.getURI().getScheme()), new BasicScheme()); } final HttpResponse response = httpClient.execute(put, context); final StatusLine statusLine = response.getStatusLine(); EntityUtils.consume(response.getEntity()); if (!(statusLine.getStatusCode() > 199 && statusLine.getStatusCode() < 299)) { throw new IOException(String.format("Unexpected server response: %s %s", statusLine.getStatusCode(), statusLine.getReasonPhrase())); } return State.SUCCESS; }
From source file:org.apache.cloudstack.storage.datastore.util.DateraUtil.java
public static void updateAppInstanceSize(DateraObject.DateraConnection conn, String appInstanceName, int newSize) throws UnsupportedEncodingException, DateraObject.DateraError { try {/* w w w.j a v a 2 s . co m*/ updateAppInstanceAdminState(conn, appInstanceName, DateraObject.AppState.OFFLINE); HttpPut url = new HttpPut(generateApiUrl("app_instances", appInstanceName, "storage_instances", DateraObject.DEFAULT_STORAGE_NAME, "volumes", DateraObject.DEFAULT_VOLUME_NAME)); DateraObject.Volume volume = new DateraObject.Volume(newSize); url.setEntity(new StringEntity(gson.toJson(volume))); executeApiRequest(conn, url); } finally { // bring it back online if something bad happened try { updateAppInstanceAdminState(conn, appInstanceName, DateraObject.AppState.ONLINE); } catch (Exception e) { s_logger.warn("Error getting appInstance " + appInstanceName + " back online ", e); } } }
From source file:org.apache.taverna.activities.rest.HTTPRequestHandler.java
private static HTTPRequestResponse doPUT(ClientConnectionManager connectionManager, String requestURL, RESTActivityConfigurationBean configBean, Object inputMessageBody, Map<String, String> urlParameters, CredentialsProvider credentialsProvider) { HttpPut httpPut = new HttpPut(requestURL); if (!configBean.getContentTypeForUpdates().isEmpty()) httpPut.setHeader(CONTENT_TYPE_HEADER_NAME, configBean.getContentTypeForUpdates()); try {/*from w w w. j a v a 2s .c o m*/ HttpEntity entity = null; if (inputMessageBody == null) { entity = new StringEntity(""); } else if (configBean.getOutgoingDataFormat() == DATA_FORMAT.String) { entity = new StringEntity((String) inputMessageBody); } else { entity = new ByteArrayEntity((byte[]) inputMessageBody); } httpPut.setEntity(entity); } catch (UnsupportedEncodingException e) { return new HTTPRequestResponse(new Exception("Error occurred while trying to " + "attach a message body to the PUT request. See attached cause of this " + "exception for details.")); } return performHTTPRequest(connectionManager, httpPut, configBean, urlParameters, credentialsProvider); }
From source file:com.google.devtools.build.lib.remote.blobstore.RestBlobStore.java
private void put(String urlPrefix, String key, HttpEntity entity) throws IOException { HttpClient client = clientFactory.build(); HttpPut put = new HttpPut(baseUrl + "/" + urlPrefix + "/" + key); put.setEntity(entity); client.execute(put, (response) -> { int statusCode = response.getStatusLine().getStatusCode(); // Accept more than SC_OK to be compatible with Nginx WebDav module. if (HttpStatus.SC_OK != statusCode && HttpStatus.SC_ACCEPTED != statusCode && HttpStatus.SC_CREATED != statusCode && HttpStatus.SC_NO_CONTENT != statusCode) { throw new IOException("PUT failed with status code " + statusCode); }/* w w w . jav a2 s . co m*/ return null; }); }
From source file:com.lovbomobile.android.locsy.client.impl.RestLocsyClient.java
private HttpPut getHttpPutRequestForSendingLocation(String url, String jsonLocation) throws UnsupportedEncodingException { HttpPut httpPut = new HttpPut(url); httpPut.setEntity(new StringEntity(jsonLocation)); httpPut.addHeader(HEADER_FIELD_CONTENT_TYPE, MIME_TYPE_JSON); httpPut.addHeader(HEADER_FIELD_ACCEPT, MIME_TYPE_JSON); HttpParams httpParams = new BasicHttpParams(); HttpConnectionParams.setConnectionTimeout(httpParams, DEFAULT_TIMEOUT); httpPut.setParams(httpParams);/*from www . j a v a 2 s. c om*/ return httpPut; }