List of usage examples for org.apache.http.client.methods HttpPut HttpPut
public HttpPut(final String uri)
From source file:org.fcrepo.integration.http.api.AbstractResourceIT.java
protected static HttpPut putObjMethod(final String id) { return new HttpPut(serverAddress + id); }
From source file:com.github.dziga.orest.client.HttpRestClient.java
int Put(String body) throws IOException, URISyntaxException { URIBuilder b = new URIBuilder().setScheme(scheme).setHost(host).setPath(path); addQueryParams(b);//from ww w. j av a 2 s . c o m URI fullUri = b.build(); HttpPut putMethod = new HttpPut(fullUri); HttpEntity entity = new StringEntity(body); putMethod.setEntity(entity); putMethod = (HttpPut) addHeadersToMethod(putMethod); processResponse(httpClient.execute(putMethod)); return getResponseCode(); }
From source file:IoTatWork.NotifyResolutionManager.java
/** * //from w w w . ja va2 s .co m * @param notification * @return */ private boolean sendNotification(PendingResolutionNotification notification) { String xmlString = notification.toXML(); String revocationPut = notification.getNotificationUrl() + notification.getRevocationHash(); System.out.println("\nProcessing notification: " + revocationPut + "\n" + notification.toXML()); // TODO logEvent //IoTatWorkApplication.logger.info("Sending pending resolution notification: "+revocationPut); IoTatWorkApplication.logger.info(LogMessage.SEND_RESOLUTION_NOTIFICATION + revocationPut); DefaultHttpClient httpClient = new DefaultHttpClient(); HttpPut putRequest = new HttpPut(revocationPut); try { StringEntity input = new StringEntity(xmlString); input.setContentType("application/xml"); putRequest.setEntity(input); HttpResponse response = httpClient.execute(putRequest); int statusCode = response.getStatusLine().getStatusCode(); switch (statusCode) { case 200: IoTatWorkApplication.logger.info(LogMessage.RESOLUTION_NOTIFICATION_RESPONSE_STATUSCODE_200); break; case 400: BufferedReader br = new BufferedReader(new InputStreamReader((response.getEntity().getContent()))); String output = br.toString(); /* while ((output = br.readLine()) != null) { System.out.println(output); } */ JsonParser parser = new JsonParser(); JsonObject jsonObj = (JsonObject) parser.parse(output); String code = jsonObj.get(JSON_PROCESSING_STATUS_CODE).getAsString(); if (code.equals("NPR400")) { IoTatWorkApplication.logger.info(LogMessage.RESOLUTION_NOTIFICATION_RESPONSE_STATUSCODE_400); } else if (code.equals("NPR450")) { IoTatWorkApplication.logger.info(LogMessage.RESOLUTION_NOTIFICATION_RESPONSE_STATUSCODE_450); } else if (code.equals("NPR451")) { IoTatWorkApplication.logger.info(LogMessage.RESOLUTION_NOTIFICATION_RESPONSE_STATUSCODE_451); } break; case 404: IoTatWorkApplication.logger.info(LogMessage.RESOLUTION_NOTIFICATION_RESPONSE_STATUSCODE_404); break; case 500: IoTatWorkApplication.logger.info(LogMessage.RESOLUTION_NOTIFICATION_RESPONSE_STATUSCODE_500); break; default: break; } httpClient.getConnectionManager().shutdown(); } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ClientProtocolException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return true; }
From source file:com.meplato.store2.ApacheHttpClient.java
/** * Execute runs a HTTP request/response with an API endpoint. * * @param method the HTTP method, e.g. POST or GET * @param uriTemplate the URI template according to RFC 6570 * @param parameters the query string parameters * @param headers the key/value pairs for the HTTP header * @param body the body of the request or {@code null} * @return the HTTP response encapsulated by {@link Response}. * @throws ServiceException if e.g. the service is unavailable. *//*from www .ja va2 s .c om*/ @Override public Response execute(String method, String uriTemplate, Map<String, Object> parameters, Map<String, String> headers, Object body) throws ServiceException { // URI template parameters String url = UriTemplate.fromTemplate(uriTemplate).expand(parameters); // Body HttpEntity requestEntity = null; if (body != null) { Gson gson = getSerializer(); try { requestEntity = EntityBuilder.create().setText(gson.toJson(body)).setContentEncoding("UTF-8") .setContentType(ContentType.APPLICATION_JSON).build(); } catch (Exception e) { throw new ServiceException("Error serializing body", null, e); } } // Do HTTP request HttpRequestBase httpRequest = null; if (method.equalsIgnoreCase("GET")) { httpRequest = new HttpGet(url); } else if (method.equalsIgnoreCase("POST")) { HttpPost httpPost = new HttpPost(url); if (requestEntity != null) { httpPost.setEntity(requestEntity); } httpRequest = httpPost; } else if (method.equalsIgnoreCase("PUT")) { HttpPut httpPut = new HttpPut(url); if (requestEntity != null) { httpPut.setEntity(requestEntity); } httpRequest = httpPut; } else if (method.equalsIgnoreCase("DELETE")) { httpRequest = new HttpDelete(url); } else if (method.equalsIgnoreCase("PATCH")) { HttpPatch httpPatch = new HttpPatch(url); if (requestEntity != null) { httpPatch.setEntity(requestEntity); } httpRequest = httpPatch; } else if (method.equalsIgnoreCase("HEAD")) { httpRequest = new HttpHead(url); } else if (method.equalsIgnoreCase("OPTIONS")) { httpRequest = new HttpOptions(url); } else { throw new ServiceException("Invalid HTTP method: " + method, null, null); } // Headers for (Map.Entry<String, String> entry : headers.entrySet()) { httpRequest.addHeader(entry.getKey(), entry.getValue()); } httpRequest.setHeader("Accept", "application/json"); httpRequest.setHeader("Accept-Charset", "utf-8"); httpRequest.setHeader("Content-Type", "application/json; charset=utf-8"); httpRequest.setHeader("User-Agent", USER_AGENT); try (CloseableHttpResponse httpResponse = httpClient.execute(httpRequest)) { Response response = new ApacheHttpResponse(httpResponse); int statusCode = response.getStatusCode(); if (statusCode >= 200 && statusCode < 300) { return response; } throw ServiceException.fromResponse(response); } catch (ClientProtocolException e) { throw new ServiceException("Client Protocol Exception", null, e); } catch (IOException e) { throw new ServiceException("IO Exception", null, e); } }
From source file:com.kubeiwu.commontool.khttp.toolbox.HttpClientStack.java
/** * Creates the appropriate subclass of HttpUriRequest for passed in request. *//*from ww w .j a va 2 s . c o m*/ /* protected */static HttpUriRequest createHttpRequest(Request<?> request, Map<String, String> additionalHeaders) throws AuthFailureError { switch (request.getMethod()) { case Method.DEPRECATED_GET_OR_POST: { // This is the deprecated way that needs to be handled for backwards compatibility. // If the request's post body is null, then the assumption is that the request is // GET. Otherwise, it is assumed that the request is a POST. byte[] postBody = request.getBody(); if (postBody != null) { HttpPost postRequest = new HttpPost(request.getUrl()); postRequest.addHeader(HEADER_CONTENT_TYPE, request.getBodyContentType()); HttpEntity entity; entity = new ByteArrayEntity(postBody); postRequest.setEntity(entity); return postRequest; } else { return new HttpGet(request.getUrl()); } } case Method.GET: return new HttpGet(request.getUrl()); case Method.DELETE: return new HttpDelete(request.getUrl()); case Method.POST: { HttpPost postRequest = new HttpPost(request.getUrl()); postRequest.addHeader(HEADER_CONTENT_TYPE, request.getBodyContentType()); setEntityIfNonEmptyBody(postRequest, request); return postRequest; } case Method.PUT: { HttpPut putRequest = new HttpPut(request.getUrl()); putRequest.addHeader(HEADER_CONTENT_TYPE, request.getBodyContentType()); setEntityIfNonEmptyBody(putRequest, request); return putRequest; } default: throw new IllegalStateException("Unknown request method."); } }
From source file:com.redhat.red.build.koji.it.AbstractWithSetupIT.java
protected void uploadFile(InputStream resourceStream, String targetPath, CloseableHttpClient client) { String url = formatUrl(CONTENT_CGI, targetPath); System.out.println("\n\n ##### START: " + name.getMethodName() + " :: Upload -> " + url + " #####\n\n"); CloseableHttpResponse response = null; try {//from www . j av a2 s . c om HttpPut put = new HttpPut(url); put.setEntity(new InputStreamEntity(resourceStream)); response = client.execute(put); } catch (IOException e) { e.printStackTrace(); fail(String.format("Failed to execute GET request: %s. Reason: %s", url, e.getMessage())); } int code = response.getStatusLine().getStatusCode(); if (code != 201 || code != 200) { fail("Failed to upload content: " + targetPath + "\nSERVER RESPONSE STATUS: " + response.getStatusLine()); } else { System.out.println("\n\n ##### END: " + name.getMethodName() + " :: Upload -> " + url + " #####\n\n"); } }
From source file:org.jboss.as.quickstarts.resteasyspring.test.ResteasySpringIT.java
@Test public void testHelloSpringResource() throws Exception { try (CloseableHttpClient client = HttpClients.createDefault()) { {// w w w .ja v a 2 s. c o m URI uri = new URIBuilder().setScheme("http").setHost(url.getHost()).setPort(url.getPort()) .setPath(url.getPath() + "hello").setParameter("name", "JBoss Developer").build(); HttpGet method = new HttpGet(uri); try (CloseableHttpResponse response = client.execute(method)) { Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatusLine().getStatusCode()); Assert.assertTrue(EntityUtils.toString(response.getEntity()).contains("JBoss Developer")); } finally { method.releaseConnection(); } } { HttpGet method = new HttpGet(url.toString() + "basic"); try (CloseableHttpResponse response = client.execute(method)) { Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatusLine().getStatusCode()); Assert.assertTrue(EntityUtils.toString(response.getEntity()).contains("basic")); } finally { method.releaseConnection(); } } { HttpPut method = new HttpPut(url.toString() + "basic"); method.setEntity(new StringEntity("basic", ContentType.TEXT_PLAIN)); try (CloseableHttpResponse response = client.execute(method)) { Assert.assertEquals(HttpResponseCodes.SC_NO_CONTENT, response.getStatusLine().getStatusCode()); } finally { method.releaseConnection(); } } { URI uri = new URIBuilder().setScheme("http").setHost(url.getHost()).setPort(url.getPort()) .setPath(url.getPath() + "queryParam").setParameter("param", "hello world").build(); HttpGet method = new HttpGet(uri); try (CloseableHttpResponse response = client.execute(method)) { Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatusLine().getStatusCode()); Assert.assertTrue(EntityUtils.toString(response.getEntity()).contains("hello world")); } finally { method.releaseConnection(); } } { HttpGet method = new HttpGet(url.toString() + "matrixParam;param=matrix"); try (CloseableHttpResponse response = client.execute(method)) { Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatusLine().getStatusCode()); Assert.assertTrue(EntityUtils.toString(response.getEntity()).equals("matrix")); } finally { method.releaseConnection(); } } { HttpGet method = new HttpGet("http://localhost:8080/spring-resteasy/uriParam/1234"); try (CloseableHttpResponse response = client.execute(method)) { Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatusLine().getStatusCode()); Assert.assertTrue(EntityUtils.toString(response.getEntity()).equals("1234")); } finally { method.releaseConnection(); } } } }
From source file:org.deviceconnect.android.profile.restful.test.NormalFileDescriptorProfileTestCase.java
/** * ??.//from w ww. j a v a2s .c o m * <pre> * ?HTTP * Method: PUT * Path: /file_descriptor/close?deviceid=xxxx&mediaid=xxxx * </pre> * <pre> * ?? * result?0??????? * </pre> */ public void testClose() { StringBuilder builder = new StringBuilder(); builder.append(DCONNECT_MANAGER_URI); builder.append("/" + FileDescriptorProfileConstants.PROFILE_NAME); builder.append("/" + FileDescriptorProfileConstants.ATTRIBUTE_CLOSE); builder.append("?"); builder.append(DConnectProfileConstants.PARAM_DEVICE_ID + "=" + getDeviceId()); builder.append("&"); builder.append(FileDescriptorProfileConstants.PARAM_PATH + "=test.txt"); builder.append("&"); builder.append(AuthorizationProfileConstants.PARAM_ACCESS_TOKEN + "=" + getAccessToken()); try { HttpUriRequest request = new HttpPut(builder.toString()); JSONObject root = sendRequest(request); Assert.assertNotNull("root is null.", root); Assert.assertEquals(DConnectMessage.RESULT_OK, root.getInt(DConnectMessage.EXTRA_RESULT)); } catch (JSONException e) { fail("Exception in JSONObject." + e.getMessage()); } }
From source file:cn.bidaround.ytcore.util.HttpClientStack.java
/** * Creates the appropriate subclass of HttpUriRequest for passed in request. *//*from w w w .ja v a 2 s.c om*/ @SuppressWarnings("deprecation") /* protected */ static HttpUriRequest createHttpRequest(Request<?> request, Map<String, String> additionalHeaders) throws AuthFailureError { switch (request.getMethod()) { case Method.DEPRECATED_GET_OR_POST: { // This is the deprecated way that needs to be handled for backwards compatibility. // If the request's post body is null, then the assumption is that the request is // GET. Otherwise, it is assumed that the request is a POST. byte[] postBody = request.getPostBody(); if (postBody != null) { HttpPost postRequest = new HttpPost(request.getUrl()); postRequest.addHeader(HEADER_CONTENT_TYPE, request.getPostBodyContentType()); HttpEntity entity; entity = new ByteArrayEntity(postBody); postRequest.setEntity(entity); return postRequest; } else { return new HttpGet(request.getUrl()); } } case Method.GET: return new HttpGet(request.getUrl()); case Method.DELETE: return new HttpDelete(request.getUrl()); case Method.POST: { HttpPost postRequest = new HttpPost(request.getUrl()); postRequest.addHeader(HEADER_CONTENT_TYPE, request.getBodyContentType()); setEntityIfNonEmptyBody(postRequest, request); return postRequest; } case Method.PUT: { HttpPut putRequest = new HttpPut(request.getUrl()); putRequest.addHeader(HEADER_CONTENT_TYPE, request.getBodyContentType()); setEntityIfNonEmptyBody(putRequest, request); return putRequest; } case Method.HEAD: return new HttpHead(request.getUrl()); case Method.OPTIONS: return new HttpOptions(request.getUrl()); case Method.TRACE: return new HttpTrace(request.getUrl()); case Method.PATCH: { HttpPatch patchRequest = new HttpPatch(request.getUrl()); patchRequest.addHeader(HEADER_CONTENT_TYPE, request.getBodyContentType()); setEntityIfNonEmptyBody(patchRequest, request); return patchRequest; } default: throw new IllegalStateException("Unknown request method."); } }