List of usage examples for org.apache.http.client.methods HttpPut setEntity
public void setEntity(final HttpEntity entity)
From source file:dk.kk.ibikecphlib.util.HttpUtils.java
public static JsonNode putToServer(String urlString, JSONObject objectToPost) { JsonNode ret = null;//ww w .j a v a 2s. c om LOG.d("PUT api request, url = " + urlString); HttpParams myParams = new BasicHttpParams(); HttpConnectionParams.setConnectionTimeout(myParams, CONNECTON_TIMEOUT); HttpConnectionParams.setSoTimeout(myParams, CONNECTON_TIMEOUT); HttpClient httpclient = new DefaultHttpClient(myParams); httpclient.getParams().setParameter(CoreProtocolPNames.USER_AGENT, Config.USER_AGENT); HttpPut httput = null; URL url = null; try { url = new URL(urlString); httput = new HttpPut(url.toString()); httput.setHeader("Content-type", "application/json"); httput.setHeader("Accept", ACCEPT); httput.setHeader("LANGUAGE_CODE", IBikeApplication.getLanguageString()); StringEntity se = new StringEntity(objectToPost.toString(), HTTP.UTF_8); se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json")); httput.setEntity(se); HttpResponse response = httpclient.execute(httput); String serverResponse = EntityUtils.toString(response.getEntity()); LOG.d("API response = " + serverResponse); ret = Util.stringToJsonNode(serverResponse); } catch (Exception e) { if (e != null && e.getLocalizedMessage() != null) { LOG.e(e.getLocalizedMessage()); } } return ret; }
From source file:co.cask.cdap.internal.app.services.http.AppFabricTestBase.java
protected static HttpResponse doPut(String resource, String body) throws Exception { DefaultHttpClient client = new DefaultHttpClient(); HttpPut put = new HttpPut(getEndPoint(resource)); if (body != null) { put.setEntity(new StringEntity(body)); }//from w ww .j a v a 2 s . c om put.setHeader(AUTH_HEADER); return client.execute(put); }
From source file:test.java.ecplugins.weblogic.TestUtils.java
public static void setResourceAndWorkspace(String resourceName, String workspaceName, String pluginName) throws Exception { props = getProperties();//from w w w . j a v a2 s . c o m HttpClient httpClient = new DefaultHttpClient(); JSONObject jo = new JSONObject(); jo.put("projectName", pluginName); jo.put("resourceName", resourceName); jo.put("workspaceName", workspaceName); HttpPut httpPutRequest = new HttpPut("http://" + props.getProperty(StringConstants.COMMANDER_SERVER) + ":8000/rest/v1.0/projects/" + pluginName); String encoding = new String( org.apache.commons.codec.binary.Base64.encodeBase64(org.apache.commons.codec.binary.StringUtils .getBytesUtf8(props.getProperty(StringConstants.COMMANDER_USER) + ":" + props.getProperty(StringConstants.COMMANDER_PASSWORD)))); StringEntity input = new StringEntity(jo.toString()); input.setContentType("application/json"); httpPutRequest.setEntity(input); httpPutRequest.setHeader("Authorization", "Basic " + encoding); HttpResponse httpResponse = httpClient.execute(httpPutRequest); if (httpResponse.getStatusLine().getStatusCode() >= 400) { throw new RuntimeException("Failed to set resource " + resourceName + " to project " + pluginName); } System.out.println("Set the resource as " + resourceName + " and workspace as " + workspaceName + " successfully for " + pluginName); }
From source file:com.lostad.app.base.util.RequestUtil.java
public static String putForm(String url, List<NameValuePair> params, String token, boolean isSingleton) throws Exception { String json = null;//from w w w. j a v a 2 s . c o m HttpClient client = HttpClientManager.getHttpClient(isSingleton); HttpEntity resEntity = null; HttpPut put = new HttpPut(url); put.addHeader("token", token); try { put.addHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8"); if (params != null) { UrlEncodedFormEntity entity = new UrlEncodedFormEntity(params, HTTP.UTF_8); if (params != null) { entity.setContentEncoding(HTTP.UTF_8); entity.setContentType("application/x-www-form-urlencoded"); } put.setEntity(entity); } HttpResponse response = client.execute(put, new BasicHttpContext()); resEntity = response.getEntity(); if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {// 200 // ? json = EntityUtils.toString(resEntity); } } catch (Exception e) { if (put != null) { put.abort();// } throw e; } finally { if (resEntity != null) { try { resEntity.consumeContent();//? } catch (IOException e) { e.printStackTrace(); } } client.getConnectionManager().closeExpiredConnections(); ///client.getConnectionManager().shutdown(); } return json; }
From source file:com.optimusinfo.elasticpath.cortex.common.Utils.java
public static int putRequest(String deleteUrl, JSONObject requestBody, String accessToken, String contentType, String contentTypeString, String authorizationString, String accessTokenInitializer) { // Making HTTP request try {//from www . j a va 2 s.c o m DefaultHttpClient httpClient = new DefaultHttpClient(); Log.i("PUT REQUEST", deleteUrl); HttpPut httpPut = new HttpPut(deleteUrl); httpPut.setHeader(contentTypeString, contentType); httpPut.setHeader(authorizationString, accessTokenInitializer + " " + accessToken); if (requestBody != null) { StringEntity requestEntity = new StringEntity(requestBody.toString()); requestEntity.setContentEncoding("UTF-8"); requestEntity.setContentType(contentType); httpPut.setEntity(requestEntity); } HttpResponse httpResponse = httpClient.execute(httpPut); return httpResponse.getStatusLine().getStatusCode(); } catch (ClientProtocolException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return 0; }
From source file:com.ibm.team.build.internal.hjplugin.util.HttpUtils.java
/** * Perform PUT request against an RTC server * @param serverURI The RTC server/*from w w w .ja va 2 s .c o m*/ * @param uri The relative URI for the PUT. It is expected that it is already encoded if necessary. * @param userId The userId to authenticate as * @param password The password to authenticate with * @param timeout The timeout period for the connection (in seconds) * @param json The JSON object to put to the RTC server * @param httpContext The context from the login if cycle is being managed by the caller * Otherwise <code>null</code> and this call will handle the login. * @param listener The listener to report errors to. * May be <code>null</code> if there is no listener. * @return The HttpContext for the request. May be reused in subsequent requests * for the same user * @throws IOException Thrown if things go wrong * @throws InvalidCredentialsException * @throws GeneralSecurityException */ public static HttpClientContext performPut(String serverURI, String uri, String userId, String password, int timeout, final JSONObject json, HttpClientContext httpContext, TaskListener listener) throws IOException, InvalidCredentialsException, GeneralSecurityException { CloseableHttpClient httpClient = getClient(); // How to fill the request body (Clone doesn't work) ContentProducer cp = new ContentProducer() { public void writeTo(OutputStream outstream) throws IOException { Writer writer = new OutputStreamWriter(outstream, UTF_8); json.write(writer); writer.flush(); } }; HttpEntity entity = new EntityTemplate(cp); String fullURI = getFullURI(serverURI, uri); HttpPut put = getPUT(fullURI, timeout); put.setEntity(entity); if (httpContext == null) { httpContext = createHttpContext(); } LOGGER.finer("PUT: " + put.getURI()); //$NON-NLS-1$ CloseableHttpResponse response = httpClient.execute(put, httpContext); try { // based on the response do any authentication. If authentication requires // the request to be performed again (i.e. Basic auth) re-issue request response = authenticateIfRequired(response, httpClient, httpContext, serverURI, userId, password, timeout, listener); // retry put request if we have to do authentication if (response == null) { put = getPUT(fullURI, timeout); put.setEntity(entity); response = httpClient.execute(put, httpContext); } int statusCode = response.getStatusLine().getStatusCode(); if (statusCode == 401) { // It is an unusual case to get here (in our current work flow) because it means // the user has become unauthenticated since the previous request // (i.e. the get of the value about to put back) throw new InvalidCredentialsException(Messages.HttpUtils_authentication_failed(userId, serverURI)); } else { int responseClass = statusCode / 100; if (responseClass != 2) { if (listener != null) { listener.fatalError(Messages.HttpUtils_PUT_failed(fullURI, statusCode)); } throw logError(fullURI, response, Messages.HttpUtils_PUT_failed(fullURI, statusCode)); } return httpContext; } } finally { closeResponse(response); } }
From source file:com.couchbase.cbadmin.client.CouchbaseAdmin.java
/** * Add a view to the bucket. This is an extension API and is not strictly * administrative./* w ww. j a v a 2s. c o m*/ * @param ep The node to use for creating the view. * @param config The configuration object defining the view to be created * @param pollTimeout time to wait until the view becomes ready, in millis. * @throws RestApiException */ static public void defineView(Node ep, ViewConfig config, long pollTimeout) throws RestApiException { // Make a 'PUT' request here.. CouchbaseAdmin adm = new CouchbaseAdmin(ep.getCouchUrl(), config.getBucketName(), config.getBucketPassword()); // Format the URI StringBuilder ub = new StringBuilder().append('/').append(config.getBucketName()).append("/_design/") .append(config.getDesign()); HttpPut req = new HttpPut(); req.setHeader("Content-Type", "application/json"); try { req.setEntity(new StringEntity(config.getDefinition())); } catch (UnsupportedEncodingException ex) { throw new RestApiException(ex); } try { adm.getResponseJson(req, ub.toString(), 201); } catch (IOException ex) { throw new RestApiException(ex); } if (pollTimeout > 0) { Collection<String> vNames = config.getViewNames(); if (vNames == null || vNames.isEmpty()) { throw new IllegalArgumentException("No views defined"); } String vName = vNames.iterator().next(); long tmo = System.currentTimeMillis() + pollTimeout; String vUri = String.format("%s/_design/%s/_view/%s?limit=1", config.getBucketName(), config.getDesign(), vName); while (System.currentTimeMillis() < tmo) { try { adm.getJson(vUri); return; } catch (IOException ex) { throw new RestApiException(ex); } catch (RestApiException ex) { if (ex.getStatusLine() == null) { throw ex; } int statusCode = ex.getStatusLine().getStatusCode(); if (statusCode != 500 && statusCode != 404) { throw ex; } adm.logger.trace("While waiting for view", ex); // Squash } try { Thread.sleep(500); } catch (InterruptedException ex) { adm.logger.error("While waiting.", ex); break; } } throw new RestApiException("Timed out waiting for view"); } }
From source file:org.apache.cloudstack.storage.datastore.util.DateraUtil.java
public static void updateAppInstanceAdminState(DateraObject.DateraConnection conn, String appInstanceName, DateraObject.AppState appState) throws UnsupportedEncodingException, DateraObject.DateraError { DateraObject.AppInstance appInstance = new DateraObject.AppInstance(appState); HttpPut updateAppInstanceReq = new HttpPut(generateApiUrl("app_instances", appInstanceName)); updateAppInstanceReq.setEntity(new StringEntity(gson.toJson(appInstance))); executeApiRequest(conn, updateAppInstanceReq); }
From source file:edu.jhu.pha.vospace.storage.SwiftKeystoneStorageManager.java
public static String storeStreamedObject(String container, InputStream data, String contentType, String name, Map<String, String> metadata) throws IOException, HttpException, FilesException { String objName = name;//from w ww. j av a2s .c om if (isValidContainerName(container) && FilesClient.isValidObjectName(objName)) { HttpPut method = new HttpPut( getFileUrl + "/" + sanitizeForURI(container) + "/" + sanitizeForURI(objName)); method.getParams().setIntParameter("http.socket.timeout", connectionTimeOut); method.setHeader(FilesConstants.X_AUTH_TOKEN, strToken); InputStreamEntity entity = new InputStreamEntity(data, -1); entity.setChunked(true); entity.setContentType(contentType); method.setEntity(entity); for (String key : metadata.keySet()) { method.setHeader(FilesConstants.X_OBJECT_META + key, sanitizeForURI(metadata.get(key))); } method.removeHeaders("Content-Length"); try { FilesResponse response = new FilesResponse(client.execute(method)); if (response.getStatusCode() == HttpStatus.SC_CREATED) { return response.getResponseHeader(FilesConstants.E_TAG).getValue(); } else { logger.error(response.getStatusLine()); throw new FilesException("Unexpected result", response.getResponseHeaders(), response.getStatusLine()); } } finally { method.abort(); } } else { if (!FilesClient.isValidObjectName(objName)) { throw new FilesInvalidNameException(objName); } else { throw new FilesInvalidNameException(container); } } }
From source file:com.fpmislata.clientecategoriasjson.ClienteClienteTest.java
private static Cliente updateCliente(String url, Cliente cliente) throws IOException { // Crea el cliente para realizar la conexion DefaultHttpClient httpClient = new DefaultHttpClient(); // Crea el mtodo con el que va a realizar la operacion HttpPut httpPut = new HttpPut(url); // Aade las cabeceras al metodo httpPut.addHeader("accept", "application/json; charset=UTF-8"); httpPut.addHeader("Content-type", "application/json; charset=UTF-8"); // Creamos el objeto Gson que parsear los objetos a JSON, excluyendo los que no tienen la anotacion @Expose Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create(); // Parseamos el objeto a String String jsonString = gson.toJson(cliente); // Construimos el objeto StringEntity indicando que su juego de caracteres es UTF-8 StringEntity input = new StringEntity(jsonString, "UTF-8"); // Indicamos que su tipo MIME es JSON input.setContentType("application/json"); // Asignamos la entidad al metodo con el que trabajamos httpPut.setEntity(input); // Invocamos el servicio rest y obtenemos la respuesta HttpResponse response = httpClient.execute(httpPut); // Comprobamos si ha fallado // Devolvemos el resultado String clienteResult = readObject(response); return gson.fromJson(clienteResult, Cliente.class); }