List of usage examples for org.apache.commons.httpclient.methods PutMethod PutMethod
public PutMethod(String paramString)
From source file:org.openo.nfvo.monitor.dac.util.APIHttpClient.java
public static String doPut(String uri, String jsonObj, String token) { String resStr = null;/*w w w. ja v a 2 s. c om*/ HttpClient htpClient = new HttpClient(); PutMethod putMethod = new PutMethod(uri); putMethod.addRequestHeader("Content-Type", "application/json"); putMethod.addRequestHeader("X-Auth-Token", token); putMethod.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "utf-8"); putMethod.setRequestBody(jsonObj); try { int statusCode = htpClient.executeMethod(putMethod); if (statusCode != HttpStatus.SC_OK) { return null; } byte[] responseBody = putMethod.getResponseBody(); resStr = new String(responseBody, "utf-8"); } catch (Exception e) { e.printStackTrace(); } finally { putMethod.releaseConnection(); } return resStr; }
From source file:org.openo.nfvo.monitor.umc.util.APIHttpClient.java
public static String doPut(String uri, JSONObject jsonObj, String token) { String resStr = null;//from www. j av a 2s. c o m String requestBody = jsonObj.toString(); HttpClient htpClient = new HttpClient(); PutMethod putMethod = new PutMethod(uri); putMethod.addRequestHeader("Content-Type", "application/json"); putMethod.addRequestHeader("X-Auth-Token", token); putMethod.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "utf-8"); putMethod.setRequestBody(requestBody); try { int statusCode = htpClient.executeMethod(putMethod); if (statusCode != HttpStatus.SC_OK) { return null; } byte[] responseBody = putMethod.getResponseBody(); resStr = new String(responseBody, "utf-8"); } catch (Exception e) { e.printStackTrace(); } finally { putMethod.releaseConnection(); } return resStr; }
From source file:org.openrdf.http.client.HTTPClient.java
protected void upload(RequestEntity reqEntity, String baseURI, boolean overwrite, Resource... contexts) throws IOException, RDFParseException, RepositoryException, UnauthorizedException { OpenRDFUtil.verifyContextNotNull(contexts); checkRepositoryURL();/* w w w . j av a 2s .co m*/ String uploadURL = Protocol.getStatementsLocation(getRepositoryURL()); // Select appropriate HTTP method EntityEnclosingMethod method; if (overwrite) { method = new PutMethod(uploadURL); } else { method = new PostMethod(uploadURL); } setDoAuthentication(method); // Set relevant query parameters List<NameValuePair> params = new ArrayList<NameValuePair>(5); for (String encodedContext : Protocol.encodeContexts(contexts)) { params.add(new NameValuePair(Protocol.CONTEXT_PARAM_NAME, encodedContext)); } if (baseURI != null && baseURI.trim().length() != 0) { String encodedBaseURI = Protocol.encodeValue(new URIImpl(baseURI)); params.add(new NameValuePair(Protocol.BASEURI_PARAM_NAME, encodedBaseURI)); } method.setQueryString(params.toArray(new NameValuePair[params.size()])); // Set payload method.setRequestEntity(reqEntity); // Send request try { int httpCode = httpClient.executeMethod(method); if (httpCode == HttpURLConnection.HTTP_UNAUTHORIZED) { throw new UnauthorizedException(); } else if (httpCode == HttpURLConnection.HTTP_UNSUPPORTED_TYPE) { throw new UnsupportedRDFormatException(method.getResponseBodyAsString()); } else if (!is2xx(httpCode)) { ErrorInfo errInfo = ErrorInfo.parse(method.getResponseBodyAsString()); if (errInfo.getErrorType() == ErrorType.MALFORMED_DATA) { throw new RDFParseException(errInfo.getErrorMessage()); } else if (errInfo.getErrorType() == ErrorType.UNSUPPORTED_FILE_FORMAT) { throw new UnsupportedRDFormatException(errInfo.getErrorMessage()); } else { throw new RepositoryException("Failed to upload data: " + errInfo); } } } finally { releaseConnection(method); } }
From source file:org.openrdf.http.client.HTTPClient.java
public void setNamespacePrefix(String prefix, String name) throws IOException, RepositoryException, UnauthorizedException { checkRepositoryURL();//from w w w . j a va 2s . c o m EntityEnclosingMethod method = new PutMethod(Protocol.getNamespacePrefixLocation(repositoryURL, prefix)); setDoAuthentication(method); method.setRequestEntity(new StringRequestEntity(name, "text/plain", "UTF-8")); try { int httpCode = httpClient.executeMethod(method); if (httpCode == HttpURLConnection.HTTP_UNAUTHORIZED) { throw new UnauthorizedException(); } else if (!is2xx(httpCode)) { ErrorInfo errInfo = getErrorInfo(method); throw new RepositoryException("Failed to set namespace: " + errInfo + " (" + httpCode + ")"); } } finally { releaseConnection(method); } }
From source file:org.owtf.runtime.core.ZestBasicRunner.java
private ZestResponse send(HttpClient httpclient, ZestRequest req) throws IOException { HttpMethod method;// ww w .jav a2s .c om URI uri = new URI(req.getUrl().toString(), false); switch (req.getMethod()) { case "GET": method = new GetMethod(uri.toString()); // Can only redirect on GETs method.setFollowRedirects(req.isFollowRedirects()); break; case "POST": method = new PostMethod(uri.toString()); break; case "OPTIONS": method = new OptionsMethod(uri.toString()); break; case "HEAD": method = new HeadMethod(uri.toString()); break; case "PUT": method = new PutMethod(uri.toString()); break; case "DELETE": method = new DeleteMethod(uri.toString()); break; case "TRACE": method = new TraceMethod(uri.toString()); break; default: throw new IllegalArgumentException("Method not supported: " + req.getMethod()); } setHeaders(method, req.getHeaders()); for (Cookie cookie : req.getCookies()) { // Replace any Zest variables in the value cookie.setValue(this.replaceVariablesInString(cookie.getValue(), false)); httpclient.getState().addCookie(cookie); } if (req.getMethod().equals("POST")) { // Do this after setting the headers so the length is corrected RequestEntity requestEntity = new StringRequestEntity(req.getData(), null, null); ((PostMethod) method).setRequestEntity(requestEntity); } int code = 0; String responseHeader = null; String responseBody = null; Date start = new Date(); try { this.debug(req.getMethod() + " : " + req.getUrl()); code = httpclient.executeMethod(method); responseHeader = method.getStatusLine().toString() + "\n" + arrayToStr(method.getResponseHeaders()); // httpclient.getParams().setParameter("http.method.response.buffer.warnlimit",new Integer(1000000000)); responseBody = method.getResponseBodyAsString(); } finally { method.releaseConnection(); } // Update the headers with the ones actually sent req.setHeaders(arrayToStr(method.getRequestHeaders())); return new ZestResponse(req.getUrl(), responseHeader, responseBody, code, new Date().getTime() - start.getTime()); }
From source file:org.ozsoft.xmldb.exist.ExistConnector.java
@Override public void storeResource(String uri, InputStream is) throws XmldbException { // Use the REST interface for storing resources. String actualUri = String.format("%s/rest%s", existUri, uri); PutMethod putMethod = new PutMethod(actualUri); putMethod.setRequestEntity(new InputStreamRequestEntity(is)); try {//from w w w . java 2 s . co m int statusCode = httpClient.executeMethod(putMethod); if (statusCode >= STATUS_ERROR) { if (statusCode == NOT_FOUND) { throw new NotFoundException(uri); } else if (statusCode == AUTHORIZATION_REQUIRED || statusCode == NOT_AUTHORIZED) { throw new NotAuthorizedException(String.format("Not authorized to store resource '%s'", uri)); } else { throw new XmldbException( String.format("Could not store resource '%s' (HTTP status code: %d)", uri, statusCode)); } } } catch (IOException e) { String msg = String.format("Could not store resource '%s': %s", uri, e.getMessage()); LOG.error(msg, e); throw new XmldbException(msg, e); } }
From source file:org.pengyou.client.lib.DavResource.java
/** * Execute the PUT method for the given path. * * @param path the server relative path to put the data * @param is The input stream.//w w w.j av a 2s . c om * @return true if the method is succeeded. * @exception HttpException * @exception IOException */ protected boolean putMethod() throws HttpException, IOException { log.debug("putMethod"); InputStream is = new ByteArrayInputStream(this.contentBody); HttpClient client = getSessionInstance(); PutMethod method = new PutMethod(context.getBaseUrl() + path); generateIfHeader(method); if (getContentType() != null && !getContentType().equals("")) method.setRequestHeader("Content-Type", getContentType()); method.setRequestContentLength(PutMethod.CONTENT_LENGTH_CHUNKED); method.setRequestBody(is); generateTransactionHeader(method); int statusCode = client.executeMethod(method); this.statusCode = statusCode; return (statusCode >= 200 && statusCode < 300) ? true : false; }
From source file:org.pentaho.di.baserver.utils.web.HttpConnectionHelper.java
protected HttpMethod getHttpMethod(String url, Map<String, String> queryParameters, String httpMethod) { org.pentaho.di.baserver.utils.inspector.HttpMethod method; if (httpMethod == null) { httpMethod = ""; }/*from w w w . jav a2 s . co m*/ try { method = org.pentaho.di.baserver.utils.inspector.HttpMethod.valueOf(httpMethod); } catch (IllegalArgumentException e) { logger.warn("Method '" + httpMethod + "' is not supported - using 'GET'"); method = org.pentaho.di.baserver.utils.inspector.HttpMethod.GET; } switch (method) { case GET: return new GetMethod(url + constructQueryString(queryParameters)); case POST: PostMethod postMethod = new PostMethod(url); setRequestEntity(postMethod, queryParameters); return postMethod; case PUT: PutMethod putMethod = new PutMethod(url); setRequestEntity(putMethod, queryParameters); return putMethod; case DELETE: return new DeleteMethod(url + constructQueryString(queryParameters)); case HEAD: return new HeadMethod(url + constructQueryString(queryParameters)); case OPTIONS: return new OptionsMethod(url + constructQueryString(queryParameters)); default: return new GetMethod(url + constructQueryString(queryParameters)); } }
From source file:org.review_board.ereviewboard.core.client.ReviewboardHttpClient.java
public String executePut(String url, Map<String, String> parameters, IProgressMonitor monitor) throws ReviewboardException { PutMethod putMethod = new PutMethod(stripSlash(location.getUrl()) + url); configureRequestForJson(putMethod);/*ww w . j a va 2s . c o m*/ List<NameValuePair> pairs = new ArrayList<NameValuePair>(); for (Map.Entry<String, String> entry : parameters.entrySet()) pairs.add(new NameValuePair(entry.getKey(), entry.getValue())); putMethod.setQueryString(pairs.toArray(new NameValuePair[0])); String queryString = putMethod.getQueryString(); putMethod.setQueryString(""); try { putMethod.setRequestEntity(new StringRequestEntity(queryString, null, "UTF-8")); } catch (UnsupportedEncodingException e) { throw new ReviewboardException(e.getMessage(), e); } return executeMethod(putMethod, monitor); }
From source file:org.roosster.api.TestApi.java
/** * // ww w. ja v a 2s . c om */ public void testApi() throws Exception { // FIRST ADD URL System.out.println("Trying to POST '" + TEST_URL + "' as a new entry to " + API_ENDPOINT); PostMethod post = new PostMethod(API_ENDPOINT + "?force=true"); post.setRequestEntity(postRequestBody); int statusCode = client.executeMethod(post); assertEquals("POST to " + TEST_URL + " failed", 200, statusCode); logMethodResponse(post); // ... THEN GET IT System.out.println("Trying to GET '" + TEST_URL + "' as a new entry to " + API_ENDPOINT); GetMethod get = new GetMethod(API_ENDPOINT + "/entry?url=" + TEST_URL); statusCode = client.executeMethod(get); assertEquals("GET from " + TEST_URL + " failed", 200, statusCode); logMethodResponse(get); // ... THEN UPDATE IT System.out.println("Trying to PUT '" + TEST_URL + "' as a new entry to " + API_ENDPOINT); PutMethod put = new PutMethod(API_ENDPOINT); put.setRequestEntity(putRequestBody); statusCode = client.executeMethod(put); assertEquals("PUT to " + TEST_URL + " failed", 200, statusCode); logMethodResponse(put); // ... THEN GET IT AGAIN System.out.println("Trying to GET '" + TEST_URL + "' as a new entry to " + API_ENDPOINT); get = new GetMethod(API_ENDPOINT + "/entry?url=" + TEST_URL); statusCode = client.executeMethod(get); assertEquals("GET from " + TEST_URL + " failed", 200, statusCode); logMethodResponse(get); // ... AND DELETE IT AGAIN System.out.println("Trying to DELETE '" + TEST_URL + "' as a new entry to " + API_ENDPOINT); DeleteMethod del = new DeleteMethod(API_ENDPOINT + "?url=" + TEST_URL); statusCode = client.executeMethod(del); assertEquals("GET from " + TEST_URL + " failed", 200, statusCode); logMethodResponse(get); // ... THEN GET IT AGAIN System.out.println("Trying to GET '" + TEST_URL + "' as a new entry to " + API_ENDPOINT); get = new GetMethod(API_ENDPOINT + "/entry?url=" + TEST_URL); statusCode = client.executeMethod(get); assertEquals("GET from " + TEST_URL + " failed", 200, statusCode); logMethodResponse(get); }