List of usage examples for org.apache.http.client.methods HttpPatch HttpPatch
public HttpPatch(final String uri)
From source file:com.github.restdriver.clientdriver.integration.ClientDriverSuccessTest.java
@Test public void testJettyWorkingWithPatchBody() throws Exception { String baseUrl = driver.getBaseUrl(); driver.addExpectation(/*from w w w . j a va 2s.c o m*/ onRequestTo("/blah2").withMethod(Method.custom("PATCH")).withBody("Jack your body!", "text/plain"), giveResponse("___", "text/plain").withStatus(501)); HttpClient client = new DefaultHttpClient(); HttpPatch patcher = new HttpPatch(baseUrl + "/blah2"); patcher.setEntity(new StringEntity("Jack your body!", ContentType.TEXT_PLAIN)); HttpResponse response = client.execute(patcher); assertThat(response.getStatusLine().getStatusCode(), is(501)); assertThat(IOUtils.toString(response.getEntity().getContent()), equalTo("___")); }
From source file:org.fcrepo.integration.FedoraHtmlResponsesIT.java
License:asdf
private static void postSparqlUpdateUsingHttpClient(final String sparql, final String pid) throws IOException { final HttpPatch method = new HttpPatch(serverAddress + pid); method.addHeader(CONTENT_TYPE, "application/sparql-update"); final BasicHttpEntity entity = new BasicHttpEntity(); entity.setContent(new ByteArrayInputStream(sparql.getBytes())); method.setEntity(entity);// w w w .java 2s . c o m final HttpResponse response = client.execute(method); assertEquals("Expected successful response.", 204, response.getStatusLine().getStatusCode()); }
From source file:com.keydap.sparrow.SparrowClient.java
/** * Modifies the selected resource/*w w w . ja v a 2s . c om*/ * @param pr the modify(a.k.a patch) request * @return */ public <T> Response<T> patchResource(PatchRequest pr) { Class resClas = pr.getResClass(); String endpoint = getEndpoint(resClas); String url = baseApiUrl + endpoint + "/" + pr.getId(); if (pr.getAttributes() != null) { String encoded; try { encoded = URLEncoder.encode(pr.getAttributes(), Consts.UTF_8.name()); } catch (Exception e) { throw new RuntimeException(e); } url += "?attributes=" + encoded; } HttpPatch patch = new HttpPatch(url); setIfMatch(patch, pr.getIfMatch()); setBody(patch, pr); return sendRawRequest(patch, resClas); }
From source file:de.codecentric.boot.admin.zuul.filters.route.SimpleHostRoutingFilter.java
private CloseableHttpResponse forward(CloseableHttpClient httpclient, String verb, String uri, HttpServletRequest request, MultiValueMap<String, String> headers, MultiValueMap<String, String> params, InputStream requestEntity) throws Exception { Map<String, Object> info = this.helper.debug(verb, uri, headers, params, requestEntity); URL host = RequestContext.getCurrentContext().getRouteHost(); HttpHost httpHost = getHttpHost(host); uri = StringUtils.cleanPath((host.getPath() + uri).replaceAll("/{2,}", "/")); HttpRequest httpRequest;/*from w w w . j a v a2 s .c o m*/ int contentLength = request.getContentLength(); InputStreamEntity entity = new InputStreamEntity(requestEntity, contentLength, request.getContentType() != null ? ContentType.create(request.getContentType()) : null); switch (verb.toUpperCase()) { case "POST": HttpPost httpPost = new HttpPost(uri + this.helper.getQueryString(params)); httpRequest = httpPost; httpPost.setEntity(entity); break; case "PUT": HttpPut httpPut = new HttpPut(uri + this.helper.getQueryString(params)); httpRequest = httpPut; httpPut.setEntity(entity); break; case "PATCH": HttpPatch httpPatch = new HttpPatch(uri + this.helper.getQueryString(params)); httpRequest = httpPatch; httpPatch.setEntity(entity); break; default: httpRequest = new BasicHttpRequest(verb, uri + this.helper.getQueryString(params)); log.debug(uri + this.helper.getQueryString(params)); } try { httpRequest.setHeaders(convertHeaders(headers)); log.debug(httpHost.getHostName() + " " + httpHost.getPort() + " " + httpHost.getSchemeName()); CloseableHttpResponse zuulResponse = forwardRequest(httpclient, httpHost, httpRequest); RequestContext.getCurrentContext().set("zuulResponse", zuulResponse); this.helper.appendDebug(info, zuulResponse.getStatusLine().getStatusCode(), revertHeaders(zuulResponse.getAllHeaders())); return zuulResponse; } finally { // When HttpClient instance is no longer needed, // shut down the connection manager to ensure // immediate deallocation of all system resources // httpclient.getConnectionManager().shutdown(); } }
From source file:at.orz.arangodb.http.HttpManager.java
/** * //from www .java2 s . c om * @param requestEntity * @return * @throws ArangoException */ public HttpResponseEntity execute(HttpRequestEntity requestEntity) throws ArangoException { String url = buildUrl(requestEntity); if (logger.isDebugEnabled()) { if (requestEntity.type == RequestType.POST || requestEntity.type == RequestType.PUT || requestEntity.type == RequestType.PATCH) { logger.debug("[REQ]http-{}: url={}, headers={}, body={}", new Object[] { requestEntity.type, url, requestEntity.headers, requestEntity.bodyText }); } else { logger.debug("[REQ]http-{}: url={}, headers={}", new Object[] { requestEntity.type, url, requestEntity.headers }); } } HttpRequestBase request = null; switch (requestEntity.type) { case GET: request = new HttpGet(url); break; case POST: HttpPost post = new HttpPost(url); configureBodyParams(requestEntity, post); request = post; break; case PUT: HttpPut put = new HttpPut(url); configureBodyParams(requestEntity, put); request = put; break; case PATCH: HttpPatch patch = new HttpPatch(url); configureBodyParams(requestEntity, patch); request = patch; break; case HEAD: request = new HttpHead(url); break; case DELETE: request = new HttpDelete(url); break; } // common-header String userAgent = "Mozilla/5.0 (compatible; ArangoDB-JavaDriver/1.0; +http://mt.orz.at/)"; // TODO: request.setHeader("User-Agent", userAgent); //request.setHeader("Content-Type", "binary/octet-stream"); // optinal-headers if (requestEntity.headers != null) { for (Entry<String, Object> keyValue : requestEntity.headers.entrySet()) { request.setHeader(keyValue.getKey(), keyValue.getValue().toString()); } } // Basic Auth Credentials credentials = null; if (requestEntity.username != null && requestEntity.password != null) { credentials = new UsernamePasswordCredentials(requestEntity.username, requestEntity.password); } else if (configure.getUser() != null && configure.getPassword() != null) { credentials = new UsernamePasswordCredentials(configure.getUser(), configure.getPassword()); } if (credentials != null) { request.addHeader(BasicScheme.authenticate(credentials, "US-ASCII", false)); } // CURL/httpie Logger if (configure.isEnableCURLLogger()) { CURLLogger.log(url, requestEntity, userAgent, credentials); } HttpResponse response = null; try { response = client.execute(request); if (response == null) { return null; } HttpResponseEntity responseEntity = new HttpResponseEntity(); // http status StatusLine status = response.getStatusLine(); responseEntity.statusCode = status.getStatusCode(); responseEntity.statusPhrase = status.getReasonPhrase(); logger.debug("[RES]http-{}: statusCode={}", requestEntity.type, responseEntity.statusCode); // ?? //// TODO etag??? Header etagHeader = response.getLastHeader("etag"); if (etagHeader != null) { responseEntity.etag = Long.parseLong(etagHeader.getValue().replace("\"", "")); } // Map??? responseEntity.headers = new TreeMap<String, String>(); for (Header header : response.getAllHeaders()) { responseEntity.headers.put(header.getName(), header.getValue()); } // ??? HttpEntity entity = response.getEntity(); if (entity != null) { Header contentType = entity.getContentType(); if (contentType != null) { responseEntity.contentType = contentType.getValue(); if (responseEntity.isDumpResponse()) { responseEntity.stream = entity.getContent(); logger.debug("[RES]http-{}: stream, {}", requestEntity.type, contentType.getValue()); } } // Close stream in this method. if (responseEntity.stream == null) { responseEntity.text = IOUtils.toString(entity.getContent()); logger.debug("[RES]http-{}: text={}", requestEntity.type, responseEntity.text); } } return responseEntity; } catch (ClientProtocolException e) { throw new ArangoException(e); } catch (IOException e) { throw new ArangoException(e); } }
From source file:com.github.restdriver.clientdriver.integration.ClientDriverSuccessTest.java
@Test public void testJettyWorkingWithPatchBodyPattern() throws Exception { String baseUrl = driver.getBaseUrl(); driver.addExpectation(//from w w w . ja va2s. c o m onRequestTo("/blah2").withMethod(Method.custom("PATCH")) .withBody(Pattern.compile("Jack [\\w\\s]+!"), "text/plain"), giveResponse("___", "text/plain").withStatus(501)); HttpClient client = new DefaultHttpClient(); HttpPatch patcher = new HttpPatch(baseUrl + "/blah2"); patcher.setEntity(new StringEntity("Jack your body!", ContentType.TEXT_PLAIN)); HttpResponse response = client.execute(patcher); assertThat(response.getStatusLine().getStatusCode(), is(501)); assertThat(IOUtils.toString(response.getEntity().getContent()), equalTo("___")); }
From source file:org.springframework.cloud.netflix.zuul.filters.route.SimpleHostRoutingFilter.java
protected HttpRequest buildHttpRequest(String verb, String uri, InputStreamEntity entity, MultiValueMap<String, String> headers, MultiValueMap<String, String> params) { HttpRequest httpRequest;//from w ww . j a v a 2s. c o m switch (verb.toUpperCase()) { case "POST": HttpPost httpPost = new HttpPost(uri + this.helper.getQueryString(params)); httpRequest = httpPost; httpPost.setEntity(entity); break; case "PUT": HttpPut httpPut = new HttpPut(uri + this.helper.getQueryString(params)); httpRequest = httpPut; httpPut.setEntity(entity); break; case "PATCH": HttpPatch httpPatch = new HttpPatch(uri + this.helper.getQueryString(params)); httpRequest = httpPatch; httpPatch.setEntity(entity); break; case "DELETE": BasicHttpEntityEnclosingRequest entityRequest = new BasicHttpEntityEnclosingRequest(verb, uri + this.helper.getQueryString(params)); httpRequest = entityRequest; entityRequest.setEntity(entity); break; default: httpRequest = new BasicHttpRequest(verb, uri + this.helper.getQueryString(params)); log.debug(uri + this.helper.getQueryString(params)); } httpRequest.setHeaders(convertHeaders(headers)); return httpRequest; }
From source file:org.identityconnectors.office365.Office365Connection.java
public boolean patchObject(String path, JSONObject body) { log.info("patchRequest(" + path + ")"); // http://msdn.microsoft.com/en-us/library/windowsazure/dn151671.aspx HttpPatch httpPatch = new HttpPatch(getAPIEndPoint(path)); httpPatch.addHeader("Authorization", this.getToken()); // patch.addHeader("Content-Type", "application/json;odata=verbose"); httpPatch.addHeader("DataServiceVersion", "3.0;NetFx"); httpPatch.addHeader("MaxDataServiceVersion", "3.0;NetFx"); httpPatch.addHeader("Accept", "application/atom+xml"); EntityBuilder eb = EntityBuilder.create(); eb.setText(body.toString());/*ww w . ja va2 s. c o m*/ eb.setContentType(ContentType.create("application/json")); httpPatch.setEntity(eb.build()); HttpClient httpClient = HttpClientBuilder.create().build(); try { HttpResponse response = httpClient.execute(httpPatch); HttpEntity entity = response.getEntity(); if (response.getStatusLine().getStatusCode() != 204) { log.error("An error occured when modify an object in Office 365"); this.invalidateToken(); StringBuffer sb = new StringBuffer(); if (entity != null && entity.getContent() != null) { BufferedReader in = new BufferedReader(new InputStreamReader(entity.getContent())); String s = null; log.info("Response :{0}", response.getStatusLine().toString()); while ((s = in.readLine()) != null) { sb.append(s); log.info(s); } } throw new ConnectorException("Modify Object failed to " + path + " and body of " + body.toString() + ". Error code was " + response.getStatusLine().getStatusCode() + ". Received the following response " + sb.toString()); } else { return true; } } catch (ClientProtocolException cpe) { log.error(cpe, "Error doing patchRequest to path {0}", path); throw new ConnectorException("Exception whilst doing PATCH to " + path); } catch (IOException ioe) { log.error(ioe, "IOE Error doing patchRequest to path {0}", path); throw new ConnectorException("Exception whilst doing PATCH to " + path); } }
From source file:com.hp.ov.sdk.rest.http.core.client.HttpRestClient.java
/** * Sends a PATCH request to HPE OneView. * * @param params//from ww w.j av a 2 s . com * connection parameters. * @param requestBody * The request body information * @param forceReturnTask * Forces the check for the Location header (task) even when the response code is not 202. * @return * The response from HPE OneView * @throws SDKBadRequestException */ private String sendPatchRequest(RestParams params, String requestBody, final boolean forceReturnTask) throws SDKBadRequestException { try { HttpPatch patch = new HttpPatch(buildURI(params)); if (requestBody == null) { requestBody = ""; } patch.setEntity(new StringEntity(requestBody, CHAR_SET)); setRequestHeaders(params, patch); patch.setConfig(createRequestTimeoutConfiguration()); return getResponse(patch, params, forceReturnTask); } catch (IllegalArgumentException e) { throw new SDKBadRequestException(SDKErrorEnum.badRequestError, null, null, null, SdkConstants.APPLIANCE, e); } }