List of usage examples for org.apache.commons.httpclient.methods PutMethod PutMethod
public PutMethod()
From source file:it.greenvulcano.gvesb.virtual.http.HTTPCallOperation.java
/** * @see it.greenvulcano.gvesb.virtual.CallOperation#perform(it.greenvulcano.gvesb.buffer.GVBuffer) *//* ww w.ja v a2 s . c om*/ @Override public GVBuffer perform(GVBuffer gvBuffer) throws ConnectionException, CallException, InvalidDataException { logger.debug("BEGIN perform(GVBuffer gvBuffer)"); HttpMethod method = null; try { String currMethodURI = null; Map<String, Object> params = GVBufferPropertiesHelper.getPropertiesMapSO(gvBuffer, true); String currHost = PropertiesHandler.expand(host, params, gvBuffer); String currPort = PropertiesHandler.expand(port, params, gvBuffer); logger.debug("Server Host: " + currHost + " - Port: " + currPort); httpClient.getHostConfiguration().setHost(currHost, Integer.parseInt(currPort), protocol); auth.setAuthentication(httpClient, host, Integer.parseInt(currPort), gvBuffer, params); proxy.setProxy(httpClient, gvBuffer, params); currMethodURI = PropertiesHandler.expand(contextPath + methodURI, params, gvBuffer); logger.debug("MethodURI[escaped:" + uriEscaped + "]=[" + currMethodURI + "]"); switch (methodName) { case OPTIONS: method = new OptionsMethod(); break; case GET: method = new GetMethod(); break; case HEAD: method = new HeadMethod(); break; case POST: method = new PostMethod(); break; case PUT: method = new PutMethod(); break; case DELETE: method = new DeleteMethod(); break; default: throw new CallException("GV_CALL_SERVICE_ERROR", new String[][] { { "service", gvBuffer.getService() }, { "system", gvBuffer.getSystem() }, { "id", gvBuffer.getId().toString() }, { "message", "Unknown method = " + methodName } }); } method.setURI(new URI(currMethodURI, uriEscaped)); if ((refDP != null) && (refDP.length() > 0)) { logger.debug("Calling configured Data Provider: " + refDP); DataProviderManager dataProviderManager = DataProviderManager.instance(); IDataProvider dataProvider = dataProviderManager.getDataProvider(refDP); try { dataProvider.setContext(method); dataProvider.setObject(gvBuffer); method = (HttpMethod) dataProvider.getResult(); } finally { dataProviderManager.releaseDataProvider(refDP, dataProvider); } } int status = httpClient.executeMethod(method); gvBuffer.setProperty(RESPONSE_STATUS, String.valueOf(status)); String statusTxt = method.getStatusText(); gvBuffer.setProperty(RESPONSE_MESSAGE, (statusTxt != null ? statusTxt : "NULL")); Header[] responseHeaders = method.getResponseHeaders(); for (Header header : responseHeaders) { String headerName = RESPONSE_HEADER_PREFIX + header.getName(); String value = header.getValue(); if (value == null) { value = ""; } gvBuffer.setProperty(headerName, value); } String cType = "text/html"; Header cTypeHeader = method.getResponseHeader("Content-Type"); if (cTypeHeader != null) { String cTypeValue = cTypeHeader.getValue(); if (cTypeValue != null) { cType = cTypeValue; } } logger.debug("Response content-type: " + cType); ContentType contentType = new ContentType(cType); byte[] responseBody = method.getResponseBody(); Object object = responseBody; if (contentType.getPrimaryType().equals("multipart")) { object = handleMultipart(responseBody, cType); } gvBuffer.setObject(object); } catch (CallException exc) { throw exc; } catch (Exception exc) { logger.error("ERROR perform(GVBuffer gvBuffer)", exc); throw new CallException("GV_CALL_SERVICE_ERROR", new String[][] { { "service", gvBuffer.getService() }, { "system", gvBuffer.getSystem() }, { "id", gvBuffer.getId().toString() }, { "message", exc.getMessage() } }, exc); } finally { try { if (method != null) { method.releaseConnection(); } } catch (Exception exc) { logger.warn("Error while releasing connection", exc); } logger.debug("END perform(GVBuffer gvBuffer)"); } return gvBuffer; }
From source file:com.sa.npopa.samples.hbase.rest.client.Client.java
/** * Send a PUT request/* ww w. j a v a 2s . co m*/ * @param cluster the cluster definition * @param path the path or URI * @param headers the HTTP headers to include, <tt>Content-Type</tt> must be * supplied * @param content the content bytes * @return a Response object with response detail * @throws IOException */ public Response put(Cluster cluster, String path, Header[] headers, byte[] content) throws IOException { PutMethod method = new PutMethod(); try { method.setRequestEntity(new ByteArrayRequestEntity(content)); int code = execute(cluster, method, headers, path); headers = method.getResponseHeaders(); content = method.getResponseBody(); return new Response(code, headers, content); } finally { method.releaseConnection(); } }
From source file:net.xmind.signin.internal.XMindNetRequest.java
public XMindNetRequest put() { this.method = new PutMethod(); return execute(); }
From source file:org.apache.axis2.transport.http.HTTPSender.java
/** * Used to send a request via HTTP Put Method * * @param msgContext - The MessageContext of the message * @param url - The target URL * @param soapActionString - The soapAction string of the request * @throws AxisFault - Thrown in case an exception occurs *///from w ww . j a va2s.co m private void sendViaPut(MessageContext msgContext, URL url, String soapActionString) throws AxisFault { HttpClient httpClient = getHttpClient(msgContext); /* Same deal - this value never gets used, why is it here? --Glen String charEncoding = (String) msgContext.getProperty(Constants.Configuration.CHARACTER_SET_ENCODING); if (charEncoding == null) { charEncoding = MessageContext.DEFAULT_CHAR_SET_ENCODING; } */ PutMethod putMethod = new PutMethod(); MessageFormatter messageFormatter = populateCommonProperties(msgContext, url, putMethod, httpClient, soapActionString); putMethod.setRequestEntity(new AxisRequestEntity(messageFormatter, msgContext, format, soapActionString, chunked, isAllowedRetry)); if (!httpVersion.equals(HTTPConstants.HEADER_PROTOCOL_10) && chunked) { putMethod.setContentChunked(true); } String soapAction = messageFormatter.formatSOAPAction(msgContext, format, soapActionString); if (soapAction != null && !msgContext.isDoingREST()) { putMethod.setRequestHeader(HTTPConstants.HEADER_SOAP_ACTION, soapAction); } /* * main excecution takes place.. */ try { executeMethod(httpClient, msgContext, url, putMethod); handleResponse(msgContext, putMethod); } catch (IOException e) { log.info("Unable to sendViaPut to url[" + url + "]", e); throw AxisFault.makeFault(e); } finally { cleanup(msgContext, putMethod); } }
From source file:org.apache.axis2.transport.http.impl.httpclient3.HTTPSenderImpl.java
/** * Used to send a request via HTTP Put Method * //from w w w.j a v a2 s . c o m * @param msgContext * - The MessageContext of the message * @param url * - The target URL * @param soapActionString * - The soapAction string of the request * @throws AxisFault * - Thrown in case an exception occurs */ protected void sendViaPut(MessageContext msgContext, URL url, String soapActionString) throws AxisFault { HttpClient httpClient = getHttpClient(msgContext); /* * Same deal - this value never gets used, why is it here? --Glen String * charEncoding = (String) * msgContext.getProperty(Constants.Configuration * .CHARACTER_SET_ENCODING); * * if (charEncoding == null) { charEncoding = * MessageContext.DEFAULT_CHAR_SET_ENCODING; } */ PutMethod putMethod = new PutMethod(); MessageFormatter messageFormatter = populateCommonProperties(msgContext, url, putMethod, httpClient, soapActionString); putMethod.setRequestEntity(new AxisRequestEntityImpl(messageFormatter, msgContext, format, soapActionString, chunked, isAllowedRetry)); if (!httpVersion.equals(HTTPConstants.HEADER_PROTOCOL_10) && chunked) { putMethod.setContentChunked(true); } String soapAction = messageFormatter.formatSOAPAction(msgContext, format, soapActionString); if (soapAction != null) { putMethod.setRequestHeader(HTTPConstants.HEADER_SOAP_ACTION, soapAction); } /* * main excecution takes place.. */ try { executeMethod(httpClient, msgContext, url, putMethod); handleResponse(msgContext, putMethod); } catch (IOException e) { log.info("Unable to sendViaPut to url[" + url + "]", e); throw AxisFault.makeFault(e); } finally { cleanup(msgContext, putMethod); } }
From source file:org.apache.ode.axis2.httpbinding.HttpMethodConverter.java
/** * create and initialize the http method. * Http Headers that may been passed in the params are not set in this method. * Headers will be automatically set by HttpClient. * See usages of HostParams.DEFAULT_HEADERS * See org.apache.commons.httpclient.HttpMethodDirector#executeMethod(org.apache.commons.httpclient.HttpMethod) *///from ww w .j ava2s . c o m protected HttpMethod prepareHttpMethod(BindingOperation opBinding, String verb, Map<String, Element> partValues, Map<String, Node> headers, final String rootUri, HttpParams params) throws UnsupportedEncodingException { if (log.isDebugEnabled()) log.debug("Preparing http request..."); // convenience variables... BindingInput bindingInput = opBinding.getBindingInput(); HTTPOperation httpOperation = (HTTPOperation) WsdlUtils.getOperationExtension(opBinding); MIMEContent content = WsdlUtils.getMimeContent(bindingInput.getExtensibilityElements()); String contentType = content == null ? null : content.getType(); boolean useUrlEncoded = WsdlUtils.useUrlEncoded(bindingInput) || PostMethod.FORM_URL_ENCODED_CONTENT_TYPE.equalsIgnoreCase(contentType); boolean useUrlReplacement = WsdlUtils.useUrlReplacement(bindingInput); // the http method to be built and returned HttpMethod method = null; // the 4 elements the http method may be made of String relativeUri = httpOperation.getLocationURI(); String queryPath = null; RequestEntity requestEntity; String encodedParams = null; // ODE supports uri template in both port and operation location. // so assemble the final url *before* replacement String completeUri = rootUri; if (StringUtils.isNotEmpty(relativeUri)) { completeUri = completeUri + (completeUri.endsWith("/") || relativeUri.startsWith("/") ? "" : "/") + relativeUri; } if (useUrlReplacement) { // insert part values in the url completeUri = new UrlReplacementTransformer().transform(completeUri, partValues); } else if (useUrlEncoded) { // encode part values encodedParams = new URLEncodedTransformer().transform(partValues); } // http-client api is not really neat // something similar to the following would save some if/else manipulations. // But we have to deal with it as-is. // // method = new Method(verb); // method.setRequestEnity(..) // etc... if ("GET".equalsIgnoreCase(verb) || "DELETE".equalsIgnoreCase(verb)) { if ("GET".equalsIgnoreCase(verb)) { method = new GetMethod(); } else if ("DELETE".equalsIgnoreCase(verb)) { method = new DeleteMethod(); } method.getParams().setDefaults(params); if (useUrlEncoded) { queryPath = encodedParams; } // Let http-client manage the redirection // see org.apache.commons.httpclient.params.HttpClientParams.MAX_REDIRECTS // default is 100 method.setFollowRedirects(true); } else if ("POST".equalsIgnoreCase(verb) || "PUT".equalsIgnoreCase(verb)) { if ("POST".equalsIgnoreCase(verb)) { method = new PostMethod(); } else if ("PUT".equalsIgnoreCase(verb)) { method = new PutMethod(); } method.getParams().setDefaults(params); // some body-building... final String contentCharset = method.getParams().getContentCharset(); if (log.isDebugEnabled()) log.debug("Content-Type [" + contentType + "] Charset [" + contentCharset + "]"); if (useUrlEncoded) { requestEntity = new StringRequestEntity(encodedParams, PostMethod.FORM_URL_ENCODED_CONTENT_TYPE, contentCharset); } else { // get the part to be put in the body Part part = opBinding.getOperation().getInput().getMessage().getPart(content.getPart()); Element partValue = partValues.get(part.getName()); if (part.getElementName() == null) { String errMsg = "XML Types are not supported. Parts must use elements."; if (log.isErrorEnabled()) log.error(errMsg); throw new RuntimeException(errMsg); } else if (HttpUtils.isXml(contentType)) { if (log.isDebugEnabled()) log.debug("Content-Type [" + contentType + "] equivalent to 'text/xml'"); // stringify the first element String xmlString = DOMUtils.domToString(DOMUtils.getFirstChildElement(partValue)); requestEntity = new StringRequestEntity(xmlString, contentType, contentCharset); } else { if (log.isDebugEnabled()) log.debug("Content-Type [" + contentType + "] NOT equivalent to 'text/xml'. The text content of part value will be sent as text"); // encoding conversion is managed by StringRequestEntity if necessary requestEntity = new StringRequestEntity(DOMUtils.getTextContent(partValue), contentType, contentCharset); } } // cast safely, PUT and POST are subclasses of EntityEnclosingMethod final EntityEnclosingMethod enclosingMethod = (EntityEnclosingMethod) method; enclosingMethod.setRequestEntity(requestEntity); enclosingMethod .setContentChunked(params.getBooleanParameter(Properties.PROP_HTTP_REQUEST_CHUNK, false)); } else { // should not happen because of HttpBindingValidator, but never say never throw new IllegalArgumentException("Unsupported HTTP method: " + verb); } method.setPath(completeUri); // assumes that the path is properly encoded (URL safe). method.setQueryString(queryPath); // set headers setHttpRequestHeaders(method, opBinding, partValues, headers, params); return method; }
From source file:org.apache.wink.itest.CookieFieldsTest.java
/** * Test the @CookieParameter annotation bean property * /*w w w .ja va 2 s .c om*/ * @throws Exception */ // public void testCookieParamBeanProp() throws Exception { // httpclient = new HttpClient(); // setCookies(); // GetMethod getHttpMethod = new GetMethod(); // getHttpMethod.getParams().setCookiePolicy(CookiePolicy.RFC_2965); // getHttpMethod.setURI(new URI(BASE_URI+"/getValue3", false)); // System.out.println("Request headers:"); // System.out.println(Arrays.asList(getHttpMethod.getRequestHeaders())); // try { // int result = httpclient.executeMethod(getHttpMethod); // System.out.println("Response status code: " + result); // System.out.println("Response body: "); // String responseBody = getHttpMethod.getResponseBodyAsString(); // System.out.println(responseBody); // System.out.println("Response headers:"); // List<Header> headers = Arrays.asList(getHttpMethod.getResponseHeaders()); // System.out.println(headers); // assertEquals(400, result); // assertEquals("value3", responseBody.trim()); // } finally { // getHttpMethod.releaseConnection(); // } // } private void setCookies() throws Exception { // call put to set the cookies PutMethod putHttpMethod = new PutMethod(); putHttpMethod.getParams().setCookiePolicy(CookiePolicy.RFC_2965); putHttpMethod.setURI(new URI(BASE_URI, false)); System.out.println("Request headers:"); System.out.println(Arrays.asList(putHttpMethod.getRequestHeaders())); try { int result = httpclient.executeMethod(putHttpMethod); System.out.println("Response status code: " + result); System.out.println("Response body: "); String responseBody = putHttpMethod.getResponseBodyAsString(); System.out.println(responseBody); System.out.println("Response headers:"); List<Header> headers = Arrays.asList(putHttpMethod.getResponseHeaders()); System.out.println(headers); assertEquals(200, result); } finally { putHttpMethod.releaseConnection(); } }
From source file:org.apache.wink.itest.CookieParamTest.java
/** * Tests that a cookie parameter is retrieved. */// www .jav a2s . c om public void testCookieParam() { try { PutMethod httpMethod = new PutMethod(); httpMethod.getParams().setCookiePolicy(CookiePolicy.RFC_2109); httpMethod.setURI(new URI(BASE_URI, false)); System.out.println("Request headers:"); System.out.println(Arrays.asList(httpMethod.getRequestHeaders())); httpclient = new HttpClient(); try { int result = httpclient.executeMethod(httpMethod); System.out.println("Response status code: " + result); System.out.println("Response body: "); String responseBody = httpMethod.getResponseBodyAsString(); System.out.println(responseBody); System.out.println("Response headers:"); System.out.println(Arrays.asList(httpMethod.getResponseHeaders())); assertEquals(200, result); assertEquals("swiped:" + 0, responseBody); } catch (IOException ioe) { ioe.printStackTrace(); fail(ioe.getMessage()); } finally { httpMethod.releaseConnection(); } System.out.println("---"); httpMethod = new PutMethod(); httpMethod.getParams().setCookiePolicy(CookiePolicy.RFC_2109); httpMethod.setURI(new URI(BASE_URI, false)); httpMethod.setRequestHeader("Cookie", "jar=1"); System.out.println("Request headers:"); System.out.println(Arrays.asList(httpMethod.getRequestHeaders())); httpclient = new HttpClient(); try { int result = httpclient.executeMethod(httpMethod); System.out.println("Response status code: " + result); System.out.println("Response body: "); String responseBody = httpMethod.getResponseBodyAsString(); System.out.println(responseBody); System.out.println("Response headers:"); System.out.println(Arrays.asList(httpMethod.getResponseHeaders())); assertEquals(200, result); assertEquals("swiped:" + 1, responseBody); } catch (IOException ioe) { ioe.printStackTrace(); fail(ioe.getMessage()); } finally { httpMethod.releaseConnection(); } } catch (URIException e) { e.printStackTrace(); fail(e.getMessage()); } }
From source file:org.apache.wink.itest.methodannotations.HttpMethodWarningsTest.java
/** * Tests that two or more <code>@HttpMethod</code> annotated annotations on * a method generates an error. Vague on specification but it seems to be an * error if two or more annotations (which each have a HttpMethod annotation * on them) are on the same resource method. Based on error, it is probably * expected that the resource is unavailable. TODO: So this test could be * that two custom annotations which are annotated each with * <code>@HttpMethod</code> are annotated on the same method. *///from ww w.j av a2 s. c om public void testTwoOrMoreAnnotationsOnMethodError() { try { PostMethod httpMethod = new PostMethod(); httpMethod.setURI(new URI(BASE_URI, false)); httpclient = new HttpClient(); try { int result = httpclient.executeMethod(httpMethod); System.out.println("Response status code: " + result); System.out.println("Response body: "); String responseBody = httpMethod.getResponseBodyAsString(); System.out.println(responseBody); assertEquals(404, result); } catch (IOException ioe) { ioe.printStackTrace(); fail(ioe.getMessage()); } finally { httpMethod.releaseConnection(); } } catch (URIException e) { e.printStackTrace(); fail(e.getMessage()); } try { PutMethod putMethod = new PutMethod(); System.out.println(BASE_URI); putMethod.setURI(new URI(BASE_URI, true)); httpclient = new HttpClient(); try { int result = httpclient.executeMethod(putMethod); System.out.println("Response status code: " + result); System.out.println("Response body: "); String responseBody = putMethod.getResponseBodyAsString(); System.out.println(responseBody); /* * if a filter is used, then the 404 will fall through to the * container */ assertTrue("The result is " + result, (result == 403 && "tomcat".equals(ServerEnvironmentInfo.getContainerName())) || result == 405 || result == 404); } catch (IOException ioe) { ioe.printStackTrace(); fail(ioe.getMessage()); } finally { putMethod.releaseConnection(); } } catch (URIException e) { e.printStackTrace(); fail(e.getMessage()); } }
From source file:org.easyj.http.RESTHttpClient.java
/** * Executes a PUT HTTP request and returns the body response as {@code String} * * @param uri Uri of the resource to be requested * @return The body response of the request as {@code String} *//* ww w . j a v a2 s. c om*/ public RESTHttpClient put(String uri) { method = new PutMethod(); return execute(uri); }