List of usage examples for org.apache.commons.httpclient.methods PutMethod setRequestBody
public void setRequestBody(InputStream paramInputStream)
From source file:GraphController.java
@RequestMapping("/graphs") public @ResponseBody Graph graph( @RequestParam(value = "authentication", required = false, defaultValue = "Error") String authentication, @RequestParam(value = "hostid", required = false, defaultValue = "") String hostid) throws FileNotFoundException, UnsupportedEncodingException, IOException { Properties props = new Properties(); FileInputStream fis = new FileInputStream("properties.xml"); //loading properites from properties file props.loadFromXML(fis);// ww w .j ava2 s. com String server_ip = props.getProperty("server_ip"); String ZABBIX_API_URL = "http://" + server_ip + "/api_jsonrpc.php"; // 1.2.3.4 is your zabbix_server_ip JSONParser parser = new JSONParser(); HttpClient client = new HttpClient(); PutMethod putMethod = new PutMethod(ZABBIX_API_URL); putMethod.setRequestHeader("Content-Type", "application/json-rpc"); // content-type is controlled in api_jsonrpc.php, so set it like this // create json object for apiinfo.version JSONObject jsonObj = new JSONObject(); JSONArray list = new JSONArray(); jsonObj.put("jsonrpc", "2.0"); jsonObj.put("method", "graph.get"); JSONObject params = new JSONObject(); params.put("output", "extend"); params.put("hostids", hostid); params.put("sortfield", "name"); jsonObj.put("params", params); jsonObj.put("auth", authentication);// todo jsonObj.put("id", new Integer(1)); putMethod.setRequestBody(jsonObj.toString()); // put the json object as input stream into request body String loginResponse = ""; try { client.executeMethod(putMethod); // send to request to the zabbix api loginResponse = putMethod.getResponseBodyAsString(); // read the result of the response Object obj = parser.parse(loginResponse); JSONObject obj2 = (JSONObject) obj; String jsonrpc = (String) obj2.get("jsonrpc"); JSONArray array = (JSONArray) obj2.get("result"); // System.out.println(array); for (int i = 0; i < array.size(); i++) { JSONObject tobj = (JSONObject) array.get(i); JSONObject objret = new JSONObject(); objret.put("graphId", tobj.get("graphid")); objret.put("graphName", tobj.get("name")); String type = (String) tobj.get("graphtype"); if (type.equals("0")) { objret.put("graphType", "normal"); } else if (type.equals("1")) { objret.put("graphType", "stacked"); } else if (type.equals("2")) { objret.put("graphType", "pie"); } else if (type.equals("3")) { objret.put("graphType", "exploded"); } list.add(objret); } return new Graph(list); } catch (HttpException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (ParseException pe) { pe.printStackTrace(); } return new Graph( "Error: please provide the appropriate input parameters of the metric you are looking for its corresponding monitoring data:"); }
From source file:CPUController.java
@RequestMapping("/cpu") public @ResponseBody CPU cpu( @RequestParam(value = "authentication", required = false, defaultValue = "Error") String authentication, @RequestParam(value = "hostid", required = false, defaultValue = "") String hostid, @RequestParam(value = "metricType", required = false, defaultValue = "") String name) throws FileNotFoundException, UnsupportedEncodingException, IOException { Properties props = new Properties(); FileInputStream fis = new FileInputStream("properties.xml"); //loading properites from properties file props.loadFromXML(fis);/*from w w w. j a va2s . c o m*/ String server_ip = props.getProperty("server_ip"); String ZABBIX_API_URL = "http://" + server_ip + "/api_jsonrpc.php"; // 1.2.3.4 is your zabbix_server_ip JSONParser parser = new JSONParser(); HttpClient client = new HttpClient(); PutMethod putMethod = new PutMethod(ZABBIX_API_URL); putMethod.setRequestHeader("Content-Type", "application/json-rpc"); // content-type is controlled in api_jsonrpc.php, so set it like this // create json object for apiinfo.version JSONObject jsonObj = new JSONObject(); jsonObj.put("jsonrpc", "2.0"); jsonObj.put("method", "item.get"); JSONObject params = new JSONObject(); params.put("output", "extend"); params.put("hostid", hostid); JSONObject search = new JSONObject(); search.put("key_", "cpu"); params.put("search", search); params.put("sortfield", "name"); jsonObj.put("params", params); jsonObj.put("auth", authentication);// todo jsonObj.put("id", new Integer(1)); putMethod.setRequestBody(jsonObj.toString()); // put the json object as input stream into request body String loginResponse = ""; String cpu = ""; String clock = ""; String metricType = ""; try { client.executeMethod(putMethod); // send to request to the zabbix api loginResponse = putMethod.getResponseBodyAsString(); // read the result of the response Object obj = parser.parse(loginResponse); JSONObject obj2 = (JSONObject) obj; String jsonrpc = (String) obj2.get("jsonrpc"); JSONArray array = (JSONArray) obj2.get("result"); // System.out.println(array); for (int i = 0; i < array.size(); i++) { JSONObject tobj = (JSONObject) array.get(i); String key = (String) tobj.get("key_"); if (!tobj.get("hostid").equals(hostid)) continue; if (name.equals("idle") && key.contains("idle")) { cpu = (String) tobj.get("lastvalue"); clock = (String) tobj.get("lastclock"); metricType = "cpu idle time"; } else if (name.equals("iowait") && key.contains("iowait")) { cpu = (String) tobj.get("lastvalue"); clock = (String) tobj.get("lastclock"); metricType = "cpu iowait time"; } else if (name.equals("nice") && key.contains("nice")) { cpu = (String) tobj.get("lastvalue"); clock = (String) tobj.get("lastclock"); metricType = "cpu nice time"; } else if (name.equals("system") && key.contains("system")) { cpu = (String) tobj.get("lastvalue"); clock = (String) tobj.get("lastclock"); metricType = "cpu system time"; } else if (name.equals("user") && key.contains("user")) { cpu = (String) tobj.get("lastvalue"); clock = (String) tobj.get("lastclock"); metricType = "cpu user time"; } else if (name.equals("load") && key.contains("load")) { cpu = (String) tobj.get("lastvalue"); clock = (String) tobj.get("lastclock"); metricType = "processor load"; } else if (name.equals("usage") && key.contains("usage")) { cpu = (String) tobj.get("lastvalue"); clock = (String) tobj.get("lastclock"); metricType = "system cpu usage average"; } } } catch (HttpException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (ParseException pe) { System.out.println("Error"); } if (cpu.equals("")) { return new CPU( "Error: Please provide the appropriate input parameters of the metric you are looking for its corresponding monitoring data:"); } return new CPU(hostid, metricType, cpu, clock); }
From source file:MemoryController.java
@RequestMapping("/memory") public @ResponseBody Memory memory( @RequestParam(value = "authentication", required = false, defaultValue = "Error") String authentication, @RequestParam(value = "hostid", required = false, defaultValue = "") String hostid, @RequestParam(value = "metricType", required = false, defaultValue = "") String name) throws FileNotFoundException, UnsupportedEncodingException, IOException { Properties props = new Properties(); FileInputStream fis = new FileInputStream("properties.xml"); //loading properites from properties file props.loadFromXML(fis);/*from w w w. ja va 2s . c o m*/ String server_ip = props.getProperty("server_ip"); String ZABBIX_API_URL = "http://" + server_ip + "/api_jsonrpc.php"; // 1.2.3.4 is your zabbix_server_ip JSONParser parser = new JSONParser(); HttpClient client = new HttpClient(); PutMethod putMethod = new PutMethod(ZABBIX_API_URL); putMethod.setRequestHeader("Content-Type", "application/json-rpc"); // content-type is controlled in api_jsonrpc.php, so set it like this // create json object for apiinfo.version JSONObject jsonObj = new JSONObject(); jsonObj.put("jsonrpc", "2.0"); jsonObj.put("method", "item.get"); JSONObject params = new JSONObject(); params.put("output", "extend"); params.put("hostid", hostid); JSONObject search = new JSONObject(); search.put("key_", "memory"); params.put("search", search); params.put("sortfield", "name"); jsonObj.put("params", params); jsonObj.put("auth", authentication);// todo jsonObj.put("id", new Integer(1)); putMethod.setRequestBody(jsonObj.toString()); // put the json object as input stream into request body PutMethod putMethod2 = new PutMethod(ZABBIX_API_URL); putMethod2.setRequestHeader("Content-Type", "application/json-rpc"); // content-type is controlled in api_jsonrpc.php, so set it like this // create json object for apiinfo.version JSONObject jsonObj2 = new JSONObject(); jsonObj2.put("jsonrpc", "2.0"); jsonObj2.put("method", "item.get"); JSONObject params2 = new JSONObject(); params2.put("output", "extend"); params2.put("hostid", hostid); JSONObject search2 = new JSONObject(); search2.put("key_", "swap"); params2.put("search", search2); params2.put("sortfield", "name"); jsonObj2.put("params", params2); jsonObj2.put("auth", authentication);// todo jsonObj2.put("id", new Integer(1)); putMethod2.setRequestBody(jsonObj2.toString()); String loginResponse = ""; String loginResponse2 = ""; String memory = ""; String clock = ""; String metricType = ""; try { client.executeMethod(putMethod); // send to request to the zabbix api loginResponse = putMethod.getResponseBodyAsString(); // read the result of the response Object obj = parser.parse(loginResponse); JSONObject obj2 = (JSONObject) obj; String jsonrpc = (String) obj2.get("jsonrpc"); JSONArray array = (JSONArray) obj2.get("result"); client.executeMethod(putMethod2); // send to request to the zabbix api loginResponse2 = putMethod2.getResponseBodyAsString(); // read the result of the response Object obj3 = parser.parse(loginResponse2); JSONObject obj4 = (JSONObject) obj3; String jsonrpc2 = (String) obj4.get("jsonrpc"); JSONArray array2 = (JSONArray) obj4.get("result"); for (int i = 0; i < array.size(); i++) { JSONObject tobj = (JSONObject) array.get(i); // lastValue = getLastValue(tobj); // lastClock = getLastClock(tobj); if (!tobj.get("hostid").equals(hostid)) continue; if (name.equals("totalMemory") && tobj.get("name").equals("Total memory")) { memory = (String) tobj.get("lastvalue"); clock = (String) tobj.get("lastclock"); metricType = "Total Memeory"; return new Memory(hostid, metricType, memory, clock); } else if (name.equals("cachedMemory") && tobj.get("name").equals("Cached memory")) { memory = (String) tobj.get("lastvalue"); clock = (String) tobj.get("lastclock"); metricType = "Cached Memory"; return new Memory(hostid, metricType, memory, clock); } else if (name.equals("freeMemory") && tobj.get("name").equals("Free memory")) { memory = (String) tobj.get("lastvalue"); clock = (String) tobj.get("lastclock"); metricType = "Free Memory"; return new Memory(hostid, metricType, memory, clock); } else if (name.equals("bufferedMemory") && tobj.get("name").equals("Buffers memory")) { memory = (String) tobj.get("lastvalue"); clock = (String) tobj.get("lastclock"); metricType = "Buffered Memory"; return new Memory(hostid, metricType, memory, clock); } else if (name.equals("sharedMemory") && tobj.get("name").equals("Shared memory")) { memory = (String) tobj.get("lastvalue"); clock = (String) tobj.get("lastclock"); metricType = "Shared Memory"; return new Memory(hostid, metricType, memory, clock); } else { continue; } } for (int i = 0; i < array2.size(); i++) { JSONObject tobj2 = (JSONObject) array2.get(i); if (!tobj2.get("hostid").equals(hostid)) continue; if (name.equals("freeSwap") && tobj2.get("name").equals("Free swap space")) { memory = (String) tobj2.get("lastvalue"); clock = (String) tobj2.get("lastclock"); metricType = "Free Swap Space"; return new Memory(hostid, metricType, memory, clock); } else { continue; } } } catch (HttpException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (ParseException pe) { System.out.println("Error"); } return new Memory( "Error: please provide the appropriate input parameters of the metric you are looking for its corresponding monitoring data:"); }
From source file:nl.nn.adapterframework.http.HttpSender.java
protected HttpMethod getMethod(URI uri, String message, ParameterValueList parameters, Map<String, String> headersParamsMap) throws SenderException { try {/*from w w w . ja v a 2s .com*/ boolean queryParametersAppended = false; if (isEncodeMessages()) { message = URLEncoder.encode(message); } StringBuffer path = new StringBuffer(uri.getPath()); if (!StringUtils.isEmpty(uri.getQuery())) { path.append("?" + uri.getQuery()); queryParametersAppended = true; } if (getMethodType().equals("GET")) { if (parameters != null) { queryParametersAppended = appendParameters(queryParametersAppended, path, parameters, headersParamsMap); if (log.isDebugEnabled()) log.debug(getLogPrefix() + "path after appending of parameters [" + path.toString() + "]"); } GetMethod result = new GetMethod(path + (parameters == null ? message : "")); for (String param : headersParamsMap.keySet()) { result.addRequestHeader(param, headersParamsMap.get(param)); } if (log.isDebugEnabled()) log.debug( getLogPrefix() + "HttpSender constructed GET-method [" + result.getQueryString() + "]"); return result; } else if (getMethodType().equals("POST")) { PostMethod postMethod = new PostMethod(path.toString()); if (StringUtils.isNotEmpty(getContentType())) { postMethod.setRequestHeader("Content-Type", getContentType()); } if (parameters != null) { StringBuffer msg = new StringBuffer(message); appendParameters(true, msg, parameters, headersParamsMap); if (StringUtils.isEmpty(message) && msg.length() > 1) { message = msg.substring(1); } else { message = msg.toString(); } } for (String param : headersParamsMap.keySet()) { postMethod.addRequestHeader(param, headersParamsMap.get(param)); } postMethod.setRequestBody(message); return postMethod; } if (getMethodType().equals("PUT")) { PutMethod putMethod = new PutMethod(path.toString()); if (StringUtils.isNotEmpty(getContentType())) { putMethod.setRequestHeader("Content-Type", getContentType()); } if (parameters != null) { StringBuffer msg = new StringBuffer(message); appendParameters(true, msg, parameters, headersParamsMap); if (StringUtils.isEmpty(message) && msg.length() > 1) { message = msg.substring(1); } else { message = msg.toString(); } } putMethod.setRequestBody(message); return putMethod; } if (getMethodType().equals("DELETE")) { DeleteMethod deleteMethod = new DeleteMethod(path.toString()); if (StringUtils.isNotEmpty(getContentType())) { deleteMethod.setRequestHeader("Content-Type", getContentType()); } return deleteMethod; } if (getMethodType().equals("HEAD")) { HeadMethod headMethod = new HeadMethod(path.toString()); if (StringUtils.isNotEmpty(getContentType())) { headMethod.setRequestHeader("Content-Type", getContentType()); } return headMethod; } if (getMethodType().equals("REPORT")) { Element element = XmlUtils.buildElement(message, true); ReportInfo reportInfo = new ReportInfo(element, 0); ReportMethod reportMethod = new ReportMethod(path.toString(), reportInfo); if (StringUtils.isNotEmpty(getContentType())) { reportMethod.setRequestHeader("Content-Type", getContentType()); } return reportMethod; } throw new SenderException( "unknown methodtype [" + getMethodType() + "], must be either POST, GET, PUT or DELETE"); } catch (URIException e) { throw new SenderException(getLogPrefix() + "cannot find path from url [" + getUrl() + "]", e); } catch (DavException e) { throw new SenderException(e); } catch (DomBuilderException e) { throw new SenderException(e); } catch (IOException e) { throw new SenderException(e); } }
From source file:org.apache.ambari.funtest.server.AmbariHttpWebRequest.java
/** * Constructs a PutMethod instance and sets the request data on it. * * @return - PutMethod.//w ww .j a v a2 s . c o m */ @SuppressWarnings("deprecation") private PutMethod getPutMethod() { PutMethod putMethod = new PutMethod(getUrl()); putMethod.setRequestBody(getContent()); return putMethod; }
From source file:org.apache.cocoon.transformation.SparqlTransformer.java
private void executeRequest(String url, String method, Map httpHeaders, SourceParameters requestParameters) throws ProcessingException, IOException, SAXException { HttpClient httpclient = new HttpClient(); if (System.getProperty("http.proxyHost") != null) { // getLogger().warn("PROXY: "+System.getProperty("http.proxyHost")); String nonProxyHostsRE = System.getProperty("http.nonProxyHosts", ""); if (nonProxyHostsRE.length() > 0) { String[] pHosts = nonProxyHostsRE.replaceAll("\\.", "\\\\.").replaceAll("\\*", ".*").split("\\|"); nonProxyHostsRE = ""; for (String pHost : pHosts) { nonProxyHostsRE += "|(^https?://" + pHost + ".*$)"; }//ww w.j a va 2 s . c om nonProxyHostsRE = nonProxyHostsRE.substring(1); } if (nonProxyHostsRE.length() == 0 || !url.matches(nonProxyHostsRE)) { try { HostConfiguration hostConfiguration = httpclient.getHostConfiguration(); hostConfiguration.setProxy(System.getProperty("http.proxyHost"), Integer.parseInt(System.getProperty("http.proxyPort", "80"))); httpclient.setHostConfiguration(hostConfiguration); } catch (Exception e) { throw new ProcessingException("Cannot set proxy!", e); } } } // Make the HttpMethod. HttpMethod httpMethod = null; // Do not use empty query parameter. if (requestParameters.getParameter(parameterName).trim().equals("")) { requestParameters.removeParameter(parameterName); } // Instantiate different HTTP methods. if ("GET".equalsIgnoreCase(method)) { httpMethod = new GetMethod(url); if (requestParameters.getEncodedQueryString() != null) { httpMethod.setQueryString( requestParameters.getEncodedQueryString().replace("\"", "%22")); /* Also escape '"' */ } else { httpMethod.setQueryString(""); } } else if ("POST".equalsIgnoreCase(method)) { PostMethod httpPostMethod = new PostMethod(url); if (httpHeaders.containsKey(HTTP_CONTENT_TYPE) && ((String) httpHeaders.get(HTTP_CONTENT_TYPE)) .startsWith("application/x-www-form-urlencoded")) { // Encode parameters in POST body. Iterator parNames = requestParameters.getParameterNames(); while (parNames.hasNext()) { String parName = (String) parNames.next(); httpPostMethod.addParameter(parName, requestParameters.getParameter(parName)); } } else { // Use query parameter as POST body httpPostMethod.setRequestBody(requestParameters.getParameter(parameterName)); // Add other parameters to query string requestParameters.removeParameter(parameterName); if (requestParameters.getEncodedQueryString() != null) { httpPostMethod.setQueryString( requestParameters.getEncodedQueryString().replace("\"", "%22")); /* Also escape '"' */ } else { httpPostMethod.setQueryString(""); } } httpMethod = httpPostMethod; } else if ("PUT".equalsIgnoreCase(method)) { PutMethod httpPutMethod = new PutMethod(url); httpPutMethod.setRequestBody(requestParameters.getParameter(parameterName)); requestParameters.removeParameter(parameterName); httpPutMethod.setQueryString(requestParameters.getEncodedQueryString()); httpMethod = httpPutMethod; } else if ("DELETE".equalsIgnoreCase(method)) { httpMethod = new DeleteMethod(url); httpMethod.setQueryString(requestParameters.getEncodedQueryString()); } else { throw new ProcessingException("Unsupported method: " + method); } // Authentication (optional). if (credentials != null && credentials.length() > 0) { String[] unpw = credentials.split("\t"); httpclient.getParams().setAuthenticationPreemptive(true); httpclient.getState().setCredentials(new AuthScope(httpMethod.getURI().getHost(), httpMethod.getURI().getPort(), AuthScope.ANY_REALM), new UsernamePasswordCredentials(unpw[0], unpw[1])); } // Add request headers. Iterator headers = httpHeaders.entrySet().iterator(); while (headers.hasNext()) { Map.Entry header = (Map.Entry) headers.next(); httpMethod.addRequestHeader((String) header.getKey(), (String) header.getValue()); } // Declare some variables before the try-block. XMLizer xmlizer = null; try { // Execute the request. int responseCode; responseCode = httpclient.executeMethod(httpMethod); // Handle errors, if any. if (responseCode < 200 || responseCode >= 300) { if (showErrors) { AttributesImpl attrs = new AttributesImpl(); attrs.addCDATAAttribute("status", "" + responseCode); xmlConsumer.startElement(SPARQL_NAMESPACE_URI, "error", "sparql:error", attrs); String responseBody = httpMethod.getStatusText(); //httpMethod.getResponseBodyAsString(); xmlConsumer.characters(responseBody.toCharArray(), 0, responseBody.length()); xmlConsumer.endElement(SPARQL_NAMESPACE_URI, "error", "sparql:error"); return; // Not a nice, but quick and dirty way to end. } else { throw new ProcessingException("Received HTTP status code " + responseCode + " " + httpMethod.getStatusText() + ":\n" + httpMethod.getResponseBodyAsString()); } } // Parse the response if (responseCode == 204) { // No content. String statusLine = httpMethod.getStatusLine().toString(); xmlConsumer.startElement(SPARQL_NAMESPACE_URI, "result", "sparql:result", EMPTY_ATTRIBUTES); xmlConsumer.characters(statusLine.toCharArray(), 0, statusLine.length()); xmlConsumer.endElement(SPARQL_NAMESPACE_URI, "result", "sparql:result"); } else if (parse.equalsIgnoreCase("xml")) { InputStream responseBodyStream = httpMethod.getResponseBodyAsStream(); xmlizer = (XMLizer) manager.lookup(XMLizer.ROLE); xmlizer.toSAX(responseBodyStream, "text/xml", httpMethod.getURI().toString(), new IncludeXMLConsumer(xmlConsumer)); responseBodyStream.close(); } else if (parse.equalsIgnoreCase("text")) { xmlConsumer.startElement(SPARQL_NAMESPACE_URI, "result", "sparql:result", EMPTY_ATTRIBUTES); String responseBody = httpMethod.getResponseBodyAsString(); xmlConsumer.characters(responseBody.toCharArray(), 0, responseBody.length()); xmlConsumer.endElement(SPARQL_NAMESPACE_URI, "result", "sparql:result"); } else { throw new ProcessingException("Unknown parse type: " + parse); } } catch (ServiceException e) { throw new ProcessingException("Cannot find the right XMLizer for " + XMLizer.ROLE, e); } finally { if (xmlizer != null) manager.release((Component) xmlizer); httpMethod.releaseConnection(); } }
From source file:org.apache.manifoldcf.examples.ManifoldCFAPIConnect.java
/** Perform an API PUT operation. *@param restPath is the URL path of the REST object, starting with "/". *@param input is the input JSON.//from w ww. j a va 2 s . c o m *@return the json response. */ public String performAPIRawPutOperation(String restPath, String input) throws IOException { HttpClient client = new HttpClient(); PutMethod method = new PutMethod(formURL(restPath)); method.setRequestHeader("Content-type", "text/plain; charset=UTF-8"); method.setRequestBody(input); int response = client.executeMethod(method); byte[] responseData = method.getResponseBody(); // We presume that the data is utf-8, since that's what the API // uses throughout. String responseString = new String(responseData, "utf-8"); if (response != HttpStatus.SC_OK && response != HttpStatus.SC_CREATED) throw new IOException("API http error; expected " + HttpStatus.SC_OK + " or " + HttpStatus.SC_CREATED + ", saw " + Integer.toString(response) + ": " + responseString); return responseString; }
From source file:org.apache.maven.wagon.providers.webdav.CorrectedWebdavResource.java
/** * Execute the PUT method for the given path. * * @param path the server relative path to put the data * @param inputStream The input stream./*from w ww . j a va 2s.com*/ * * @return true if the method is succeeded. */ public boolean putMethod(String path, InputStream inputStream, int contentLength) throws IOException { setClient(); PutMethod method = new PutMethod(URIUtil.encodePathQuery(path)); method.setFollowRedirects(super.followRedirects); generateIfHeader(method); if (getGetContentType() != null && !getGetContentType().equals("")) { method.setRequestHeader("Content-Type", getGetContentType()); } method.setRequestContentLength(contentLength); method.setRequestBody(inputStream); generateTransactionHeader(method); generateAdditionalHeaders(method); int statusCode = client.executeMethod(method); setStatusCode(statusCode); return isHttpSuccess(statusCode); }
From source file:org.apache.webdav.ant.Utils.java
public static void putFile(HttpClient client, HttpURL url, InputStream is, String contentType, String lockToken) throws IOException, HttpException { PutMethod put = new PutMethod(url.getEscapedURI()); generateIfHeader(put, lockToken);/*from ww w .ja va 2 s . c om*/ put.setRequestHeader("Content-Type", contentType); put.setRequestBody(is); put.setFollowRedirects(true); int status = client.executeMethod(put); switch (status) { case WebdavStatus.SC_OK: case WebdavStatus.SC_CREATED: case WebdavStatus.SC_NO_CONTENT: return; default: HttpException ex = new HttpException(); ex.setReason(put.getStatusText()); ex.setReasonCode(status); throw ex; } }
From source file:org.apache.webdav.lib.WebdavResource.java
/** * Execute the PUT method for the given path. * * @param path the server relative path to put the data * @param data The byte array.//from ww w . j a v a 2s. c o m * @return true if the method is succeeded. * @exception HttpException * @exception IOException */ public boolean putMethod(String path, byte[] data) throws HttpException, IOException { setClient(); PutMethod method = new PutMethod(URIUtil.encodePathQuery(path)); generateIfHeader(method); if (getGetContentType() != null && !getGetContentType().equals("")) method.setRequestHeader("Content-Type", getGetContentType()); method.setRequestHeader("Content-Length", String.valueOf(data.length)); method.setRequestBody(new ByteArrayInputStream(data)); generateTransactionHeader(method); generateAdditionalHeaders(method); int statusCode = client.executeMethod(method); setStatusCode(statusCode); return (statusCode >= 200 && statusCode < 300) ? true : false; }