List of usage examples for org.apache.commons.httpclient.methods PostMethod setRequestEntity
public void setRequestEntity(RequestEntity paramRequestEntity)
From source file:com.zimbra.qa.unittest.TestCalDav.java
@Test public void testPostToSchedulingOutbox() throws Exception { Account dav1 = users[1].create();/* w w w .j a va 2s .co m*/ Account dav2 = users[2].create(); Account dav3 = users[3].create(); String url = getSchedulingOutboxUrl(dav1, dav1); HttpClient client = new HttpClient(); PostMethod method = new PostMethod(url); addBasicAuthHeaderForUser(method, dav1); method.addRequestHeader("Content-Type", "text/calendar"); method.addRequestHeader("Originator", "mailto:" + dav1.getName()); method.addRequestHeader("Recipient", "mailto:" + dav2.getName()); method.addRequestHeader("Recipient", "mailto:" + dav3.getName()); method.setRequestEntity(new ByteArrayRequestEntity(exampleCancelIcal(dav1, dav2, dav3).getBytes(), MimeConstants.CT_TEXT_CALENDAR)); HttpMethodExecutor.execute(client, method, HttpStatus.SC_OK); }
From source file:games.strategy.triplea.pbem.AxisAndAlliesForumPoster.java
public boolean postTurnSummary(final String message, final String subject) { try {/*from w w w . j av a2 s . co m*/ login(); // Now we load the post page, and find the hidden fields needed to post final GetMethod get = new GetMethod( "http://www.axisandallies.org/forums/index.php?action=post;topic=" + m_topicId + ".0"); int status = m_client.executeMethod(m_hostConfiguration, get, m_httpState); String body = get.getResponseBodyAsString(); if (status == 200) { String numReplies; String seqNum; String sc; Matcher m = NUM_REPLIES_PATTERN.matcher(body); if (m.matches()) { numReplies = m.group(1); } else { throw new Exception("Hidden field 'num_replies' not found on page"); } m = SEQ_NUM_PATTERN.matcher(body); if (m.matches()) { seqNum = m.group(1); } else { throw new Exception("Hidden field 'seqnum' not found on page"); } m = SC_PATTERN.matcher(body); if (m.matches()) { sc = m.group(1); } else { throw new Exception("Hidden field 'sc' not found on page"); } // now we have the required hidden fields to reply to final PostMethod post = new PostMethod( "http://www.axisandallies.org/forums/index.php?action=post2;start=0;board=40"); try { // Construct the multi part post final List<Part> parts = new ArrayList<Part>(); parts.add(createStringPart("topic", m_topicId)); parts.add(createStringPart("subject", subject)); parts.add(createStringPart("icon", "xx")); parts.add(createStringPart("message", message)); // If the user has chosen to receive notifications, ensure this setting is passed on parts.add(createStringPart("notify", NOTIFY_PATTERN.matcher(body).matches() ? "1" : "0")); if (m_includeSaveGame && m_saveGameFile != null) { final FilePart part = new FilePart("attachment[]", m_saveGameFileName, m_saveGameFile); part.setContentType("application/octet-stream"); part.setTransferEncoding(null); part.setCharSet(null); parts.add(part); } parts.add(createStringPart("post", "Post")); parts.add(createStringPart("num_replies", numReplies)); parts.add(createStringPart("additional_options", "1")); parts.add(createStringPart("sc", sc)); parts.add(createStringPart("seqnum", seqNum)); final MultipartRequestEntity entity = new MultipartRequestEntity( parts.toArray(new Part[parts.size()]), new HttpMethodParams()); post.setRequestEntity(entity); // add headers post.addRequestHeader("Referer", "http://www.axisandallies.org/forums/index.php?action=post;topic=" + m_topicId + ".0;num_replies=" + numReplies); post.addRequestHeader("Accept", "*/*"); try { // the site has spam prevention which means you can't post until 15 seconds after login Thread.sleep(15 * 1000); } catch (final InterruptedException ie) { ie.printStackTrace(); // this should never happen } post.setFollowRedirects(false); status = m_client.executeMethod(m_hostConfiguration, post, m_httpState); body = post.getResponseBodyAsString(); if (status == 302) { // site responds with a 302 redirect back to the forum index (board=40) // The syntax for post is ".....topic=xx.yy" where xx is the thread id, and yy is the post number in the given thread // since the site is lenient we can just give a high post_number to go to the last post in the thread m_turnSummaryRef = "http://www.axisandallies.org/forums/index.php?topic=" + m_topicId + ".10000"; } else { // these two patterns find general errors, where the first pattern checks if the error text appears, // the second pattern extracts the error message. This could be the "The last posting from your IP was less than 15 seconds ago.Please try again later" // this patter finds errors that are marked in red (for instance "You are not allowed to post URLs", or // "Some one else has posted while you vere reading" Matcher matcher = ERROR_LIST_PATTERN.matcher(body); if (matcher.matches()) { throw new Exception("The site gave an error: '" + matcher.group(1) + "'"); } matcher = AN_ERROR_OCCURRED_PATTERN.matcher(body); if (matcher.matches()) { matcher = ERROR_TEXT_PATTERN.matcher(body); if (matcher.matches()) { throw new Exception("The site gave an error: '" + matcher.group(1) + "'"); } } final Header refreshHeader = post.getResponseHeader("Refresh"); if (refreshHeader != null) { // sometimes the message will be flagged as spam, and a refresh url is given final String value = refreshHeader.getValue(); // refresh: 0; URL=http://...topic=26114.new%3bspam=true#new final Pattern p = Pattern.compile("[^;]*;\\s*url=.*spam=true.*", Pattern.DOTALL | Pattern.CASE_INSENSITIVE); m = p.matcher(value); if (m.matches()) { throw new Exception("The summary was posted but was flagged as spam"); } } throw new Exception( "Unknown error, please contact the forum owner and also post a bug to the tripleA development team"); } } finally { post.releaseConnection(); // Commented out log out call since it was causing all of a user's sessions to be logged out and doesn't appear to be needed // final GetMethod logout = new GetMethod("http://www.axisandallies.org/forums/index.php?action=logout;sesc=" + sc); // try // { // status = m_client.executeMethod(m_hostConfiguration, logout, m_httpState); // // site responds with a 200 + Refresh header to redirect to index.php // if (status != 200) // { // // nothing we can do if this fails // } // } finally // { // logout.releaseConnection(); // } } } else { throw new Exception("Unable to load forum post " + m_topicId); } } catch (final Exception e) { m_turnSummaryRef = e.getMessage(); return false; } return true; }
From source file:edu.tsinghua.lumaqq.test.CustomHeadUploader.java
/** * /* w w w . j ava2s. c o m*/ * * @param filename */ public void upload(String filename, QQUser user) { HttpClient client = new HttpClient(); HostConfiguration conf = new HostConfiguration(); conf.setHost(QQ.QQ_SERVER_UPLOAD_CUSTOM_HEAD); client.setHostConfiguration(conf); PostMethod method = new PostMethod("/cgi-bin/cface/upload"); method.addRequestHeader("Accept", "*/*"); method.addRequestHeader("Pragma", "no-cache"); StringPart uid = new StringPart("clientuin", String.valueOf(user.getQQ())); uid.setContentType(null); uid.setTransferEncoding(null); //StringPart clientkey = new StringPart("clientkey", "0D649E66B0C1DBBDB522CE9C846754EF6AFA10BBF1A48A532DF6369BBCEF6EE7"); //StringPart clientkey = new StringPart("clientkey", "3285284145CC19EC0FFB3B25E4F6817FF3818B0E72F1C4E017D9238053BA2040"); StringPart clientkey = new StringPart("clientkey", "2FEEBE858DAEDFE6352870E32E5297ABBFC8C87125F198A5232FA7ADA9EADE67"); //StringPart clientkey = new StringPart("clientkey", "8FD643A7913C785AB612F126C6CD68A253F459B90EBCFD9375053C159418AF16"); // StringPart clientkey = new StringPart("clientkey", Util.convertByteToHexStringWithoutSpace(user.getClientKey())); clientkey.setContentType(null); clientkey.setTransferEncoding(null); //StringPart sign = new StringPart("sign", "2D139466226299A73F8BCDA7EE9AB157E8D9DA0BB38B6F4942A1658A00BD4C1FEE415838810E5AEF40B90E2AA384A875"); //StringPart sign = new StringPart("sign", "50F479417088F26EFC75B9BCCF945F35346188BB9ADD3BDF82098C9881DA086E3B28D56726D6CB2331909B62459E1E62"); //StringPart sign = new StringPart("sign", "31A69198C19A7C4BFB60DCE352FE2CC92C9D27E7C7FEADE1CBAAFD988906981ECC0DD1782CBAE88A2B716F84F9E285AA"); StringPart sign = new StringPart("sign", "68FFB636DE63D164D4072D7581213C77EC7B425DDFEB155428768E1E409935AA688AC88910A74C5D2D94D5EF2A3D1764"); sign.setContentType(null); sign.setTransferEncoding(null); FilePart file; try { file = new FilePart("customfacefile", filename, new File(filename)); } catch (FileNotFoundException e) { return; } Part[] parts = new Part[] { uid, clientkey, sign, file }; MultipartRequestEntity entity = new MultipartRequestEntity(parts, method.getParams()); method.setRequestEntity(entity); try { client.executeMethod(method); if (method.getStatusCode() == HttpStatus.SC_OK) { Header header = method.getResponseHeader("CFace-Msg"); System.out.println(header.getValue()); header = method.getResponseHeader("CFace-RetCode"); System.out.println(header.getValue()); } } catch (HttpException e) { return; } catch (IOException e) { return; } finally { method.releaseConnection(); } }
From source file:com.zimbra.qa.unittest.TestCalDav.java
public HttpMethodExecutor doFreeBusyCheck(Account organizer, List<Account> attendees, Date start, Date end) throws ServiceException, IOException { HttpClient client = new HttpClient(); String outboxurl = getSchedulingOutboxUrl(organizer, organizer); PostMethod postMethod = new PostMethod(outboxurl); postMethod.addRequestHeader("Content-Type", "text/calendar"); postMethod.addRequestHeader("Originator", "mailto:" + organizer.getName()); for (Account attendee : attendees) { postMethod.addRequestHeader("Recipient", "mailto:" + attendee.getName()); }//from w w w .ja v a 2s . c o m addBasicAuthHeaderForUser(postMethod, organizer); String fbIcal = makeFreeBusyRequestIcal(organizer, attendees, start, end); postMethod.setRequestEntity(new ByteArrayRequestEntity(fbIcal.getBytes(), MimeConstants.CT_TEXT_CALENDAR)); return HttpMethodExecutor.execute(client, postMethod, HttpStatus.SC_OK); }
From source file:JiraWebClient.java
public void attachFile(final JiraIssue issue, final String comment, final FilePart filePart, final String contentType, IProgressMonitor monitor) throws JiraException { doInSession(monitor, new JiraWebSessionCallback() { @Override/*from ww w.j a va2 s .co m*/ public void run(JiraClient server, String baseUrl, IProgressMonitor monitor) throws JiraException { StringBuilder attachFileURLBuffer = new StringBuilder(baseUrl); attachFileURLBuffer.append("/secure/AttachFile.jspa"); //$NON-NLS-1$ PostMethod post = new PostMethod(attachFileURLBuffer.toString()); prepareSecurityToken(post); List<PartBase> parts = new ArrayList<PartBase>(); StringPart idPart = new StringPart("id", issue.getId()); //$NON-NLS-1$ StringPart commentLevelPart = new StringPart("commentLevel", ""); //$NON-NLS-1$ //$NON-NLS-2$ // The transfer encodings have to be removed for some reason // There is no need to send the content types for the strings, // as they should be in the correct format idPart.setTransferEncoding(null); idPart.setContentType(null); if (comment != null) { StringPart commentPart = new StringPart("comment", comment); //$NON-NLS-1$ commentPart.setTransferEncoding(null); commentPart.setContentType(null); commentPart.setCharSet(client.getCharacterEncoding(monitor)); parts.add(commentPart); } commentLevelPart.setTransferEncoding(null); commentLevelPart.setContentType(null); filePart.setTransferEncoding(null); if (contentType != null) { filePart.setContentType(contentType); } parts.add(filePart); parts.add(idPart); parts.add(commentLevelPart); post.setRequestEntity( new MultipartRequestEntity(parts.toArray(new Part[parts.size()]), post.getParams())); try { execute(post); if (!expectRedirect(post, "/secure/ManageAttachments.jspa?id=" + issue.getId())) { //$NON-NLS-1$ handleErrorMessage(post); } } finally { post.releaseConnection(); } } }); }
From source file:edu.harvard.hmdc.dvnplugin.DVNOAIUrlCacher.java
private boolean processTermsOfUseResponse() throws IOException { //get the location header to find out where to redirect to String location = conn.getResponseHeaderValue("location"); releaseConnection();//from w w w . ja v a 2 s.c o m GetMethod method = null; int status = 200; String jsessionid = null; try { logger.debug3("making Get method " + location + "&clicker=downloadServlet"); method = new GetMethod(location + "&clicker=downloadServlet"); // instruct method not to follow redirects: method.setFollowRedirects(false); logger.debug3("executing method"); status = getClient().executeMethod(method); InputStream in = method.getResponseBodyAsStream(); BufferedReader rd = new BufferedReader(new InputStreamReader(in)); String line = null; String vdcid = null; String viewstate = null; String studyid = null; String remotefileid = null; String regexpJsession = "jsessionid=([^\"?&]*)"; String regexpViewState = "ViewState\" value=\"([^\"]*)\""; String regexpStudyId = "studyId\" value=\"([0-9]*)\""; String regexpRemoteFileId = "fileId=([0-9]*)"; Pattern patternJsession = Pattern.compile(regexpJsession); Pattern patternViewState = Pattern.compile(regexpViewState); Pattern patternStudyId = Pattern.compile(regexpStudyId); Pattern patternRemoteFileId = Pattern.compile(regexpRemoteFileId); Matcher matcher = null; matcher = patternRemoteFileId.matcher(fetchUrl); if (matcher.find()) { remotefileid = matcher.group(1); logger.debug3("TermsOfUse: found fileid " + remotefileid); } while ((line = rd.readLine()) != null) { matcher = patternJsession.matcher(line); if (matcher.find()) { jsessionid = matcher.group(1); logger.debug3("TermsOfUse: found jsessionid " + jsessionid); } matcher = patternViewState.matcher(line); if (matcher.find()) { viewstate = matcher.group(1); logger.debug3("TermsOfUse: found viewstate " + viewstate); } matcher = patternStudyId.matcher(line); if (matcher.find()) { studyid = matcher.group(1); logger.debug3("TermsOfUse: found studyid " + studyid); } } rd.close(); method.releaseConnection(); logger.debug3("released TermsOfUse GET connection"); //boolean notTrue = false; //if ( notTrue ) { if (jsessionid != null) { logger.debug3("TermsOfUse: obtained authorization information"); location = location.substring(0, location.indexOf("?")); logger.debug3("Connecting again " + location + ";jsessionid=" + jsessionid); PostMethod TOUpostMethod = new PostMethod(location + ";jsessionid=" + jsessionid); // instruct method not to follow redirects: TOUpostMethod.setFollowRedirects(false); Part[] parts = { new StringPart("pageName", "TermsOfUsePage"), new StringPart("content:termsOfUsePageView:form1:vdcId", ""), new StringPart("content:termsOfUsePageView:form1:studyId", studyid), new StringPart("content:termsOfUsePageView:form1:redirectPage", "/FileDownload/?fileId=" + remotefileid), new StringPart("content:termsOfUsePageView:form1:tou", "download"), new StringPart("content:termsOfUsePageView:form1:termsAccepted", "on"), new StringPart("content:termsOfUsePageView:form1:termsButton", "Continue"), new StringPart("content:termsOfUsePageView:form1_hidden", "content:termsOfUsePageView:form1_hidden'"), new StringPart("javax.faces.ViewState", viewstate) }; TOUpostMethod.addRequestHeader("Cookie", "JSESSIONID=" + jsessionid); TOUpostMethod.setRequestEntity(new MultipartRequestEntity(parts, TOUpostMethod.getParams())); status = getClient().executeMethod(TOUpostMethod); // TODO -- more diagnostics needed here! logger.debug3("TermsOfUse POST: received code " + status); if (status == 302) { String newLocation = null; for (int i = 0; i < TOUpostMethod.getResponseHeaders().length; i++) { String headerName = TOUpostMethod.getResponseHeaders()[i].getName(); if (headerName.equals("Location")) { newLocation = TOUpostMethod.getResponseHeaders()[i].getValue(); } } logger.debug3("TermsOfUse POST: redirected to " + newLocation); } TOUpostMethod.releaseConnection(); logger.debug3("released TermsOfUse POST connection"); } // } catch (IOException e) { //logger.debug2("failed to access TermsOfUse page", e); //return false; } catch (MalformedURLException ex) { logger.debug2("failed to acquire TermsOfUse authorization", ex); return false; } catch (IOException ex) { logger.debug2("failed to acquire TermsOfUse authorization", ex); return false; } catch (RuntimeException e) { logger.warning("failed to acquire TermsOfUse authorization", e); return false; } // OK, we can try again now! logger.debug3("trying to access the file again " + fetchUrl); try { conn = makeConnection(fetchUrl, connectionPool); if (localAddr != null) { conn.setLocalAddress(localAddr); } if (reqProps != null) { for (Iterator iter = reqProps.keySet().iterator(); iter.hasNext();) { String key = (String) iter.next(); conn.setRequestProperty(key, reqProps.getProperty(key)); } } conn.setRequestProperty("user-agent", LockssDaemon.getUserAgent()); String myCookie = "JSESSIONID=" + jsessionid; logger.debug3("setting cookie: " + myCookie); conn.addRequestProperty("Cookie", myCookie); logger.debug3("executing request"); conn.execute(); } catch (MalformedURLException ex) { logger.debug2("openConnection", ex); throw resultMap.getMalformedURLException(ex); } catch (IOException ex) { logger.debug2("openConnection", ex); throw resultMap.getHostException(ex); } catch (RuntimeException e) { logger.warning("openConnection: unexpected exception", e); throw e; } return true; }
From source file:com.panet.imeta.trans.steps.httppost.HTTPPOST.java
private Object[] callHTTPPOST(Object[] rowData) throws KettleException { // get dynamic url ? if (meta.isUrlInField()) data.realUrl = data.inputRowMeta.getString(rowData, data.indexOfUrlField); try {//from w ww . j av a 2 s . co m if (log.isDetailed()) logDetailed(Messages.getString("HTTPPOST.Log.ConnectingToURL", data.realUrl)); // Prepare HTTP POST // HttpClient HTTPPOSTclient = new HttpClient(); PostMethod post = new PostMethod(data.realUrl); //post.setFollowRedirects(false); // Specify content type and encoding // If content encoding is not explicitly specified // ISO-8859-1 is assumed if (Const.isEmpty(data.realEncoding)) post.setRequestHeader("Content-type", "text/xml"); else post.setRequestHeader("Content-type", "text/xml; " + data.realEncoding); // BODY PARAMETERS if (data.useBodyParameters) { // set body parameters that we want to send for (int i = 0; i < data.body_parameters_nrs.length; i++) { data.bodyParameters[i] .setValue(data.inputRowMeta.getString(rowData, data.body_parameters_nrs[i])); } post.setRequestBody(data.bodyParameters); } // QUERY PARAMETERS if (data.useQueryParameters) { for (int i = 0; i < data.query_parameters_nrs.length; i++) { data.queryParameters[i] .setValue(data.inputRowMeta.getString(rowData, data.query_parameters_nrs[i])); } post.setQueryString(data.queryParameters); } // Set request entity? if (data.indexOfRequestEntity >= 0) { String tmp = data.inputRowMeta.getString(rowData, data.indexOfRequestEntity); // Request content will be retrieved directly // from the input stream // Per default, the request content needs to be buffered // in order to determine its length. // Request body buffering can be avoided when // content length is explicitly specified if (meta.isPostAFile()) { File input = new File(tmp); post.setRequestEntity(new InputStreamRequestEntity(new FileInputStream(input), input.length())); } else { post.setRequestEntity( new InputStreamRequestEntity(new ByteArrayInputStream(tmp.getBytes()), tmp.length())); } } // Execute request // InputStream inputStream = null; try { // Execute the POST method int statusCode = HTTPPOSTclient.executeMethod(post); // Display status code if (log.isDebug()) log.logDebug(toString(), Messages.getString("HTTPPOST.Log.ResponseCode", "" + statusCode)); String body = null; if (statusCode != -1) { // the response inputStream = post.getResponseBodyAsStream(); StringBuffer bodyBuffer = new StringBuffer(); int c; while ((c = inputStream.read()) != -1) bodyBuffer.append((char) c); inputStream.close(); // Display response body = bodyBuffer.toString(); if (log.isDebug()) log.logDebug(toString(), Messages.getString("HTTPPOST.Log.ResponseBody", body)); } //return new Value(meta.getFieldName(), body); return RowDataUtil.addValueData(rowData, data.inputRowMeta.size(), body); } finally { if (inputStream != null) inputStream.close(); // Release current connection to the connection pool once you are done post.releaseConnection(); } } catch (Exception e) { throw new KettleException(Messages.getString("HTTPPOST.Error.CanNotReadURL", data.realUrl), e); } }
From source file:com.zimbra.common.soap.SoapHttpTransport.java
public Element invoke(Element document, boolean raw, boolean noSession, String requestedAccountId, String changeToken, String tokenType, ResponseHandler respHandler) throws IOException, HttpException, ServiceException { PostMethod method = null; try {/*w w w . j a v a 2 s .co m*/ // Assemble post method. Append document name, so that the request // type is written to the access log. String uri, query; int i = mUri.indexOf('?'); if (i >= 0) { uri = mUri.substring(0, i); query = mUri.substring(i); } else { uri = mUri; query = ""; } if (!uri.endsWith("/")) uri += '/'; uri += getDocumentName(document); method = new PostMethod(uri + query); // Set user agent if it's specified. String agentName = getUserAgentName(); if (agentName != null) { String agentVersion = getUserAgentVersion(); if (agentVersion != null) agentName += " " + agentVersion; method.setRequestHeader(new Header("User-Agent", agentName)); } // the content-type charset will determine encoding used // when we set the request body method.setRequestHeader("Content-Type", getRequestProtocol().getContentType()); if (getClientIp() != null) { method.setRequestHeader(RemoteIP.X_ORIGINATING_IP_HEADER, getClientIp()); if (ZimbraLog.misc.isDebugEnabled()) { ZimbraLog.misc.debug("set remote IP header [%s] to [%s]", RemoteIP.X_ORIGINATING_IP_HEADER, getClientIp()); } } Element soapReq = generateSoapMessage(document, raw, noSession, requestedAccountId, changeToken, tokenType); String soapMessage = SoapProtocol.toString(soapReq, getPrettyPrint()); HttpMethodParams params = method.getParams(); method.setRequestEntity(new StringRequestEntity(soapMessage, null, "UTF-8")); if (getRequestProtocol().hasSOAPActionHeader()) method.setRequestHeader("SOAPAction", mUri); if (mCustomHeaders != null) { for (Map.Entry<String, String> entry : mCustomHeaders.entrySet()) method.setRequestHeader(entry.getKey(), entry.getValue()); } String host = method.getURI().getHost(); HttpState state = HttpClientUtil.newHttpState(getAuthToken(), host, this.isAdmin()); String trustedToken = getTrustedToken(); if (trustedToken != null) { state.addCookie( new Cookie(host, ZimbraCookie.COOKIE_ZM_TRUST_TOKEN, trustedToken, "/", null, false)); } params.setCookiePolicy(state.getCookies().length == 0 ? CookiePolicy.IGNORE_COOKIES : CookiePolicy.BROWSER_COMPATIBILITY); params.setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(mRetryCount - 1, true)); params.setSoTimeout(mTimeout); params.setVersion(HttpVersion.HTTP_1_1); method.setRequestHeader("Connection", mKeepAlive ? "Keep-alive" : "Close"); if (mHostConfig != null && mHostConfig.getUsername() != null && mHostConfig.getPassword() != null) { state.setProxyCredentials(new AuthScope(null, -1), new UsernamePasswordCredentials(mHostConfig.getUsername(), mHostConfig.getPassword())); } if (mHttpDebugListener != null) { mHttpDebugListener.sendSoapMessage(method, soapReq, state); } int responseCode = mClient.executeMethod(mHostConfig, method, state); // SOAP allows for "200" on success and "500" on failure; // real server issues will probably be "503" or "404" if (responseCode != HttpServletResponse.SC_OK && responseCode != HttpServletResponse.SC_INTERNAL_SERVER_ERROR) throw ServiceException.PROXY_ERROR(method.getStatusLine().toString(), uri); // Read the response body. Use the stream API instead of the byte[] // version to avoid HTTPClient whining about a large response. InputStreamReader reader = new InputStreamReader(method.getResponseBodyAsStream(), SoapProtocol.getCharset()); String responseStr = ""; try { if (respHandler != null) { respHandler.process(reader); return null; } else { responseStr = ByteUtil.getContent(reader, (int) method.getResponseContentLength(), false); Element soapResp = parseSoapResponse(responseStr, raw); if (mHttpDebugListener != null) { mHttpDebugListener.receiveSoapMessage(method, soapResp); } return soapResp; } } catch (SoapFaultException x) { // attach request/response to the exception and rethrow x.setFaultRequest(soapMessage); x.setFaultResponse(responseStr.substring(0, Math.min(10240, responseStr.length()))); throw x; } } finally { // Release the connection to the connection manager if (method != null) method.releaseConnection(); // really not necessary if running in the server because the reaper thread // of our connection manager will take care it. // if called from CLI, all connections will be closed when the CLI // exits. Leave it here anyway. if (!mKeepAlive) mClient.getHttpConnectionManager().closeIdleConnections(0); } }
From source file:com.day.cq.wcm.foundation.impl.Rewriter.java
/** * Process a page./*from www . j a v a2s . co m*/ */ public void rewrite(HttpServletRequest request, HttpServletResponse response) throws IOException { try { targetURL = new URI(target); } catch (URISyntaxException e) { IOException ioe = new IOException("Bad URI syntax: " + target); ioe.initCause(e); throw ioe; } setHostPrefix(targetURL); HttpClient httpClient = new HttpClient(); HttpState httpState = new HttpState(); HostConfiguration hostConfig = new HostConfiguration(); HttpMethodBase httpMethod; // define host hostConfig.setHost(targetURL.getHost(), targetURL.getPort()); // create http method String method = (String) request.getAttribute("cq.ext.app.method"); if (method == null) { method = request.getMethod(); } method = method.toUpperCase(); boolean isPost = "POST".equals(method); String urlString = targetURL.getPath(); StringBuffer query = new StringBuffer(); if (targetURL.getQuery() != null) { query.append("?"); query.append(targetURL.getQuery()); } //------------ GET --------------- if ("GET".equals(method)) { // add internal props Iterator<String> iter = extraParams.keySet().iterator(); while (iter.hasNext()) { String name = iter.next(); String value = extraParams.get(name); if (query.length() == 0) { query.append("?"); } else { query.append("&"); } query.append(Text.escape(name)); query.append("="); query.append(Text.escape(value)); } if (passInput) { // add request params @SuppressWarnings("unchecked") Enumeration<String> e = request.getParameterNames(); while (e.hasMoreElements()) { String name = e.nextElement(); if (targetParamName.equals(name)) { continue; } String[] values = request.getParameterValues(name); for (int i = 0; i < values.length; i++) { if (query.length() == 0) { query.append("?"); } else { query.append("&"); } query.append(Text.escape(name)); query.append("="); query.append(Text.escape(values[i])); } } } httpMethod = new GetMethod(urlString + query); //------------ POST --------------- } else if ("POST".equals(method)) { PostMethod m = new PostMethod(urlString + query); httpMethod = m; String contentType = request.getContentType(); boolean mp = contentType != null && contentType.toLowerCase().startsWith("multipart/"); if (mp) { //------------ MULTPART POST --------------- List<Part> parts = new LinkedList<Part>(); Iterator<String> iter = extraParams.keySet().iterator(); while (iter.hasNext()) { String name = iter.next(); String value = extraParams.get(name); parts.add(new StringPart(name, value)); } if (passInput) { // add request params @SuppressWarnings("unchecked") Enumeration<String> e = request.getParameterNames(); while (e.hasMoreElements()) { String name = e.nextElement(); if (targetParamName.equals(name)) { continue; } String[] values = request.getParameterValues(name); for (int i = 0; i < values.length; i++) { parts.add(new StringPart(name, values[i])); } } } m.setRequestEntity( new MultipartRequestEntity(parts.toArray(new Part[parts.size()]), m.getParams())); } else { //------------ NORMAL POST --------------- // add internal props Iterator<String> iter = extraParams.keySet().iterator(); while (iter.hasNext()) { String name = iter.next(); String value = extraParams.get(name); m.addParameter(name, value); } if (passInput) { // add request params @SuppressWarnings("unchecked") Enumeration e = request.getParameterNames(); while (e.hasMoreElements()) { String name = (String) e.nextElement(); if (targetParamName.equals(name)) { continue; } String[] values = request.getParameterValues(name); for (int i = 0; i < values.length; i++) { m.addParameter(name, values[i]); } } } } } else { log.error("Unsupported method ''{0}''", method); throw new IOException("Unsupported http method " + method); } log.debug("created http connection for method {0} to {1}", method, urlString + query); // add some request headers httpMethod.addRequestHeader("User-Agent", request.getHeader("User-Agent")); httpMethod.setFollowRedirects(!isPost); httpMethod.getParams().setSoTimeout(soTimeout); httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(connectionTimeout); // send request httpClient.executeMethod(hostConfig, httpMethod, httpState); String contentType = httpMethod.getResponseHeader("Content-Type").getValue(); log.debug("External app responded: {0}", httpMethod.getStatusLine()); log.debug("External app contenttype: {0}", contentType); // check response code int statusCode = httpMethod.getStatusCode(); if (statusCode >= HttpURLConnection.HTTP_BAD_REQUEST) { PrintWriter writer = response.getWriter(); writer.println("External application returned status code: " + statusCode); return; } else if (statusCode == HttpURLConnection.HTTP_MOVED_TEMP || statusCode == HttpURLConnection.HTTP_MOVED_PERM) { String location = httpMethod.getResponseHeader("Location").getValue(); if (location == null) { response.sendError(HttpURLConnection.HTTP_NOT_FOUND); return; } response.sendRedirect(rewriteURL(location, false)); return; } // open input stream InputStream in = httpMethod.getResponseBodyAsStream(); // check content type if (contentType != null && contentType.startsWith("text/html")) { rewriteHtml(in, contentType, response); } else { // binary mode if (contentType != null) { response.setContentType(contentType); } OutputStream outs = response.getOutputStream(); try { byte buf[] = new byte[8192]; int len; while ((len = in.read(buf)) != -1) { outs.write(buf, 0, len); } } finally { if (in != null) { in.close(); } } } }
From source file:com.apatar.ui.Actions.java
private void publishToApatar() throws HttpException, IOException { JPublishToApatarDialog dlg = new JPublishToApatarDialog(ApatarUiMain.MAIN_FRAME); dlg.setVisible(true);//from ww w.j a v a 2s.c om if (dlg.getOption() == JPublishToApatarDialog.CANCEL_OPTION) { return; } PostMethod method = new PostMethod(PUBLISH_TO_APATAR_URL); File file; if (dlg.isSelectFromFile()) { file = new File(dlg.getFilePath()); } else { String tempFolderName = "tempdatamap/"; File tempFolder = new File(tempFolderName); if (!tempFolder.exists()) { tempFolder.mkdir(); } String fileName = "tempdatamap/" + dlg.getDataMapName().replaceAll("[|/\\:*?\"<> ]", "_") + ".aptr"; ReadWriteXMLDataUi rwXMLdata = new ReadWriteXMLDataUi(); file = rwXMLdata.writeXMLData(fileName.toString(), ApplicationData.getProject(), true); } Part[] parts = new Part[14]; parts[0] = new StringPart("option", "com_remository"); parts[1] = new StringPart("task", ""); parts[1] = new StringPart("func", "savefile"); parts[2] = new StringPart("element", "component"); parts[3] = new StringPart("client", ""); parts[4] = new StringPart("oldid", "0"); parts[5] = new FilePart("userfile", file); parts[6] = new StringPart("containerid", "" + dlg.getDataMapLocation().getId()); parts[7] = new StringPart("filetitle", dlg.getDataMapName()); parts[8] = new StringPart("description", dlg.getDataMapDescription()); parts[9] = new StringPart("smalldesc", dlg.getShortDescription()); parts[10] = new StringPart("filetags", dlg.getTags()); parts[11] = new StringPart("pubExternal", "true"); parts[12] = new StringPart("username", dlg.getUserName()); parts[13] = new StringPart("password", CoreUtils.getMD5(dlg.getPassword())); method.setRequestEntity(new MultipartRequestEntity(parts, method.getParams())); HttpClient client = new HttpClient(); client.getHttpConnectionManager().getParams().setConnectionTimeout(10000); int status = client.executeMethod(method); if (status != HttpStatus.SC_OK) { JOptionPane.showMessageDialog(ApatarUiMain.MAIN_FRAME, "Upload failed, response=" + HttpStatus.getStatusText(status)); } else { StringBuffer buff = new StringBuffer(method.getResponseBodyAsString()); try { Matcher matcher = ApatarRegExp.getMatcher("<meta name=\"apatarResponse\" content=\"[a-zA-Z_0-9]+\"", buff.toString()); boolean patternFound = false; while (matcher.find()) { patternFound = true; String result = matcher.group(); result = result.replaceFirst("<meta name=\"apatarResponse\" content=\"", ""); result = result.replace("\"", ""); if (result.equalsIgnoreCase("done")) { JOptionPane.showMessageDialog(ApatarUiMain.MAIN_FRAME, "File has been published"); } else if (result.equalsIgnoreCase("error_xml")) { JOptionPane.showMessageDialog(ApatarUiMain.MAIN_FRAME, "File is not valid"); } else if (result.equalsIgnoreCase("error_login")) { JOptionPane.showMessageDialog(ApatarUiMain.MAIN_FRAME, "Name or Password is not valid"); } } if (!patternFound) { JOptionPane.showMessageDialog(ApatarUiMain.MAIN_FRAME, "Wrong response from server. Please check your connection."); } } catch (ApatarException e) { e.printStackTrace(); } } }