List of usage examples for org.apache.commons.httpclient.methods PostMethod addParameter
public void addParameter(String paramString1, String paramString2) throws IllegalArgumentException
From source file:com.fluidops.iwb.wiki.WikiBot.java
/** * Execute a wikimedia query asking for the latest content of the * given wikipedia page. If {@link #expandTemplates} is set, the * templates within the content are automatically expanded * //from w ww . j av a 2 s .com * @param wikiPage * @return */ private String retrieveWikiContent(String wikiPage) throws IOException, Exception { PostMethod method = new PostMethod(wikimediaApiURL()); method.addRequestHeader("User-Agent", WIKIBOT_USER_AGENT); method.addRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=utf-8"); method.addParameter("action", "query"); method.addParameter("prop", "revisions"); method.addParameter("rvprop", "ids|content"); if (expandTemplates) method.addParameter("rvexpandtemplates", ""); method.addParameter("tlnamespace", "0"); method.addParameter("format", "xml"); method.addParameter("redirects", ""); method.addParameter("titles", wikiPage.replace(" ", "_")); try { int status = httpClient.executeMethod(method); if (status == HttpStatus.SC_OK) { return parsePage(method.getResponseBodyAsStream()); } throw new IOException("Error while retrieving wiki page " + wikiPage + ": " + status + " (" + method.getStatusText() + ")"); } finally { method.releaseConnection(); } }
From source file:edu.wustl.bulkoperator.client.BulkOperationServiceImpl.java
/** * This method will be called to get Job details. * @param jobId jobId/*from w ww .java 2s. c om*/ * @return Job Message * @throws BulkOperationException BulkOperationException */ public JobMessage getJobDetails(Long jobId) throws BulkOperationException { JobMessage jobMessage = null; if (!isLoggedIn) { jobMessage = new JobMessage(); jobMessage.setOperationSuccessfull(false); jobMessage.addMessage(ApplicationProperties.getValue("bulk.operation.client.login.error")); return jobMessage; } PostMethod postMethod = new PostMethod(url + "/BulkHandler.do"); try { postMethod.addParameter("jobId", jobId.toString()); postMethod.addParameter("fromAction", "jobDetails"); client.executeMethod(postMethod); InputStream inputStream = (InputStream) postMethod.getResponseBodyAsStream(); ObjectInputStream ois = new ObjectInputStream(inputStream); Object object = ois.readObject(); jobMessage = (JobMessage) object; } catch (IOException e) { List<String> listOfArguments = new ArrayList<String>(); listOfArguments.add("Template file"); listOfArguments.add("CSV file"); jobMessage = new JobMessage(); jobMessage.setOperationSuccessfull(false); jobMessage.addMessage(ApplicationProperties.getValue("bulk.operation.file.not.found", listOfArguments)); } catch (ClassNotFoundException e) { jobMessage = new JobMessage(); jobMessage.setOperationSuccessfull(false); jobMessage.addMessage(ApplicationProperties.getValue("clz.not.found.error")); } finally { postMethod.releaseConnection(); } return jobMessage; }
From source file:fr.jmmc.smprsc.data.stub.StubMetaData.java
/** * @param xml//from w w w . j av a2s . c o m */ private void postXMLToRegistry(final String xml) { // Check parameter vailidty if (xml == null) { _logger.warn( "Something went wrong while serializing SAMP application '{}' meta-data ... aborting report.", _applicationName); return; } _logger.info("Sending JMMC SAMP application '{}' XML description to JMMC registry ...", _applicationName); try { final URI uri = Http.validateURL(REGISTRY_BASE_URL + REGISTRY_SUBMISSION_FORM_NAME); // use the multi threaded HTTP client final String result = Http.post(uri, false, new PostQueryProcessor() { /** * Process the given post method to define its HTTP input fields * * @param method post method to complete * @throws IOException if any IO error occurs */ @Override public void process(final PostMethod method) throws IOException { method.addParameter("uid", _applicationId); method.addParameter("xmlSampStub", xml); } }); _logger.debug("HTTP response : '{}'.", result); // Parse result for failure if (result != null) { _logger.info("Sent SAMP application '{}' XML description to JMMC regitry.", _applicationName); } else { _logger.warn("SAMP application meta-data were not sent properly."); } } catch (IOException ioe) { _logger.error("Cannot send SAMP application meta-data : ", ioe); } }
From source file:dk.netarkivet.viewerproxy.WebProxyTester.java
/** * Test the general integration of the WebProxy access through the running Jetty true: *///www . jav a 2 s . c om @Test public void testJettyIntegration() throws Exception { TestURIResolver uriResolver = new TestURIResolver(); proxy = new WebProxy(uriResolver); try { new Socket(InetAddress.getLocalHost(), httpPort); } catch (IOException e) { fail("Port not in use after starting server"); } // GET request HttpClient client = new HttpClient(); HostConfiguration hc = new HostConfiguration(); String hostName = SystemUtils.getLocalHostName(); hc.setProxy(hostName, httpPort); client.setHostConfiguration(hc); GetMethod get = new GetMethod("http://foo.bar/"); client.executeMethod(get); assertEquals("Status code should be what URI resolver gives", 242, get.getStatusCode()); assertEquals("Body should contain what URI resolver wrote", "Test", get.getResponseBodyAsString()); get.releaseConnection(); // POST request PostMethod post = new PostMethod("http://foo2.bar/"); post.addParameter("a", "x"); post.addParameter("a", "y"); client.executeMethod(post); // Check request received by URIResolver assertEquals("URI resolver lookup should be called.", 2, uriResolver.lookupCount); assertEquals("URI resolver lookup should be called with right URI.", new URI("http://foo2.bar/"), uriResolver.lookupRequestArgument); assertEquals("Posted parameter should be received.", 1, uriResolver.lookupRequestParameteres.size()); assertNotNull("Posted parameter should be received.", uriResolver.lookupRequestParameteres.get("a")); assertEquals("Posted parameter should be received.", 2, uriResolver.lookupRequestParameteres.get("a").length); assertEquals("Posted parameter should be received.", "x", uriResolver.lookupRequestParameteres.get("a")[0]); assertEquals("Posted parameter should be received.", "y", uriResolver.lookupRequestParameteres.get("a")[1]); assertEquals("Status code should be what URI resolver gives", 242, post.getStatusCode()); assertEquals("Body should contain what URI resolver wrote", "Test", post.getResponseBodyAsString()); post.releaseConnection(); // Request with parameter and portno get = new GetMethod("http://foo2.bar:8090/?baz=boo"); client.executeMethod(get); // Check request received by URIResolver assertEquals("URI resolver lookup should be called.", 3, uriResolver.lookupCount); assertEquals("URI resolver 2 lookup should be called with right URI.", new URI("http://foo2.bar:8090/?baz=boo"), uriResolver.lookupRequestArgument); assertEquals("Status code should be what URI resolver gives", 242, get.getStatusCode()); assertEquals("Body should contain what URI resolver wrote", "Test", get.getResponseBodyAsString()); get.releaseConnection(); }
From source file:com.utest.webservice.client.rest.RestClient.java
public HttpMethod createPost(String service, String path, Map<String, Object> parameters) { final PostMethod post = new PostMethod(baseUrl + servicePath + service + "/" + path); post.getParams().setBooleanParameter(HttpMethodParams.USE_EXPECT_CONTINUE, true); for (final Map.Entry<String, Object> param : parameters.entrySet()) { post.addParameter(param.getKey(), (param.getValue() == null) ? "" : param.getValue().toString()); }/*from www. ja v a 2 s . co m*/ setHeader(post); return post; }
From source file:com.aimluck.eip.services.social.ALSocialApplicationHandler.java
public Map<String, ALGadgetSpec> getMetaData(List<String> specUrls, String view, boolean isDetail, boolean nocache) { Map<String, ALGadgetSpec> maps = new HashMap<String, ALGadgetSpec>(); if (specUrls == null || specUrls.size() == 0) { return maps; }//ww w .ja va 2 s . co m try { HttpClient httpClient = new HttpClient(); httpClient.getParams().setParameter("http.connection.timeout", 10000); httpClient.getParams().setParameter("http.socket.timeout", 10000); PostMethod postMethod = new PostMethod(getMetaDataUrl()); postMethod.addRequestHeader("Content-Type", "application/javascript"); postMethod.addParameter("st", "default:st"); postMethod.addParameter("req", "1"); postMethod.addParameter("callback", "1"); JSONObject jsonObject = new JSONObject(); JSONObject context = new JSONObject(); context.put("country", "JP"); context.put("language", "ja"); context.put("view", view == null ? "home" : view); context.put("container", "default"); context.put("nocache", nocache ? 1 : 0); if (isDetail) { context.put("withDescription", "1"); context.put("withOAuthService", "1"); } JSONArray gadgets = new JSONArray(); for (String specUrl : specUrls) { JSONObject gadget = new JSONObject(); gadget.put("url", specUrl); gadget.put("moduleId", 1); gadgets.add(gadget); } jsonObject.put("context", context); jsonObject.put("gadgets", gadgets); postMethod.setRequestEntity( new StringRequestEntity(jsonObject.toString(), "application/javascript", "UTF-8")); httpClient.executeMethod(postMethod); String result = postMethod.getResponseBodyAsString(); JSONObject fromObject = JSONObject.fromObject(result); JSONArray jsonArray = (JSONArray) fromObject.get("gadgets"); Map<String, Class<?>> classMap = new HashMap<String, Class<?>>(); classMap.put("oauthService", ALOAuthService.class); classMap.put("userPrefs", HashMap.class); if (jsonArray == null) { return maps; } int size = jsonArray.size(); for (int i = 0; i < size; i++) { try { JSONObject object = jsonArray.getJSONObject(i); Object e = object.get("errors"); if (e == null) { ALGadgetSpec spec = (ALGadgetSpec) JSONObject.toBean(object, ALGadgetSpec.class, classMap); maps.put(spec.getUrl(), spec); } } catch (Throwable t) { logger.warn("[ALSocialApplicationHandler]", t); } } } catch (Throwable t) { logger.warn("[ALSocialApplicationHandler]", t); } return maps; }
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; try {/*from w ww.jav a 2 s.c o m*/ // 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; }
From source file:cn.vlabs.duckling.aone.client.impl.EmailAttachmentSenderImpl.java
/** * docIdemail/*from w ww.jav a 2s . com*/ * * @param fileName * @param email * @param teamId * @param docId * @param fileSize * @return */ private AttachmentPushResult createFileResouceInDDL(String email, int teamId, int docId, AttachmentInfo attachment) { AttachmentPushResult result = new AttachmentPushResult(); setAttachResult(result, attachment); PostMethod method = new PostMethod(getDDLIp()); method.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "utf-8"); method.addParameter(CLBID, docId + ""); method.addParameter(EMAIL, email); method.addParameter(TEAMID, teamId + ""); method.addParameter(FILESIZE, attachment.getFileSize() + ""); method.addParameter(FILEID, attachment.getFileId()); try { method.addParameter(FILENAME, URLEncoder.encode(attachment.getFileName(), "UTF-8")); int status = ddlClient.executeMethod(method); if (status >= 200 && status < 300) { String responseString = method.getResponseBodyAsString(); AttachmentPushResult r = dealHttpResponse(responseString); setAttachResult(r, attachment); return r; } else { result.setStatusCode(AttachmentPushResult.NETWORK_ERROR); result.setMessage("DDL?" + status + ""); return result; } } catch (HttpException e) { result.setStatusCode(AttachmentPushResult.NETWORK_ERROR); result.setMessage("DDL?" + e.getMessage() + ""); return result; } catch (IOException e) { result.setStatusCode(AttachmentPushResult.IO_ERROR); result.setMessage("ddlIo"); return result; } catch (Exception e) { result.setStatusCode(AttachmentPushResult.IO_ERROR); result.setMessage("ddl" + e.getStackTrace()); return result; } finally { method.releaseConnection(); } }
From source file:cn.vlabs.duckling.aone.client.impl.EmailAttachmentSenderImpl.java
/** * ?DDL//ww w .jav a 2s . com * @param email * @param attachment * @return */ private AttachmentPushResult validateExsit(String email, int teamId, AttachmentInfo attachment) { if (attachment.getCoverFlag()) { return null; } PostMethod method = new PostMethod(getDDLValidateIp()); method.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "utf-8"); method.addParameter(FILENAME, attachment.getFileName()); method.addParameter(EMAIL, email); method.addParameter(FILESIZE, attachment.getFileSize() + ""); method.addParameter(FILEID, attachment.getFileId()); method.addParameter(TEAMID, teamId + ""); AttachmentPushResult result = new AttachmentPushResult(); result.setFileName(attachment.getFileName()); try { int status = ddlClient.executeMethod(method); if (status >= 200 && status < 300) { String responseString = method.getResponseBodyAsString(); return dealValidateResult(responseString); } else { result.setStatusCode(AttachmentPushResult.NETWORK_ERROR); result.setMessage("DDL?" + status + ""); return result; } } catch (HttpException e) { result.setStatusCode(AttachmentPushResult.NETWORK_ERROR); result.setMessage("DDL?" + e.getMessage() + ""); return result; } catch (IOException e) { result.setStatusCode(AttachmentPushResult.IO_ERROR); result.setMessage("ddlIo"); e.printStackTrace(); return result; } finally { method.releaseConnection(); } }
From source file:net.mumie.cocoon.grade.UserWorksheetGradeMessageImpl.java
/** * Adds the contents of the grade to the message. *///from w w w . j av a 2s.c o m protected void init(PostMethod method, MessageDestination destination) throws Exception { final String METHOD_NAME = "init"; this.logDebug(METHOD_NAME + " 1/2: Started"); UserWorksheetGrade grade = null; try { grade = (UserWorksheetGrade) this.serviceManager.lookup(UserWorksheetGrade.ROLE); grade.setup(this.userId, this.worksheetId); method.addParameter("body", getXMLCode(grade)); this.logDebug(METHOD_NAME + " 2/2: Done"); } finally { this.serviceManager.release(grade); } }