List of usage examples for org.apache.http.client.methods HttpPut HttpPut
public HttpPut(final String uri)
From source file:org.sonatype.nexus.repositories.metadata.Hc4RawTransport.java
@Override public void writeRawData(final String path, final byte[] bytes) throws IOException { final HttpPut put = new HttpPut(createUrlWithPath(path)); put.setEntity(new ByteArrayEntity(bytes, ContentType.APPLICATION_XML)); final HttpResponse response = httpClient.execute(put); try {//www .j a v a 2 s . com if (response.getStatusLine().getStatusCode() > 299) { throw new IOException("The response was not successful: " + response.getStatusLine()); } } finally { EntityUtils.consume(response.getEntity()); } }
From source file:at.ac.tuwien.dsg.elasticdaasclient.utils.RestfulWSClient.java
public String callPutMethod(String xmlString) { String rs = ""; try {/*from ww w .j a va 2 s .c o m*/ //HttpGet method = new HttpGet(url); StringEntity inputKeyspace = new StringEntity(xmlString); // Logger.getLogger(RestfulWSClient.class.getName()).log(Level.INFO, "Connection .. " + url); HttpPut request = new HttpPut(url); request.addHeader("content-type", "application/xml; charset=utf-8"); request.addHeader("Accept", "application/xml, multipart/related"); request.setEntity(inputKeyspace); HttpResponse methodResponse = this.getHttpClient().execute(request); int statusCode = methodResponse.getStatusLine().getStatusCode(); // Logger.getLogger(RestfulWSClient.class.getName()).log(Level.INFO, "Status Code: " + statusCode); BufferedReader rd = new BufferedReader(new InputStreamReader(methodResponse.getEntity().getContent())); StringBuilder result = new StringBuilder(); String line; while ((line = rd.readLine()) != null) { result.append(line); } rs = result.toString(); // System.out.println("Response String: " + result.toString()); } catch (Exception ex) { } return rs; }
From source file:fr.liglab.adele.cilia.workbench.restmonitoring.utils.http.HttpHelper.java
public static void put(PlatformID platformID, String target, String data) throws CiliaException { String url = getURL(platformID, target); HttpPut httpRequest = new HttpPut(url); // entity/*from w w w .j a v a2s . c o m*/ StringEntity entity = new StringEntity(data, ContentType.create("text/plain", "UTF-8")); httpRequest.setEntity(entity); // HTTP request HttpClient httpClient = getClient(); try { httpClient.execute(httpRequest, new BasicResponseHandler()); httpClient.getConnectionManager().shutdown(); } catch (Exception e) { httpClient.getConnectionManager().shutdown(); throw new CiliaException("can't perform HTTP PUT request", e); } }
From source file:io.github.data4all.util.upload.ChangesetUtil.java
/** * Creates a {@link HttpPut} request and signs it by writing an OAuth * signature to it./* ww w. ja va 2 s . c o m*/ * * @param user * The {@link User} account to sign the {@link HttpPut} with. * @return A {@link HttpPut} Request. * @throws OsmException * Indicates an failure in an osm progess. */ private static HttpPut getChangeSetPut(User user) throws OsmException { final OAuthParameters params = OAuthParameters.CURRENT; final OAuthConsumer consumer = new CommonsHttpOAuthConsumer(params.getConsumerKey(), params.getConsumerSecret()); consumer.setTokenWithSecret(user.getOAuthToken(), user.getOauthTokenSecret()); final HttpPut httpPut = new HttpPut(params.getScopeUrl() + "api/0.6/changeset/create"); try { consumer.sign(httpPut); } catch (OAuthMessageSignerException e) { throw new OsmException(e); } catch (OAuthExpectationFailedException e) { throw new OsmException(e); } catch (OAuthCommunicationException e) { throw new OsmException(e); } return httpPut; }
From source file:com.imaginary.home.cloud.api.call.LocationCall.java
static public void main(String... args) throws Exception { if (args.length < 1) { System.err.println("You must specify an action"); System.exit(-1);// www . j a va 2s .c om return; } String action = args[0]; if (action.equalsIgnoreCase("initializePairing")) { if (args.length < 5) { System.err.println("You must specify a location ID"); System.exit(-2); return; } String endpoint = args[1]; String locationId = args[2]; String apiKeyId = args[3]; String apiKeySecret = args[4]; HashMap<String, Object> act = new HashMap<String, Object>(); act.put("action", "initializePairing"); HttpParams params = new BasicHttpParams(); HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); //noinspection deprecation HttpProtocolParams.setContentCharset(params, HTTP.UTF_8); HttpProtocolParams.setUserAgent(params, "Imaginary Home"); HttpClient client = new DefaultHttpClient(params); HttpPut method = new HttpPut(endpoint + "/location/" + locationId); long timestamp = System.currentTimeMillis(); method.addHeader("Content-Type", "application/json"); method.addHeader("x-imaginary-version", CloudService.VERSION); method.addHeader("x-imaginary-timestamp", String.valueOf(timestamp)); method.addHeader("x-imaginary-api-key", apiKeyId); method.addHeader("x-imaginary-signature", CloudService.sign(apiKeySecret.getBytes("utf-8"), "put:/location/" + locationId + ":" + apiKeyId + ":" + timestamp + ":" + CloudService.VERSION)); //noinspection deprecation method.setEntity(new StringEntity((new JSONObject(act)).toString(), "application/json", "UTF-8")); HttpResponse response; StatusLine status; try { response = client.execute(method); status = response.getStatusLine(); } catch (IOException e) { e.printStackTrace(); throw new CommunicationException(e); } if (status.getStatusCode() == HttpServletResponse.SC_OK) { String json = EntityUtils.toString(response.getEntity()); JSONObject u = new JSONObject(json); System.out.println((u.has("pairingCode") && !u.isNull("pairingCode")) ? u.getString("pairingCode") : "--no code--"); } else { System.err.println("Failed to initialize pairing (" + status.getStatusCode() + ": " + EntityUtils.toString(response.getEntity())); System.exit(status.getStatusCode()); } } else if (action.equalsIgnoreCase("create")) { if (args.length < 7) { System.err.println("create ENDPOINT NAME DESCRIPTION TIMEZONE API_KEY_ID API_KEY_SECRET"); System.exit(-2); return; } String endpoint = args[1]; String name = args[2]; String description = args[3]; String tz = args[4]; String apiKeyId = args[5]; String apiKeySecret = args[6]; HashMap<String, Object> lstate = new HashMap<String, Object>(); lstate.put("name", name); lstate.put("description", description); lstate.put("timeZone", tz); HttpParams params = new BasicHttpParams(); HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); //noinspection deprecation HttpProtocolParams.setContentCharset(params, HTTP.UTF_8); HttpProtocolParams.setUserAgent(params, "Imaginary Home"); HttpClient client = new DefaultHttpClient(params); HttpPost method = new HttpPost(endpoint + "/location"); long timestamp = System.currentTimeMillis(); System.out.println( "Signing: " + "post:/location:" + apiKeyId + ":" + timestamp + ":" + CloudService.VERSION); method.addHeader("Content-Type", "application/json"); method.addHeader("x-imaginary-version", CloudService.VERSION); method.addHeader("x-imaginary-timestamp", String.valueOf(timestamp)); method.addHeader("x-imaginary-api-key", apiKeyId); method.addHeader("x-imaginary-signature", CloudService.sign(apiKeySecret.getBytes("utf-8"), "post:/location:" + apiKeyId + ":" + timestamp + ":" + CloudService.VERSION)); //noinspection deprecation method.setEntity(new StringEntity((new JSONObject(lstate)).toString(), "application/json", "UTF-8")); HttpResponse response; StatusLine status; try { response = client.execute(method); status = response.getStatusLine(); } catch (IOException e) { e.printStackTrace(); throw new CommunicationException(e); } if (status.getStatusCode() == HttpServletResponse.SC_CREATED) { String json = EntityUtils.toString(response.getEntity()); JSONObject u = new JSONObject(json); System.out.println((u.has("locationId") && !u.isNull("locationId")) ? u.getString("locationId") : "--no location--"); } else { System.err.println("Failed to create location (" + status.getStatusCode() + ": " + EntityUtils.toString(response.getEntity())); System.exit(status.getStatusCode()); } } else { System.err.println("No such action: " + action); System.exit(-3); } }
From source file:org.bishoph.oxdemo.util.CreateTaskAction.java
@Override protected JSONObject doInBackground(Object... params) { try {/* www.j ava 2s .c om*/ String uri = (String) params[0]; String title = (String) params[1]; if (title == null && folder_id > 0) { Log.v("OXDemo", "Either title or folder_id missing. Done nothing!"); return null; } Log.v("OXDemo", "Attempting to create task " + title + " on " + uri); JSONObject jsonobject = new JSONObject(); jsonobject.put("folder_id", folder_id); jsonobject.put("title", title); jsonobject.put("status", 1); jsonobject.put("priority", 0); jsonobject.put("percent_completed", 0); jsonobject.put("recurrence_type", 0); jsonobject.put("private_flag", false); jsonobject.put("notification", false); Log.v("OXDemo", "Body = " + jsonobject.toString()); HttpPut httpput = new HttpPut(uri); StringEntity stringentity = new StringEntity(jsonobject.toString(), HTTP.UTF_8); stringentity.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json;charset=UTF-8")); httpput.setHeader("Accept", "application/json, text/javascript"); httpput.setHeader("Content-type", "application/json"); httpput.setEntity(stringentity); HttpResponse response = httpclient.execute(httpput, localcontext); Log.v("OXDemo", "Created task " + title); HttpEntity entity = response.getEntity(); String result = EntityUtils.toString(entity); Log.d("OXDemo", "<<<<<<<\n" + result + "\n\n"); JSONObject jsonObj = new JSONObject(result); jsonObj.put("title", title); return jsonObj; } catch (JSONException e) { Log.e("OXDemo", e.getMessage()); } catch (IOException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } return null; }
From source file:gov.nih.nci.system.web.client.RESTfulCreateClient.java
public Response create(File fileLoc, String url) { try {/*w w w. j a va2 s. c o m*/ if (url == null) { ResponseBuilder builder = Response.status(Status.BAD_REQUEST); builder.type("application/xml"); StringBuffer buffer = new StringBuffer(); buffer.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>"); buffer.append("<response>"); buffer.append("<type>ERROR</type>"); buffer.append("<code>INVALID_URL</code>"); buffer.append("<message>Invalid URL: " + url + "</message>"); buffer.append("</response>"); builder.entity(buffer.toString()); return builder.build(); } if (fileLoc == null || !fileLoc.exists()) { ResponseBuilder builder = Response.status(Status.BAD_REQUEST); builder.type("application/xml"); StringBuffer buffer = new StringBuffer(); buffer.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>"); buffer.append("<response>"); buffer.append("<type>ERROR</type>"); buffer.append("<code>INVALID_FILE</code>"); buffer.append("<message>Invalid File given to read</message>"); buffer.append("</response>"); builder.entity(buffer.toString()); return builder.build(); } DefaultHttpClient httpClient = new DefaultHttpClient(); HttpPut putRequest = new HttpPut(url); FileEntity input = new FileEntity(fileLoc); input.setContentType("application/xml"); if (userName != null && password != null) { String base64encodedUsernameAndPassword = new String( Base64.encodeBase64((userName + ":" + password).getBytes())); putRequest.addHeader("Authorization", "Basic " + base64encodedUsernameAndPassword); } putRequest.setEntity(input); HttpResponse response = httpClient.execute(putRequest); BufferedReader br = new BufferedReader(new InputStreamReader((response.getEntity().getContent()))); String output; StringBuffer buffer = new StringBuffer(); buffer.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>"); buffer.append("<response>"); while ((output = br.readLine()) != null) { buffer.append(output); } ResponseBuilder builder = Response.status(Status.CREATED); builder.type("application/xml"); buffer.append("</response>"); builder.entity(buffer.toString()); httpClient.getConnectionManager().shutdown(); return builder.build(); } catch (Exception e) { e.printStackTrace(); } return null; }
From source file:com.amazonaws.devicefarm.DeviceFarmUploader.java
/** * Upload a single file, waits for upload to complete. * @param file the file/* ww w.ja v a 2 s. c o m*/ * @param project the project * @param uploadType the upload type * @return upload object */ public Upload upload(final File file, final Project project, final UploadType uploadType) { if (!(file.exists() && file.canRead())) { throw new DeviceFarmException(String.format("File %s does not exist or is not readable", file)); } final CreateUploadRequest appUploadRequest = new CreateUploadRequest().withName(file.getName()) .withProjectArn(project.getArn()).withContentType("application/octet-stream") .withType(uploadType.toString()); final Upload upload = api.createUpload(appUploadRequest).getUpload(); final CloseableHttpClient httpClient = HttpClients.createDefault(); final HttpPut httpPut = new HttpPut(upload.getUrl()); httpPut.setHeader("Content-Type", upload.getContentType()); final FileEntity entity = new FileEntity(file); httpPut.setEntity(entity); writeToLog(String.format("Uploading %s to S3", file.getName())); final HttpResponse response; try { response = httpClient.execute(httpPut); } catch (IOException e) { throw new DeviceFarmException(String.format("Error uploading artifact %s", file), e); } if (response.getStatusLine().getStatusCode() != 200) { throw new DeviceFarmException(String.format("Upload returned non-200 responses: %s", response.getStatusLine().getStatusCode())); } waitForUpload(file, upload); return upload; }
From source file:net.oauth.client.httpclient4.HttpClient4.java
public HttpResponseMessage execute(HttpMessage request, Map<String, Object> parameters) throws IOException { final String method = request.method; final String url = request.url.toExternalForm(); final InputStream body = request.getBody(); final boolean isDelete = DELETE.equalsIgnoreCase(method); final boolean isPost = POST.equalsIgnoreCase(method); final boolean isPut = PUT.equalsIgnoreCase(method); byte[] excerpt = null; HttpRequestBase httpRequest;/* w w w . j ava 2 s . com*/ if (isPost || isPut) { HttpEntityEnclosingRequestBase entityEnclosingMethod = isPost ? new HttpPost(url) : new HttpPut(url); if (body != null) { ExcerptInputStream e = new ExcerptInputStream(body); excerpt = e.getExcerpt(); String length = request.removeHeaders(HttpMessage.CONTENT_LENGTH); entityEnclosingMethod .setEntity(new InputStreamEntity(e, (length == null) ? -1 : Long.parseLong(length))); } httpRequest = entityEnclosingMethod; } else if (isDelete) { httpRequest = new HttpDelete(url); } else { httpRequest = new HttpGet(url); } for (Map.Entry<String, String> header : request.headers) { httpRequest.addHeader(header.getKey(), header.getValue()); } HttpParams params = httpRequest.getParams(); for (Map.Entry<String, Object> p : parameters.entrySet()) { String name = p.getKey(); String value = p.getValue().toString(); if (FOLLOW_REDIRECTS.equals(name)) { params.setBooleanParameter(ClientPNames.HANDLE_REDIRECTS, Boolean.parseBoolean(value)); } else if (READ_TIMEOUT.equals(name)) { params.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, Integer.parseInt(value)); } else if (CONNECT_TIMEOUT.equals(name)) { params.setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, Integer.parseInt(value)); } } HttpClient client = clientPool.getHttpClient(new URL(httpRequest.getURI().toString())); HttpResponse httpResponse = client.execute(httpRequest); return new HttpMethodResponse(httpRequest, httpResponse, excerpt, request.getContentCharset()); }