List of usage examples for org.apache.commons.httpclient.methods PostMethod PostMethod
public PostMethod(String paramString)
From source file:com.duroty.controller.actions.GoogieSpellAction.java
protected ActionForward doExecute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { ActionMessages errors = new ActionMessages(); PostMethod post = null;/*w ww . j av a 2 s . co m*/ try { Enumeration enumeration = request.getParameterNames(); while (enumeration.hasMoreElements()) { String name = (String) enumeration.nextElement(); String value = (String) request.getParameter(name); DLog.log(DLog.WARN, this.getClass(), name + " >> " + value); } String text = "<?xml version=\"1.0\" encoding=\"utf-8\" ?><spellrequest textalreadyclipped=\"0\" ignoredups=\"0\" ignoredigits=\"1\" ignoreallcaps=\"1\"><text>" + request.getParameter("check") + "</text></spellrequest>"; String lang = request.getParameter("lang"); String id = request.getParameter("id"); String cmd = request.getParameter("cmd"); String url = "https://" + googleUrl + "/tbproxy/spell?lang=" + lang + "&hl=" + lang; post = new PostMethod(url); post.setRequestBody(text); post.setRequestHeader("Content-type", "text/xml; charset=ISO-8859-1"); HttpClient client = new HttpClient(); int result = client.executeMethod(post); // Display status code System.out.println("Response status code: " + result); // Display response System.out.println("Response body: "); String resp = post.getResponseBodyAsString(); System.out.println(resp); String goodieSpell = "<?xml version=\"1.0\" encoding=\"utf-8\" ?>\n"; Vector matches = getMatches(resp); if (matches.size() <= 0) { goodieSpell = goodieSpell + "<res id=\"" + id + "\" cmd=\"" + cmd + "\" />"; } else { goodieSpell = goodieSpell + "<res id=\"" + id + "\" cmd=\"" + cmd + "\">"; StringBuffer buffer = new StringBuffer(); for (int i = 0; i < matches.size(); i++) { if (buffer.length() > 0) { buffer.append("+"); } String aux = (String) matches.get(i); aux = aux.substring(aux.indexOf(">") + 1, aux.length()); aux = aux.substring(0, aux.indexOf("<")); aux = aux.trim().replaceAll("\\s+", "\\+"); buffer.append(aux); } goodieSpell = goodieSpell + buffer.toString() + "</res>"; } request.setAttribute("googieSpell", goodieSpell); } catch (Exception ex) { String errorMessage = ExceptionUtilities.parseMessage(ex); if (errorMessage == null) { errorMessage = "NullPointerException"; } errors.add("general", new ActionMessage(ExceptionCode.ERROR_MESSAGES_PREFIX + "general", errorMessage)); request.setAttribute("exception", errorMessage); doTrace(request, DLog.ERROR, getClass(), errorMessage); } finally { try { post.releaseConnection(); } catch (Exception e) { } } if (errors.isEmpty()) { doTrace(request, DLog.INFO, getClass(), "OK"); return mapping.findForward(Constants.ACTION_SUCCESS_FORWARD); } else { saveErrors(request, errors); return mapping.findForward(Constants.ACTION_FAIL_FORWARD); } }
From source file:com.snaker.DownloadManager.java
private Runnable createRunnable(final Downloader d) { final Task task = d.getTask(); return new Runnable() { @Override/* w w w . ja va 2 s .c o m*/ public void run() { logger.info("start download:" + d.getUrl()); HttpClient client = clients.get(task.getId()); DownloadHandler handler = d.getHandler(); HttpMethodBase m = null; d.setStatus(Status.STARTED); d.setStartTime(System.currentTimeMillis()); try { String url = d.getUrl(); if (d.isGet()) { GetMethod get = new GetMethod(url); m = get; } else { final String requestCharset = d.getRequestCharset(); PostMethod post = new PostMethod(url) { public String getRequestCharSet() { if (requestCharset != null) return requestCharset; else return super.getRequestCharSet(); } public boolean getFollowRedirects() { return d.isFollowRedirects(); } }; if (requestCharset != null) { post.setRequestHeader("ContentType", "application/x-www-form-urlencoded;charset=" + requestCharset); } DownloadParams parms = d.getParms(); if (parms != null) post.setRequestBody(parms.toNVP()); m = post; } { // set the headers m.setRequestHeader("User-Agent", "Mozilla/5.0 (Windows NT 5.1; rv:8.0.1) Gecko/20100101 Firefox/8.0.1"); m.setRequestHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"); m.setRequestHeader("Accept-Language", "en-us,zh-cn;q=0.5"); m.setRequestHeader("Accept-Charset", "ISO-8859-1,utf-8;q=0.7,*;q=0.7"); m.setRequestHeader("Referer", url); } client.executeMethod(m); //check status int sc = m.getStatusCode(); d.setStatusCode(sc); if (isBadStatusCode(sc)) { logger.error("download failed,url:" + d.getUrl() + ",Status Code:" + sc); d.setStatus(Status.FAILED); d.setDescription(m.getStatusText()); return; } else if (sc == 404 || sc == 410) { d.setStatus(Status.FINISHED); d.setDescription("NOT FOUND"); return; } long size = m.getResponseContentLength(); d.setFileSize(size); // get File Name if (d.getFileName() == null) { Header h = m.getResponseHeader("Content-Disposition"); String fileName = null; if (h != null) { String f = h.getValue(); int tag = f.indexOf("filename="); if (tag != -1 && tag != f.length() - 1) fileName = f.substring(tag + 1); } if (fileName == null || fileName.length() == 0) { int tag1 = url.lastIndexOf("/"); int tag2 = url.lastIndexOf("?"); if (tag1 != -1 && tag1 != url.length() - 1) { if (tag2 > tag1) { fileName = url.substring(tag1 + 1, tag2); } else { fileName = url.substring(tag1 + 1); } } } d.setFileName(fileName); } // set the all headers Header[] headers = m.getResponseHeaders(); if (headers != null) { for (Header header : headers) { d.addResponseHeader(header.getName(), header.getValue()); } } d.setStatus(Status.RUNNING); // recv the body if (handler == null) { byte[] content = m.getResponseBody(); int len = content.length; d.setFileSize(len); d.setReceived(len); d.setResponseCharset(m.getResponseCharSet()); d.setResponseBody(content); } else { InputStream is = m.getResponseBodyAsStream(); handler.start(d); byte[] buffer = new byte[102400]; long count = 0; while (true) { int r = is.read(buffer); if (r > 0) { count += r; d.setReceived(count); handler.handle(buffer, r); } else { break; } } is.close(); } d.setStatus(Status.FINISHED); } catch (Exception e) { logger.error("download failed,url:" + d.getUrl(), e); d.setStatus(Status.FAILED); d.setDescription(e.getMessage()); } finally { m.releaseConnection(); if (handler != null) { handler.stop(); } downloadings.remove(d); d.setEndTime(System.currentTimeMillis()); while (downloaded.size() >= maxDownloadedCount) { downloaded.poll(); } downloaded.offer(d); task.downloadFininshed(d); } } }; }
From source file:easyshop.downloadhelper.HttpPageGetter.java
public OriHttpPage getPost(HttpClient client, String action, NameValuePair[] data) { PostMethod post = new PostMethod(action); post.setRequestBody(data);// ww w .j a va 2 s. co m try { int c = client.executeMethod(post); BufferedInputStream remoteBIS = new BufferedInputStream(post.getResponseBodyAsStream()); ByteArrayOutputStream baos = new ByteArrayOutputStream(10240); byte[] buf = new byte[1024]; int bytesRead = 0; while (bytesRead >= 0) { baos.write(buf, 0, bytesRead); bytesRead = remoteBIS.read(buf); } remoteBIS.close(); byte[] content = baos.toByteArray(); // byte[] content=get.getResponseBody(); ConnResponse conRes = new ConnResponse(post.getResponseHeader("Content-type").getValue(), null, 0, 0, post.getStatusCode()); return new OriHttpPage(action, content, conRes, Constants.CHARTSET_DEFAULT); } catch (IOException ioe) { log.warn("Caught IO Exception: " + ioe.getMessage(), ioe); ioe.printStackTrace(); failureCount++; ConnResponse conRes = new ConnResponse(null, null, 0, 0, 0); return new OriHttpPage(null, null); } }
From source file:com.epam.wilma.service.http.WilmaHttpClient.java
/** * Posting the given file to the given URL via HTTP POST method and returns * {@code true} if the request was successful. * * @param url the given URL/* w w w. j a v a 2 s .c om*/ * @param file the given file * @return {@code true} if the request is successful, otherwise return {@code false} */ public boolean uploadFile(String url, File file) { boolean requestSuccessful = false; PostMethod method = new PostMethod(url); try { Part[] parts = { new FilePart("file", file) }; method.setRequestEntity(new MultipartRequestEntity(parts, method.getParams())); int statusCode = httpclient.executeMethod(method); if (HttpStatus.SC_OK == statusCode) { requestSuccessful = true; } } catch (HttpException e) { LOG.error("Protocol exception occurred when called: " + url, e); } catch (IOException e) { LOG.error("I/O (transport) error occurred when called: " + url, e); } finally { method.releaseConnection(); } return requestSuccessful; }
From source file:com.sun.faban.harness.util.DeployTask.java
/** * Executes the Faban deployment task./* ww w .j a va 2s . c o m*/ * @throws BuildException If there is an */ public void execute() throws BuildException { try { // First check the jar file and name if (jarFile == null) throw new BuildException("jar attribute missing for target deploy."); if (!jarFile.isFile()) throw new BuildException("jar file not found."); String jarName = jarFile.getName(); if (!jarName.endsWith(".jar")) throw new BuildException("Jar file name must end with \".jar\""); jarName = jarName.substring(0, jarName.length() - 4); if (jarName.indexOf('.') > -1) throw new BuildException("Jar file name must not have any " + "dots except ending with \".jar\""); // Prepare the parts for the request. ArrayList<Part> params = new ArrayList<Part>(4); if (user != null) params.add(new StringPart("user", user)); if (password != null) params.add(new StringPart("password", password)); if (clearConfig) params.add(new StringPart("clearconfig", "true")); params.add(new FilePart("jarfile", jarFile)); Part[] parts = new Part[params.size()]; parts = params.toArray(parts); // Prepare the post method. PostMethod post = new PostMethod(target + "/deploy"); // Ensure text/plain is the only accept header. post.removeRequestHeader("Accept"); post.setRequestHeader("Accept", "text/plain"); post.setRequestEntity(new MultipartRequestEntity(parts, post.getParams())); // Execute the multi-part post method. HttpClient client = new HttpClient(); client.getHttpConnectionManager().getParams().setConnectionTimeout(5000); int status = client.executeMethod(post); StringBuilder b = new StringBuilder(); InputStream respBody = post.getResponseBodyAsStream(); byte[] readBuffer = new byte[8192]; for (;;) { int size = respBody.read(readBuffer); if (size == -1) break; b.append(new String(readBuffer, 0, size)); } String response = b.toString(); // Check status. if (status == HttpStatus.SC_CONFLICT) { handleErrorFlush(response); throw new BuildException( "Benchmark to deploy is currently " + "run or queued to be run. Please clear run queue " + "of this benchmark before deployment"); } else if (status == HttpStatus.SC_NOT_ACCEPTABLE) { handleErrorFlush(response); throw new BuildException( "Benchmark deploy name or deploy " + "file invalid. Deploy file may contain errors. Name " + "must have no '.' and file must have the " + "'.jar' extensions."); } else if (status != HttpStatus.SC_CREATED) { handleOutput(response); throw new BuildException( "Faban responded with status code " + status + ". Status code 201 (SC_CREATED) expected."); } } catch (FileNotFoundException e) { throw new BuildException(e); } catch (HttpException e) { throw new BuildException(e); } catch (IOException e) { throw new BuildException(e); } }
From source file:com.founder.zykc.controller.FdbzcrjryController.java
@RestfulAnnotation(serverId = "3") @RequestMapping(value = "/queryFdbzcrjList", method = RequestMethod.POST) public @ResponseBody EasyUIPage queryList(EasyUIPage page, @RequestParam(value = "rows", required = false) Integer rows, String sfzhm, String zwxm, SessionBean sessionBean) {//from w w w . j av a2 s . c om page.setPagePara(rows); String url = "http://10.78.17.154:9999/lbs"; String urlParameter = "operation=ForbiddenDepartureManagement_GetInfoByIDName_v001&license=a756244eb0236bdc26061cb6b6bdb481&content="; int total = 0; List<FdbzcrjryVo> list = new ArrayList<FdbzcrjryVo>(); String content = ""; boolean isUpdated = false; if (!StringUtils.isEmpty(sfzhm) && !StringUtils.isEmpty(zwxm)) { content = "{\"data\":[{\"SFZHM\":\"" + sfzhm + "\"," + "\"ZWXM\":\"" + zwxm + "\"}]," + "\"pageindex\":" + (Integer.valueOf(page.getPage()) - 1) + "," + "\"pagesize\":" + rows + "}"; } else if (StringUtils.isEmpty(sfzhm)) { content = "{\"data\":[{\"ZWXM\":\"" + zwxm + "\"}]," + "\"pageindex\":" + (Integer.valueOf(page.getPage()) - 1) + "," + "\"pagesize\":" + rows + "}"; } else if (StringUtils.isEmpty(zwxm)) { // content = "{\"data\":[{\"SFZHM\":\"" + sfzhm // + "\"}]}"; content = "{\"data\":[{\"SFZHM\":\"" + sfzhm + "\"}]," + "\"pageindex\":" + (Integer.valueOf(page.getPage()) - 1) + "," + "\"pagesize\":" + rows + "}"; } try { content = urlParameter + java.net.URLEncoder.encode(content, "UTF-8"); } catch (UnsupportedEncodingException e1) { e1.printStackTrace(); } PostMethod postMethod = new PostMethod(url); byte[] b; try { b = content.getBytes("utf-8"); InputStream is = new ByteArrayInputStream(b, 0, b.length); RequestEntity re = new InputStreamRequestEntity(is, b.length, "application/soap+xml; charset=utf-8"); postMethod.setRequestEntity(re); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } HttpClient httpClient = new HttpClient(); HttpConnectionManagerParams managerParams = httpClient.getHttpConnectionManager().getParams(); managerParams.setConnectionTimeout(50000); int statusCode = 0; try { statusCode = httpClient.executeMethod(postMethod); } catch (HttpException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } if (statusCode == 200) { String soapResponseData = ""; try { soapResponseData = postMethod.getResponseBodyAsString(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } JSONObject jb = JSONObject.fromObject(soapResponseData); if ((Integer) jb.get("datalen") > 0) { Map<String, String> dictHkszd = new HashMap<String, String>();//? Map<String, String> dictFlyj = new HashMap<String, String>();//?? Map<String, String> dictCsd = new HashMap<String, String>();// Map<String, String> dictBbrylx = new HashMap<String, String>();// Map<String, String> dictPcs = new HashMap<String, String>();// Map<String, String> dictXb = new HashMap<String, String>();// Map<String, String> dictZjzl = new HashMap<String, String>();//?? Map<String, String> dictZzjg = new HashMap<String, String>();// Map<String, String> dictMj = new HashMap<String, String>();// try { dictHkszd = sysDictGlService.getDictMap("BD_D_FDBZCJHKSZD"); dictFlyj = sysDictGlService.getDictMap("BD_D_FDBZCJFLYJ"); dictCsd = sysDictGlService.getDictMap("BD_D_FDBZCJCSD"); dictBbrylx = sysDictGlService.getDictMap("BD_D_FDBZCJBBRYLB"); dictPcs = sysDictGlService.getDictMap("BD_D_FDBZCJPCS"); dictXb = sysDictGlService.getDictMap("BD_D_FDBZCJXB"); dictZjzl = sysDictGlService.getDictMap("BD_D_FDBZCJZJZL"); dictZzjg = sysDictGlService.getDictMap("BD_D_FDBZCJORG"); dictMj = sysDictGlService.getDictMap("BD_D_FDBZCJMJ"); } catch (Exception e2) { // TODO Auto-generated catch block e2.printStackTrace(); } total = Integer.valueOf(jb.getString("total")); for (int i = 0; i < (Integer) jb.get("datalen"); i++) { JSONObject jo = jb.getJSONArray("data").getJSONObject(i); FdbzcrjryVo vo = new FdbzcrjryVo(); if (jo.containsKey("BBDWBM")) { vo.setBbdwbm(dictZzjg.get(jo.getString("BBDWBM"))); } if (jo.containsKey("BBLXDH")) { vo.setBblxdh(jo.getString("BBLXDH")); } if (jo.containsKey("BBLXR")) { vo.setBblxr(jo.getString("BBLXR")); } if (jo.containsKey("BBQX")) { vo.setBbqx(jo.getString("BBQX")); } if (jo.containsKey("BBRQ")) { vo.setBbrq(jo.getString("BBRQ")); } if (jo.containsKey("BBRYLB")) { vo.setBbrylb(dictBbrylx.get(jo.getString("BBRYLB"))); } if (jo.containsKey("BBYY")) { vo.setBbyy(jo.getString("BBYY")); } if (jo.containsKey("BZ")) { vo.setBz(jo.getString("BZ")); } if (jo.containsKey("CSD")) { vo.setCsd(dictCsd.get(jo.getString("CSD"))); } if (jo.containsKey("DAH")) { vo.setDah(jo.getString("DAH")); } if (jo.containsKey("DWDH")) { vo.setDwdh(jo.getString("DWDH")); } if (jo.containsKey("FLYJ")) { vo.setFlyj(dictFlyj.get(jo.getString("FLYJ"))); } if (jo.containsKey("GZDW")) { vo.setGzdw(jo.getString("GZDW")); } if (jo.containsKey("HKSZD")) { vo.setHkszd(dictHkszd.get(jo.getString("HKSZD"))); } if (jo.containsKey("FLYJ")) { vo.setFlyj(dictFlyj.get(jo.getString("FLYJ"))); } if (jo.containsKey("JTDH")) { vo.setJtdh(jo.getString("JTDH")); } if (jo.containsKey("MJ")) { vo.setMj(dictMj.get(jo.getString("MJ"))); } if (jo.containsKey("PCSSZD")) { vo.setPcsszd(dictPcs.get(jo.getString("PCSSZD"))); } if (jo.containsKey("PYXM")) { vo.setPyxm(jo.getString("PYXM")); } if (jo.containsKey("SFZDCK")) { vo.setSfzdck(jo.getString("SFZDCK")); } if (jo.containsKey("SFZHM")) { vo.setSfzhm(jo.getString("SFZHM")); } if (jo.containsKey("XB")) { vo.setXb(dictXb.get(jo.getString("XB"))); } if (jo.containsKey("XZZ")) { vo.setXzz(jo.getString("XZZ")); } if (jo.containsKey("ZJHM")) { vo.setZjhm(jo.getString("ZJHM")); } if (jo.containsKey("ZJZL")) { vo.setZjzl(dictZjzl.get(jo.getString("ZJZL"))); } if (jo.containsKey("ZWM")) { vo.setZwm(jo.getString("ZWM")); } if (jo.containsKey("ZWX")) { vo.setZwx(jo.getString("ZWX")); } if (jo.containsKey("RYDH")) { vo.setRydh(jo.getString("RYDH")); } list.add(vo); } } } else { System.out.println("????" + statusCode); } page.setRows(list); page.setTotal(total); return page; }
From source file:eu.europa.ec.markt.dss.validation.https.CommonsHttpDataLoader.java
@Override public InputStream post(String URL, InputStream content) throws CannotFetchDataException { try {/* w w w . java 2 s .c om*/ LOG.fine("Post data to url " + URL); PostMethod post = new PostMethod(URL); RequestEntity requestEntity = new InputStreamRequestEntity(content); post.setRequestEntity(requestEntity); if (contentType != null) { post.setRequestHeader("Content-Type", contentType); } getClient().executeMethod(post); return post.getResponseBodyAsStream(); } catch (IOException ex) { throw new CannotFetchDataException(ex, URL); } }
From source file:net.adamcin.granite.client.packman.http3.Http3PackageManagerClient.java
@Override public boolean login(String username, String password) throws IOException { PostMethod request = new PostMethod(getBaseUrl() + LOGIN_PATH); request.addParameter(LOGIN_PARAM_USERNAME, username); request.addParameter(LOGIN_PARAM_PASSWORD, password); request.addParameter(LOGIN_PARAM_VALIDATE, LOGIN_VALUE_VALIDATE); request.addParameter(LOGIN_PARAM_CHARSET, LOGIN_VALUE_CHARSET); int status = getClient().executeMethod(request); if (status == 405) { // if 405 Method not allowed, fallback to legacy login return loginLegacy(username, password); } else {// ww w . j a v a 2 s. c om return status == 200; } }
From source file:com.zb.app.external.wechat.service.WeixinService.java
@SuppressWarnings("deprecation") public String sendMessage(WeixinMessage weixinMessage) throws Exception { StringBuilder sb = new StringBuilder(400); sb.append("https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token="); sb.append(getAccessToken());/*from w w w . j a v a 2s. co m*/ // https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=ACCESS_TOKEN PostMethod method = new PostMethod(sb.toString()); method.getParams().setContentCharset("utf-8"); String object2Json = new Gson().toJson(weixinMessage); logger.error(object2Json); // method.addParameter("body", object2Json); // method.setRequestBody(object2Json); RequestEntity entity = new StringRequestEntity(object2Json); method.setRequestEntity(entity); String result = HttpClientUtils.getResponseBodyAsString(method); logger.error(result); return result; }
From source file:com.cerema.cloud2.lib.resources.shares.CreateRemoteShareOperation.java
@Override protected RemoteOperationResult run(OwnCloudClient client) { RemoteOperationResult result = null; int status = -1; PostMethod post = null;/* w w w . ja va 2 s . c o m*/ try { // Post Method post = new PostMethod(client.getBaseUri() + ShareUtils.SHARING_API_PATH); post.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=utf-8"); // necessary for special characters post.addParameter(PARAM_PATH, mRemoteFilePath); post.addParameter(PARAM_SHARE_TYPE, Integer.toString(mShareType.getValue())); post.addParameter(PARAM_SHARE_WITH, mShareWith); if (mPublicUpload) { post.addParameter(PARAM_PUBLIC_UPLOAD, Boolean.toString(true)); } if (mPassword != null && mPassword.length() > 0) { post.addParameter(PARAM_PASSWORD, mPassword); } if (OCShare.DEFAULT_PERMISSION != mPermissions) { post.addParameter(PARAM_PERMISSIONS, Integer.toString(mPermissions)); } post.addRequestHeader(OCS_API_HEADER, OCS_API_HEADER_VALUE); status = client.executeMethod(post); if (isSuccess(status)) { String response = post.getResponseBodyAsString(); ShareToRemoteOperationResultParser parser = new ShareToRemoteOperationResultParser( new ShareXMLParser()); parser.setOneOrMoreSharesRequired(true); parser.setOwnCloudVersion(client.getOwnCloudVersion()); parser.setServerBaseUri(client.getBaseUri()); result = parser.parse(response); if (result.isSuccess() && mGetShareDetails) { // retrieve more info - POST only returns the index of the new share OCShare emptyShare = (OCShare) result.getData().get(0); GetRemoteShareOperation getInfo = new GetRemoteShareOperation(emptyShare.getRemoteId()); result = getInfo.execute(client); } } else { result = new RemoteOperationResult(false, status, post.getResponseHeaders()); } } catch (Exception e) { result = new RemoteOperationResult(e); Log_OC.e(TAG, "Exception while Creating New Share", e); } finally { if (post != null) { post.releaseConnection(); } } return result; }