List of usage examples for org.apache.commons.httpclient.methods PutMethod PutMethod
public PutMethod(String paramString)
From source file:com.twinsoft.convertigo.beans.connectors.SiteClipperConnector.java
private void doProcessRequest(Shuttle shuttle) throws IOException, ServletException, EngineException { shuttle.statisticsTaskID = context.statistics.start(EngineStatistics.GET_DOCUMENT); try {/* w ww . ja v a 2 s.co m*/ shuttle.sharedScope = context.getSharedScope(); String domain = shuttle.getRequest(QueryPart.host) + shuttle.getRequest(QueryPart.port); Engine.logSiteClipper.trace("(SiteClipperConnector) Prepare the request for the domain " + domain); if (!shouldRewrite(domain)) { Engine.logSiteClipper.info( "(SiteClipperConnector) The domain " + domain + " is not allowed with this connector"); shuttle.response.sendError(HttpServletResponse.SC_FORBIDDEN, "The domain " + domain + " is not allowed with this connector"); return; } String uri = shuttle.getRequest(QueryPart.uri); Engine.logSiteClipper.info("Preparing " + shuttle.request.getMethod() + " " + shuttle.getRequestUrl()); HttpMethod httpMethod = null; XulRecorder xulRecorder = context.getXulRecorder(); if (xulRecorder != null) { httpMethod = shuttle.httpMethod = xulRecorder.getRecord(shuttle.getRequestUrlAndQuery()); } if (httpMethod == null) { try { switch (shuttle.getRequestHttpMethodType()) { case GET: httpMethod = new GetMethod(uri); break; case POST: httpMethod = new PostMethod(uri); ((PostMethod) httpMethod) .setRequestEntity(new InputStreamRequestEntity(shuttle.request.getInputStream())); break; case PUT: httpMethod = new PutMethod(uri); ((PutMethod) httpMethod) .setRequestEntity(new InputStreamRequestEntity(shuttle.request.getInputStream())); break; case DELETE: httpMethod = new DeleteMethod(uri); break; case HEAD: httpMethod = new HeadMethod(uri); break; case OPTIONS: httpMethod = new OptionsMethod(uri); break; case TRACE: httpMethod = new TraceMethod(uri); break; default: throw new ServletException( "(SiteClipperConnector) unknown http method " + shuttle.request.getMethod()); } httpMethod.setFollowRedirects(false); } catch (Exception e) { throw new ServletException( "(SiteClipperConnector) unexpected exception will building the http method : " + e.getMessage()); } shuttle.httpMethod = httpMethod; SiteClipperScreenClass screenClass = getCurrentScreenClass(); Engine.logSiteClipper.info("Request screen class: " + screenClass.getName()); for (String name : Collections .list(GenericUtils.<Enumeration<String>>cast(shuttle.request.getHeaderNames()))) { if (requestHeadersToIgnore.contains(HeaderName.parse(name))) { Engine.logSiteClipper.trace("(SiteClipperConnector) Ignoring request header " + name); } else { String value = shuttle.request.getHeader(name); Engine.logSiteClipper .trace("(SiteClipperConnector) Copying request header " + name + "=" + value); shuttle.setRequestCustomHeader(name, value); } } Engine.logSiteClipper.debug("(SiteClipperConnector) applying request rules for the screenclass " + screenClass.getName()); for (IRequestRule rule : screenClass.getRequestRules()) { if (rule.isEnabled()) { Engine.logSiteClipper .trace("(SiteClipperConnector) applying request rule " + rule.getName()); rule.fireEvents(); boolean done = rule.applyOnRequest(shuttle); Engine.logSiteClipper.debug("(SiteClipperConnector) the request rule " + rule.getName() + " is " + (done ? "well" : "not") + " applied"); } else { Engine.logSiteClipper .trace("(SiteClipperConnector) skip the disabled request rule " + rule.getName()); } } for (Entry<String, String> header : shuttle.requestCustomHeaders.entrySet()) { Engine.logSiteClipper.trace("(SiteClipperConnector) Push request header " + header.getKey() + "=" + header.getValue()); httpMethod.addRequestHeader(header.getKey(), header.getValue()); } String queryString = shuttle.request.getQueryString(); if (queryString != null) { try { // Fake test in order to check query string validity new URI("http://localhost/index?" + queryString, true, httpMethod.getParams().getUriCharset()); } catch (URIException e) { // Bugfix #2103 StringBuffer newQuery = new StringBuffer(); for (String part : RegexpUtils.pattern_and.split(queryString)) { String[] pair = RegexpUtils.pattern_equals.split(part, 2); try { newQuery.append('&') .append(URLEncoder.encode(URLDecoder.decode(pair[0], "UTF-8"), "UTF-8")); if (pair.length > 1) { newQuery.append('=').append( URLEncoder.encode(URLDecoder.decode(pair[1], "UTF-8"), "UTF-8")); } } catch (UnsupportedEncodingException ee) { Engine.logSiteClipper .trace("(SiteClipperConnector) failed to encode query part : " + part); } } queryString = newQuery.length() > 0 ? newQuery.substring(1) : newQuery.toString(); Engine.logSiteClipper.trace("(SiteClipperConnector) re-encode query : " + queryString); } } Engine.logSiteClipper.debug("(SiteClipperConnector) Copying the query string : " + queryString); httpMethod.setQueryString(queryString); // if (context.httpState == null) { // Engine.logSiteClipper.debug("(SiteClipperConnector) Creating new HttpState for context id " + context.contextID); // context.httpState = new HttpState(); // } else { // Engine.logSiteClipper.debug("(SiteClipperConnector) Using HttpState of context id " + context.contextID); // } getHttpState(shuttle); HostConfiguration hostConfiguration = getHostConfiguration(shuttle); HttpMethodParams httpMethodParams = httpMethod.getParams(); httpMethodParams.setBooleanParameter("http.connection.stalecheck", true); httpMethodParams.setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, true)); Engine.logSiteClipper.info("Requesting " + httpMethod.getName() + " " + hostConfiguration.getHostURL() + httpMethod.getURI().toString()); HttpClient httpClient = context.getHttpClient3(shuttle.getHttpPool()); HttpUtils.logCurrentHttpConnection(httpClient, hostConfiguration, shuttle.getHttpPool()); httpClient.executeMethod(hostConfiguration, httpMethod, context.httpState); } else { Engine.logSiteClipper.info("Retrieve recorded response from Context"); } int status = httpMethod.getStatusCode(); shuttle.processState = ProcessState.response; Engine.logSiteClipper.info("Request terminated with status " + status); shuttle.response.setStatus(status); if (Engine.isStudioMode() && status == HttpServletResponse.SC_OK && shuttle.getResponseMimeType().startsWith("text/")) { fireDataChanged(new ConnectorEvent(this, shuttle.getResponseAsString())); } SiteClipperScreenClass screenClass = getCurrentScreenClass(); Engine.logSiteClipper.info("Response screen class: " + screenClass.getName()); if (Engine.isStudioMode()) { Engine.theApp.fireObjectDetected(new EngineEvent(screenClass)); } for (Header header : httpMethod.getResponseHeaders()) { String name = header.getName(); if (responseHeadersToIgnore.contains(HeaderName.parse(name))) { Engine.logSiteClipper.trace("(SiteClipperConnector) Ignoring response header " + name); } else { String value = header.getValue(); Engine.logSiteClipper .trace("(SiteClipperConnector) Copying response header " + name + "=" + value); shuttle.responseCustomHeaders.put(name, value); } } Engine.logSiteClipper.debug( "(SiteClipperConnector) applying response rules for the screenclass " + screenClass.getName()); for (IResponseRule rule : screenClass.getResponseRules()) { if (rule.isEnabled()) { Engine.logSiteClipper.trace("(SiteClipperConnector) applying response rule " + rule.getName()); rule.fireEvents(); boolean done = rule.applyOnResponse(shuttle); Engine.logSiteClipper.debug("(SiteClipperConnector) the response rule " + rule.getName() + " is " + (done ? "well" : "not") + " applied"); } else { Engine.logSiteClipper .trace("(SiteClipperConnector) skip the disabled response rule " + rule.getName()); } } for (Entry<String, String> header : shuttle.responseCustomHeaders.entrySet()) { Engine.logSiteClipper.trace( "(SiteClipperConnector) Push request header " + header.getKey() + "=" + header.getValue()); shuttle.response.addHeader(header.getKey(), header.getValue()); } if (shuttle.postInstructions != null) { JSONArray instructions = new JSONArray(); for (IClientInstruction instruction : shuttle.postInstructions) { try { instructions.put(instruction.getInstruction()); } catch (JSONException e) { Engine.logSiteClipper.error( "(SiteClipperConnector) Failed to add a post instruction due to a JSONException", e); } } String codeToInject = "<script>C8O_postInstructions = " + instructions.toString() + "</script>\n" + "<script src=\"" + shuttle.getRequest(QueryPart.full_convertigo_path) + "/scripts/jquery.min.js\"></script>\n" + "<script src=\"" + shuttle.getRequest(QueryPart.full_convertigo_path) + "/scripts/siteclipper.js\"></script>\n"; String content = shuttle.getResponseAsString(); Matcher matcher = HtmlLocation.head_top.matcher(content); String newContent = RegexpUtils.inject(matcher, codeToInject); if (newContent == null) { matcher = HtmlLocation.body_top.matcher(content); newContent = RegexpUtils.inject(matcher, codeToInject); } if (newContent != null) { shuttle.setResponseAsString(newContent); } else { Engine.logSiteClipper.info( "(SiteClipperConnector) Failed to find a head or body tag in the response content"); Engine.logSiteClipper.trace("(SiteClipperConnector) Response content : \"" + content + "\""); } } long nbBytes = 0L; if (shuttle.responseAsString != null && shuttle.responseAsString.hashCode() != shuttle.responseAsStringOriginal.hashCode()) { OutputStream os = shuttle.response.getOutputStream(); switch (shuttle.getResponseContentEncoding()) { case gzip: os = new GZIPOutputStream(os); break; case deflate: os = new DeflaterOutputStream(os, new Deflater(Deflater.DEFAULT_COMPRESSION | Deflater.DEFAULT_STRATEGY, true)); break; default: break; } nbBytes = shuttle.responseAsByte.length; IOUtils.write(shuttle.responseAsString, os, shuttle.getResponseCharset()); os.close(); } else { InputStream is = (shuttle.responseAsByte == null) ? httpMethod.getResponseBodyAsStream() : new ByteArrayInputStream(shuttle.responseAsByte); if (is != null) { nbBytes = 0; OutputStream os = shuttle.response.getOutputStream(); int read = is.read(); while (read >= 0) { os.write(read); os.flush(); read = is.read(); nbBytes++; } is.close(); // nbBytes = IOUtils.copyLarge(is, shuttle.response.getOutputStream()); Engine.logSiteClipper .trace("(SiteClipperConnector) Response body copyied (" + nbBytes + " bytes)"); } } shuttle.response.getOutputStream().close(); shuttle.score = getScore(nbBytes); Engine.logSiteClipper .debug("(SiteClipperConnector) Request terminated with a score of " + shuttle.score); } finally { long duration = context.statistics.stop(shuttle.statisticsTaskID); if (context.requestedObject != null) { try { Engine.theApp.billingManager.insertBilling(context, Long.valueOf(duration), Long.valueOf(shuttle.score)); } catch (Exception e) { Engine.logContext.warn("Unable to insert billing ticket (the billing is thus ignored): [" + e.getClass().getName() + "] " + e.getMessage()); } } } }
From source file:com.liferay.portal.util.HttpImpl.java
protected byte[] URLtoByteArray(String location, Http.Method method, Map<String, String> headers, Cookie[] cookies, Http.Auth auth, Http.Body body, List<Http.FilePart> fileParts, Map<String, String> parts, Http.Response response, boolean followRedirects) throws IOException { byte[] bytes = null; HttpMethod httpMethod = null;/*w ww . j a v a2 s .c o m*/ HttpState httpState = null; try { _cookies.set(null); if (location == null) { return null; } else if (!location.startsWith(Http.HTTP_WITH_SLASH) && !location.startsWith(Http.HTTPS_WITH_SLASH)) { location = Http.HTTP_WITH_SLASH + location; } HostConfiguration hostConfiguration = getHostConfiguration(location); HttpClient httpClient = getClient(hostConfiguration); if (method.equals(Http.Method.POST) || method.equals(Http.Method.PUT)) { if (method.equals(Http.Method.POST)) { httpMethod = new PostMethod(location); } else { httpMethod = new PutMethod(location); } if (body != null) { RequestEntity requestEntity = new StringRequestEntity(body.getContent(), body.getContentType(), body.getCharset()); EntityEnclosingMethod entityEnclosingMethod = (EntityEnclosingMethod) httpMethod; entityEnclosingMethod.setRequestEntity(requestEntity); } else if (method.equals(Http.Method.POST)) { PostMethod postMethod = (PostMethod) httpMethod; processPostMethod(postMethod, fileParts, parts); } } else if (method.equals(Http.Method.DELETE)) { httpMethod = new DeleteMethod(location); } else if (method.equals(Http.Method.HEAD)) { httpMethod = new HeadMethod(location); } else { httpMethod = new GetMethod(location); } if (headers != null) { for (Map.Entry<String, String> header : headers.entrySet()) { httpMethod.addRequestHeader(header.getKey(), header.getValue()); } } if ((method.equals(Http.Method.POST) || method.equals(Http.Method.PUT)) && ((body != null) || ((fileParts != null) && !fileParts.isEmpty()) | ((parts != null) && !parts.isEmpty()))) { } else if (!hasRequestHeader(httpMethod, HttpHeaders.CONTENT_TYPE)) { httpMethod.addRequestHeader(HttpHeaders.CONTENT_TYPE, ContentTypes.APPLICATION_X_WWW_FORM_URLENCODED); } if (!hasRequestHeader(httpMethod, HttpHeaders.USER_AGENT)) { httpMethod.addRequestHeader(HttpHeaders.USER_AGENT, _DEFAULT_USER_AGENT); } httpState = new HttpState(); if ((cookies != null) && (cookies.length > 0)) { org.apache.commons.httpclient.Cookie[] commonsCookies = toCommonsCookies(cookies); httpState.addCookies(commonsCookies); HttpMethodParams httpMethodParams = httpMethod.getParams(); httpMethodParams.setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY); } if (auth != null) { httpMethod.setDoAuthentication(true); httpState.setCredentials(new AuthScope(auth.getHost(), auth.getPort(), auth.getRealm()), new UsernamePasswordCredentials(auth.getUsername(), auth.getPassword())); } proxifyState(httpState, hostConfiguration); httpClient.executeMethod(hostConfiguration, httpMethod, httpState); Header locationHeader = httpMethod.getResponseHeader("location"); if ((locationHeader != null) && !locationHeader.equals(location)) { String redirect = locationHeader.getValue(); if (followRedirects) { return URLtoByteArray(redirect, Http.Method.GET, headers, cookies, auth, body, fileParts, parts, response, followRedirects); } else { response.setRedirect(redirect); } } InputStream inputStream = httpMethod.getResponseBodyAsStream(); if (inputStream != null) { Header contentLength = httpMethod.getResponseHeader(HttpHeaders.CONTENT_LENGTH); if (contentLength != null) { response.setContentLength(GetterUtil.getInteger(contentLength.getValue())); } Header contentType = httpMethod.getResponseHeader(HttpHeaders.CONTENT_TYPE); if (contentType != null) { response.setContentType(contentType.getValue()); } bytes = FileUtil.getBytes(inputStream); } for (Header header : httpMethod.getResponseHeaders()) { response.addHeader(header.getName(), header.getValue()); } return bytes; } finally { try { if (httpState != null) { _cookies.set(toServletCookies(httpState.getCookies())); } } catch (Exception e) { _log.error(e, e); } try { if (httpMethod != null) { httpMethod.releaseConnection(); } } catch (Exception e) { _log.error(e, e); } } }
From source file:de.mpg.mpdl.inge.pubman.web.sword.SwordUtil.java
/** * Uploads a file to the staging servlet and returns the corresponding URL. * //w w w . j av a2 s . c om * @param InputStream to upload * @param mimetype The mimetype of the file * @param userHandle The userhandle to use for upload * @return The URL of the uploaded file. * @throws Exception If anything goes wrong... */ protected URL uploadFile(InputStream in, String mimetype, String userHandle, ZipEntry zipEntry) throws Exception { // Prepare the HttpMethod. String fwUrl = PropertyReader.getFrameworkUrl(); PutMethod method = new PutMethod(fwUrl + "/st/staging-file"); method.setRequestEntity(new InputStreamRequestEntity(in, -1)); method.setRequestHeader("Content-Type", mimetype); method.setRequestHeader("Cookie", "escidocCookie=" + userHandle); // Execute the method with HttpClient. HttpClient client = new HttpClient(); client.executeMethod(method); String response = method.getResponseBodyAsString(); InitialContext context = new InitialContext(); XmlTransformingBean ctransforming = new XmlTransformingBean(); return ctransforming.transformUploadResponseToFileURL(response); }
From source file:de.mpg.escidoc.pubman.sword.SwordUtil.java
/** * Uploads a file to the staging servlet and returns the corresponding URL. * @param InputStream to upload//w ww .j a v a 2 s. c om * @param mimetype The mimetype of the file * @param userHandle The userhandle to use for upload * @return The URL of the uploaded file. * @throws Exception If anything goes wrong... */ protected URL uploadFile(InputStream in, String mimetype, String userHandle, ZipEntry zipEntry) throws Exception { // Prepare the HttpMethod. String fwUrl = de.mpg.escidoc.services.framework.ServiceLocator.getFrameworkUrl(); PutMethod method = new PutMethod(fwUrl + "/st/staging-file"); method.setRequestEntity(new InputStreamRequestEntity(in, -1)); method.setRequestHeader("Content-Type", mimetype); method.setRequestHeader("Cookie", "escidocCookie=" + userHandle); // Execute the method with HttpClient. HttpClient client = new HttpClient(); client.executeMethod(method); String response = method.getResponseBodyAsString(); InitialContext context = new InitialContext(); XmlTransformingBean ctransforming = new XmlTransformingBean(); return ctransforming.transformUploadResponseToFileURL(response); }
From source file:com.zimbra.qa.unittest.TestCalDav.java
/** * dav - sending http error 302 because: wrong url - redirecting to: * http://pan.local:7070/dav/dav1@pan.local/Calendar/d123f102-42a7-4283-b025-3376dabe53b3.ics * com.zimbra.cs.dav.DavException: wrong url - redirecting to: * http://pan.local:7070/dav/dav1@pan.local/Calendar/d123f102-42a7-4283-b025-3376dabe53b3.ics * at com.zimbra.cs.dav.resource.CalendarCollection.createItem(CalendarCollection.java:431) * at com.zimbra.cs.dav.service.method.Put.handle(Put.java:49) * at com.zimbra.cs.dav.service.DavServlet.service(DavServlet.java:322) *///from www . j av a 2 s . c o m @Test public void testCreateUsingClientChosenName() throws ServiceException, IOException { Account dav1 = users[1].create(); String davBaseName = "clientInvented.now"; String calFolderUrl = getFolderUrl(dav1, "Calendar"); String url = String.format("%s%s", calFolderUrl, davBaseName); HttpClient client = new HttpClient(); PutMethod putMethod = new PutMethod(url); addBasicAuthHeaderForUser(putMethod, dav1); putMethod.addRequestHeader("Content-Type", "text/calendar"); putMethod.setRequestEntity(new ByteArrayRequestEntity(simpleEvent(dav1), MimeConstants.CT_TEXT_CALENDAR)); if (DebugConfig.enableDAVclientCanChooseResourceBaseName) { HttpMethodExecutor.execute(client, putMethod, HttpStatus.SC_CREATED); } else { HttpMethodExecutor.execute(client, putMethod, HttpStatus.SC_MOVED_TEMPORARILY); // Not testing much in this mode but... return; } doGetMethod(url, dav1, HttpStatus.SC_OK); PropFindMethod propFindMethod = new PropFindMethod(getFolderUrl(dav1, "Calendar")); addBasicAuthHeaderForUser(propFindMethod, dav1); TestCalDav.HttpMethodExecutor executor; String respBody; Element respElem; propFindMethod.addRequestHeader("Content-Type", MimeConstants.CT_TEXT_XML); propFindMethod.addRequestHeader("Depth", "1"); propFindMethod.setRequestEntity( new ByteArrayRequestEntity(propFindEtagResType.getBytes(), MimeConstants.CT_TEXT_XML)); executor = new TestCalDav.HttpMethodExecutor(client, propFindMethod, HttpStatus.SC_MULTI_STATUS); respBody = new String(executor.responseBodyBytes, MimeConstants.P_CHARSET_UTF8); respElem = Element.XMLElement.parseXML(respBody); assertEquals("name of top element in propfind response", DavElements.P_MULTISTATUS, respElem.getName()); assertTrue("propfind response should have child elements", respElem.hasChildren()); Iterator<Element> iter = respElem.elementIterator(); boolean hasCalendarHref = false; boolean hasCalItemHref = false; while (iter.hasNext()) { Element child = iter.next(); if (DavElements.P_RESPONSE.equals(child.getName())) { Iterator<Element> hrefIter = child.elementIterator(DavElements.P_HREF); while (hrefIter.hasNext()) { Element href = hrefIter.next(); calFolderUrl.endsWith(href.getText()); hasCalendarHref = hasCalendarHref || calFolderUrl.endsWith(href.getText()); hasCalItemHref = hasCalItemHref || url.endsWith(href.getText()); } } } assertTrue("propfind response contained entry for calendar", hasCalendarHref); assertTrue("propfind response contained entry for calendar entry ", hasCalItemHref); doDeleteMethod(url, dav1, HttpStatus.SC_NO_CONTENT); }
From source file:com.adobe.share.api.ShareAPI.java
/** * Prepares a new HTTP request./*ww w. ja v a2 s.co m*/ * * @param user the user * @param method the method * @param url the url * @param anon the anon * @param requestBody the request body * * @return the http method */ protected final HttpMethod createRequest(final ShareAPIUser user, final String method, final String url, final boolean anon, final String requestBody) { HttpMethod httpMethod = null; if ("GET".equals(method)) { httpMethod = new GetMethod(url); } else if ("POST".equals(method)) { httpMethod = new PostMethod(url); httpMethod.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); try { ((PostMethod) httpMethod).setRequestEntity(new StringRequestEntity(requestBody, null, null)); } catch (UnsupportedEncodingException uee) { // Catch the unsupported encoding exception LOGGER.error("Unsupported encoding exception: " + uee.getMessage()); } } else if ("PUT".equals(method)) { httpMethod = new PutMethod(url); httpMethod.setRequestHeader("Content-Type", "text/plain"); if (requestBody != null) { ((PutMethod) httpMethod).setRequestEntity( new InputStreamRequestEntity(new ByteArrayInputStream(requestBody.getBytes()))); } } else if ("DELETE".equals(method)) { httpMethod = new DeleteMethod(url); } else if ("HEAD".equals(method)) { httpMethod = new HeadMethod(url); } /** * MoveMethod not supported by HttpClient else if("MOVE".equals(method)) * { httpMethod = new MoveMethod(url); } **/ httpMethod.setRequestHeader("Authorization", generateAuthorization(user, anon, method, url)); return httpMethod; }
From source file:com.twelve.capital.external.feed.util.HttpImpl.java
protected byte[] URLtoByteArray(String location, Http.Method method, Map<String, String> headers, Cookie[] cookies, Http.Auth auth, Http.Body body, List<Http.FilePart> fileParts, Map<String, String> parts, Http.Response response, boolean followRedirects, String progressId, PortletRequest portletRequest) throws IOException { byte[] bytes = null; HttpMethod httpMethod = null;//from ww w .jav a 2 s . c o m HttpState httpState = null; try { _cookies.set(null); if (location == null) { return null; } else if (!location.startsWith(Http.HTTP_WITH_SLASH) && !location.startsWith(Http.HTTPS_WITH_SLASH)) { location = Http.HTTP_WITH_SLASH + location; } HostConfiguration hostConfiguration = getHostConfiguration(location); HttpClient httpClient = getClient(hostConfiguration); if (method.equals(Http.Method.POST) || method.equals(Http.Method.PUT)) { if (method.equals(Http.Method.POST)) { httpMethod = new PostMethod(location); } else { httpMethod = new PutMethod(location); } if (body != null) { RequestEntity requestEntity = new StringRequestEntity(body.getContent(), body.getContentType(), body.getCharset()); EntityEnclosingMethod entityEnclosingMethod = (EntityEnclosingMethod) httpMethod; entityEnclosingMethod.setRequestEntity(requestEntity); } else if (method.equals(Http.Method.POST)) { PostMethod postMethod = (PostMethod) httpMethod; if (!hasRequestHeader(postMethod, HttpHeaders.CONTENT_TYPE)) { HttpClientParams httpClientParams = httpClient.getParams(); httpClientParams.setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, StringPool.UTF8); } processPostMethod(postMethod, fileParts, parts); } } else if (method.equals(Http.Method.DELETE)) { httpMethod = new DeleteMethod(location); } else if (method.equals(Http.Method.HEAD)) { httpMethod = new HeadMethod(location); } else { httpMethod = new GetMethod(location); } if (headers != null) { for (Map.Entry<String, String> header : headers.entrySet()) { httpMethod.addRequestHeader(header.getKey(), header.getValue()); } } if ((method.equals(Http.Method.POST) || method.equals(Http.Method.PUT)) && ((body != null) || ((fileParts != null) && !fileParts.isEmpty()) || ((parts != null) && !parts.isEmpty()))) { } else if (!hasRequestHeader(httpMethod, HttpHeaders.CONTENT_TYPE)) { httpMethod.addRequestHeader(HttpHeaders.CONTENT_TYPE, ContentTypes.APPLICATION_X_WWW_FORM_URLENCODED_UTF8); } if (!hasRequestHeader(httpMethod, HttpHeaders.USER_AGENT)) { httpMethod.addRequestHeader(HttpHeaders.USER_AGENT, _DEFAULT_USER_AGENT); } httpState = new HttpState(); if (ArrayUtil.isNotEmpty(cookies)) { org.apache.commons.httpclient.Cookie[] commonsCookies = toCommonsCookies(cookies); httpState.addCookies(commonsCookies); HttpMethodParams httpMethodParams = httpMethod.getParams(); httpMethodParams.setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY); } if (auth != null) { httpMethod.setDoAuthentication(true); httpState.setCredentials(new AuthScope(auth.getHost(), auth.getPort(), auth.getRealm()), new UsernamePasswordCredentials(auth.getUsername(), auth.getPassword())); } proxifyState(httpState, hostConfiguration); int responseCode = httpClient.executeMethod(hostConfiguration, httpMethod, httpState); response.setResponseCode(responseCode); Header locationHeader = httpMethod.getResponseHeader("location"); if ((locationHeader != null) && !locationHeader.equals(location)) { String redirect = locationHeader.getValue(); if (followRedirects) { return URLtoByteArray(redirect, Http.Method.GET, headers, cookies, auth, body, fileParts, parts, response, followRedirects, progressId, portletRequest); } else { response.setRedirect(redirect); } } InputStream inputStream = httpMethod.getResponseBodyAsStream(); if (inputStream != null) { int contentLength = 0; Header contentLengthHeader = httpMethod.getResponseHeader(HttpHeaders.CONTENT_LENGTH); if (contentLengthHeader != null) { contentLength = GetterUtil.getInteger(contentLengthHeader.getValue()); response.setContentLength(contentLength); } Header contentType = httpMethod.getResponseHeader(HttpHeaders.CONTENT_TYPE); if (contentType != null) { response.setContentType(contentType.getValue()); } if (Validator.isNotNull(progressId) && (portletRequest != null)) { ProgressInputStream progressInputStream = new ProgressInputStream(portletRequest, inputStream, contentLength, progressId); UnsyncByteArrayOutputStream unsyncByteArrayOutputStream = new UnsyncByteArrayOutputStream( contentLength); try { progressInputStream.readAll(unsyncByteArrayOutputStream); } finally { progressInputStream.clearProgress(); } bytes = unsyncByteArrayOutputStream.unsafeGetByteArray(); unsyncByteArrayOutputStream.close(); } else { bytes = FileUtil.getBytes(inputStream); } } for (Header header : httpMethod.getResponseHeaders()) { response.addHeader(header.getName(), header.getValue()); } return bytes; } finally { try { if (httpState != null) { _cookies.set(toServletCookies(httpState.getCookies())); } } catch (Exception e) { _log.error(e, e); } try { if (httpMethod != null) { httpMethod.releaseConnection(); } } catch (Exception e) { _log.error(e, e); } } }
From source file:com.zimbra.qa.unittest.TestCalDav.java
public HttpMethodExecutor doIcalPut(String url, Account authAcct, byte[] vcalendar, int expected) throws IOException { HttpClient client = new HttpClient(); PutMethod putMethod = new PutMethod(url); addBasicAuthHeaderForUser(putMethod, authAcct); putMethod.addRequestHeader("Content-Type", "text/calendar"); putMethod.setRequestEntity(new ByteArrayRequestEntity(vcalendar, MimeConstants.CT_TEXT_CALENDAR)); return HttpMethodExecutor.execute(client, putMethod, expected); }
From source file:muki.tool.JavaCompilationDeploymentTestCase.java
@Test public void testPutOperation1() throws Exception { String url = URL_RESOURCE1 + "/pathPutOperation1"; PutMethod method = new PutMethod(url); int statusCode = this.getHttpClient().executeMethod(method); assertTrue("Method failed: " + method.getStatusLine(), statusCode == HttpStatus.SC_NO_CONTENT); byte[] responseBody = method.getResponseBody(); assertNull(responseBody);/*from w w w . ja v a2 s.com*/ }
From source file:muki.tool.JavaCompilationDeploymentTestCase.java
@Test public void testPutOperation2() throws Exception { String url = URL_RESOURCE1 + "/pathPutOperation2"; PutMethod method = new PutMethod(url); String param = "this is string parameter!"; method.setRequestEntity(new StringRequestEntity(param, "application/xml", null)); int statusCode = this.getHttpClient().executeMethod(method); assertTrue("Method failed: " + method.getStatusLine(), statusCode == HttpStatus.SC_NO_CONTENT); byte[] responseBody = method.getResponseBody(); assertNull(responseBody);/* w ww . ja v a 2 s .co m*/ }