List of usage examples for org.apache.commons.httpclient.methods PostMethod addParameter
public void addParameter(String paramString1, String paramString2) throws IllegalArgumentException
From source file:org.olat.modules.tu.TunnelComponent.java
/** * @param tuReq//from w w w . j a v a 2s . c o m * @param client * @return HttpMethod */ public HttpMethod fetch(final TURequest tuReq, final HttpClient client) { final String modulePath = tuReq.getUri(); HttpMethod meth = null; final String method = tuReq.getMethod(); if (method.equals("GET")) { final GetMethod cmeth = new GetMethod(modulePath); final String queryString = tuReq.getQueryString(); if (queryString != null) { cmeth.setQueryString(queryString); } meth = cmeth; if (meth == null) { return null; } // if response is a redirect, follow it meth.setFollowRedirects(true); } else if (method.equals("POST")) { final String type = tuReq.getContentType(); if (type == null || type.equals("application/x-www-form-urlencoded")) { // regular post, no file upload } final PostMethod pmeth = new PostMethod(modulePath); final Set postKeys = tuReq.getParameterMap().keySet(); for (final Iterator iter = postKeys.iterator(); iter.hasNext();) { final String key = (String) iter.next(); final String vals[] = (String[]) tuReq.getParameterMap().get(key); for (int i = 0; i < vals.length; i++) { pmeth.addParameter(key, vals[i]); } meth = pmeth; } if (meth == null) { return null; // Redirects are not supported when using POST method! // See RFC 2616, section 10.3.3, page 62 } } // Add olat specific headers to the request, can be used by external // applications to identify user and to get other params // test page e.g. http://cgi.algonet.se/htbin/cgiwrap/ug/test.py meth.addRequestHeader("X-OLAT-USERNAME", tuReq.getUserName()); meth.addRequestHeader("X-OLAT-LASTNAME", tuReq.getLastName()); meth.addRequestHeader("X-OLAT-FIRSTNAME", tuReq.getFirstName()); meth.addRequestHeader("X-OLAT-EMAIL", tuReq.getEmail()); try { client.executeMethod(meth); return meth; } catch (final Exception e) { meth.releaseConnection(); } return null; }
From source file:org.olat.restapi.CoursesElementsTest.java
@Test public void testCreateCoursePost() throws IOException, URISyntaxException { final HttpClient c = loginWithCookie("administrator", "olat"); // create an empty course final URI uri = getCoursesUri().queryParam("shortTitle", "course3").queryParam("title", "course3 long name") .build();/*from w w w.j a v a 2s.c o m*/ final PutMethod method = createPut(uri, MediaType.APPLICATION_JSON, true); final int code = c.executeMethod(method); assertEquals(code, 200); final String body = method.getResponseBodyAsString(); method.releaseConnection(); final CourseVO course = parse(body, CourseVO.class); assertNotNull(course); assertNotNull(course.getKey()); assertNotNull(course.getEditorRootNodeId()); // create an structure node final URI newStructureUri = getElementsUri(course).path("structure").build(); final PostMethod newStructureMethod = createPost(newStructureUri, MediaType.APPLICATION_JSON, true); newStructureMethod.addParameter("parentNodeId", course.getEditorRootNodeId()); newStructureMethod.addParameter("position", "0"); newStructureMethod.addParameter("shortTitle", "Structure-0"); newStructureMethod.addParameter("longTitle", "Structure-long-0"); newStructureMethod.addParameter("objectives", "Structure-objectives-0"); final int newStructureCode = c.executeMethod(newStructureMethod); assertTrue(newStructureCode == 200 || newStructureCode == 201); final String newStructureBody = newStructureMethod.getResponseBodyAsString(); final CourseNodeVO structureNode = parse(newStructureBody, CourseNodeVO.class); assertNotNull(structureNode); assertNotNull(structureNode.getId()); assertEquals(structureNode.getShortTitle(), "Structure-0"); assertEquals(structureNode.getLongTitle(), "Structure-long-0"); assertEquals(structureNode.getLearningObjectives(), "Structure-objectives-0"); assertEquals(structureNode.getParentId(), course.getEditorRootNodeId()); // create single page final URL pageUrl = RepositoryEntriesTest.class.getResource("singlepage.html"); assertNotNull(pageUrl); final File page = new File(pageUrl.toURI()); final URI newPageUri = getElementsUri(course).path("singlepage").build(); final PostMethod newPageMethod = createPost(newPageUri, MediaType.APPLICATION_JSON, true); newPageMethod.addRequestHeader("Content-Type", MediaType.MULTIPART_FORM_DATA); final Part[] parts = { new FilePart("file", page), new StringPart("filename", page.getName()), new StringPart("parentNodeId", course.getEditorRootNodeId()), new StringPart("position", "1"), new StringPart("shortTitle", "Single-Page-0"), new StringPart("longTitle", "Single-Page-long-0"), new StringPart("objectives", "Single-Page-objectives-0") }; newPageMethod.setRequestEntity(new MultipartRequestEntity(parts, method.getParams())); final int newPageCode = c.executeMethod(newPageMethod); assertTrue(newPageCode == 200 || newPageCode == 201); final String newPageBody = newPageMethod.getResponseBodyAsString(); final CourseNodeVO pageNode = parse(newPageBody, CourseNodeVO.class); assertNotNull(pageNode); assertNotNull(pageNode.getId()); assertEquals(pageNode.getShortTitle(), "Single-Page-0"); assertEquals(pageNode.getLongTitle(), "Single-Page-long-0"); assertEquals(pageNode.getLearningObjectives(), "Single-Page-objectives-0"); assertEquals(structureNode.getParentId(), course.getEditorRootNodeId()); // create a folder node final URI newFolderUri = getElementsUri(course).path("folder").build(); final PostMethod newFolderMethod = createPost(newFolderUri, MediaType.APPLICATION_JSON, true); newFolderMethod.addParameter("parentNodeId", course.getEditorRootNodeId()); newFolderMethod.addParameter("position", "2"); newFolderMethod.addParameter("shortTitle", "Folder-0"); newFolderMethod.addParameter("longTitle", "Folder-long-0"); newFolderMethod.addParameter("objectives", "Folder-objectives-0"); final int newFolderCode = c.executeMethod(newFolderMethod); assertTrue(newFolderCode == 200 || newFolderCode == 201); final String newFolderBody = newFolderMethod.getResponseBodyAsString(); final CourseNodeVO folderNode = parse(newFolderBody, CourseNodeVO.class); assertNotNull(folderNode); assertNotNull(folderNode.getId()); assertEquals(folderNode.getShortTitle(), "Folder-0"); assertEquals(folderNode.getLongTitle(), "Folder-long-0"); assertEquals(folderNode.getLearningObjectives(), "Folder-objectives-0"); assertEquals(folderNode.getParentId(), course.getEditorRootNodeId()); // create a forum node final URI newForumUri = getElementsUri(course).path("forum").build(); final PostMethod newForumMethod = createPost(newForumUri, MediaType.APPLICATION_JSON, true); newForumMethod.addParameter("parentNodeId", course.getEditorRootNodeId()); newForumMethod.addParameter("position", "3"); newForumMethod.addParameter("shortTitle", "Forum-0"); newForumMethod.addParameter("longTitle", "Forum-long-0"); newForumMethod.addParameter("objectives", "Forum-objectives-0"); final int newForumCode = c.executeMethod(newForumMethod); assertTrue(newForumCode == 200 || newForumCode == 201); final String newForumBody = newForumMethod.getResponseBodyAsString(); final CourseNodeVO forumNode = parse(newForumBody, CourseNodeVO.class); assertNotNull(forumNode); assertNotNull(forumNode.getId()); assertEquals(forumNode.getShortTitle(), "Forum-0"); assertEquals(forumNode.getLongTitle(), "Forum-long-0"); assertEquals(forumNode.getLearningObjectives(), "Forum-objectives-0"); assertEquals(forumNode.getParentId(), course.getEditorRootNodeId()); // create a task node final URI newTaskUri = getElementsUri(course).path("task").build(); final PostMethod newTaskMethod = createPost(newTaskUri, MediaType.APPLICATION_JSON, true); newTaskMethod.addParameter("parentNodeId", course.getEditorRootNodeId()); newTaskMethod.addParameter("position", "4"); newTaskMethod.addParameter("shortTitle", "Task-0"); newTaskMethod.addParameter("longTitle", "Task-long-0"); newTaskMethod.addParameter("objectives", "Task-objectives-0"); newTaskMethod.addParameter("points", "25"); newTaskMethod.addParameter("text", "A very difficult test"); final int newTaskCode = c.executeMethod(newTaskMethod); assertTrue(newTaskCode == 200 || newTaskCode == 201); final String newTaskBody = newTaskMethod.getResponseBodyAsString(); final CourseNodeVO taskNode = parse(newTaskBody, CourseNodeVO.class); assertNotNull(taskNode); assertNotNull(taskNode.getId()); assertEquals(taskNode.getShortTitle(), "Task-0"); assertEquals(taskNode.getLongTitle(), "Task-long-0"); assertEquals(taskNode.getLearningObjectives(), "Task-objectives-0"); assertEquals(taskNode.getParentId(), course.getEditorRootNodeId()); // create a test node final URI newTestUri = getElementsUri(course).path("test").build(); final PostMethod newTestMethod = createPost(newTestUri, MediaType.APPLICATION_JSON, true); newTestMethod.addParameter("parentNodeId", course.getEditorRootNodeId()); newTestMethod.addParameter("testResourceableId", course.getEditorRootNodeId()); newTestMethod.addParameter("position", "5"); newTestMethod.addParameter("shortTitle", "Test-0"); newTestMethod.addParameter("longTitle", "Test-long-0"); newTestMethod.addParameter("objectives", "Test-objectives-0"); final int newTestCode = c.executeMethod(newTestMethod); assertTrue(newTestCode == 404);// must bind a real test /* * assertTrue(newTestCode == 200 || newTestCode == 201); String newTestBody = newTestMethod.getResponseBodyAsString(); CourseNodeVO testNode = parse(newTestBody, * CourseNodeVO.class); assertNotNull(testNode); assertNotNull(testNode.getId()); assertEquals(testNode.getShortTitle(), "Test-0"); * assertEquals(testNode.getParentId(), course.getEditorRootNodeId()); */ // create an assessment node final URI newAssessmentUri = getElementsUri(course).path("assessment").build(); final PostMethod newAssessmentMethod = createPost(newAssessmentUri, MediaType.APPLICATION_JSON, true); newAssessmentMethod.addParameter("parentNodeId", course.getEditorRootNodeId()); newAssessmentMethod.addParameter("position", "5"); newAssessmentMethod.addParameter("shortTitle", "Assessment-0"); newAssessmentMethod.addParameter("longTitle", "Assessment-long-0"); newAssessmentMethod.addParameter("objectives", "Assessment-objectives-0"); final int newAssessmentCode = c.executeMethod(newAssessmentMethod); assertTrue(newAssessmentCode == 200 || newAssessmentCode == 201); final String newAssessmentBody = newAssessmentMethod.getResponseBodyAsString(); final CourseNodeVO assessmentNode = parse(newAssessmentBody, CourseNodeVO.class); assertNotNull(assessmentNode); assertNotNull(assessmentNode.getId()); assertEquals(assessmentNode.getShortTitle(), "Assessment-0"); assertEquals(assessmentNode.getLongTitle(), "Assessment-long-0"); assertEquals(assessmentNode.getLearningObjectives(), "Assessment-objectives-0"); assertEquals(assessmentNode.getParentId(), course.getEditorRootNodeId()); // create an contact node final URI newContactUri = getElementsUri(course).path("contact").build(); final PostMethod newContactMethod = createPost(newContactUri, MediaType.APPLICATION_JSON, true); newContactMethod.addParameter("parentNodeId", course.getEditorRootNodeId()); newContactMethod.addParameter("position", "6"); newContactMethod.addParameter("shortTitle", "Contact-0"); newContactMethod.addParameter("longTitle", "Contact-long-0"); newContactMethod.addParameter("objectives", "Contact-objectives-0"); final int newContactCode = c.executeMethod(newContactMethod); assertEquals(200, newContactCode); final String newContactBody = newContactMethod.getResponseBodyAsString(); final CourseNodeVO contactNode = parse(newContactBody, CourseNodeVO.class); assertNotNull(contactNode); assertNotNull(contactNode.getId()); assertEquals(contactNode.getShortTitle(), "Contact-0"); assertEquals(contactNode.getLongTitle(), "Contact-long-0"); assertEquals(contactNode.getLearningObjectives(), "Contact-objectives-0"); assertEquals(contactNode.getParentId(), course.getEditorRootNodeId()); }
From source file:org.openanzo.servlet.sparql.TestSendQuery.java
/** * @param args/* ww w .ja va 2 s. c om*/ */ public static void main(String[] args) { try { HttpClient client = new HttpClient(); client.getState().setCredentials(new AuthScope("localhost", 8080), new UsernamePasswordCredentials("sysadmin", "123")); PostMethod post = new PostMethod("http://localhost:8080/sparql"); post.setDoAuthentication(true); post.addParameter("query", "SELECT * WHERE {?s ?p ?o}"); post.addParameter("default-graph-uri", Constants.GRAPHS.ALL_NAMEDGRAPHS.toString()); post.setRequestHeader("Accept-Charset", "utf-8"); client.executeMethod(post); int statusCode = post.getStatusCode(); System.err.println(statusCode); System.err.println(post.getResponseBodyAsString()); System.err.println(post.getResponseCharSet()); } catch (Exception e) { e.printStackTrace(); } }
From source file:org.openhab.binding.daikin.internal.DaikinBinding.java
private void updateState(DaikinHost host) { // TODO: can't figure out how to authenticate this HTTP POST request // TODO: have to configure the controller with NO AUTHENTICATION for this to work // TODO: maybe something like this...https://github.com/jim-easterbrook/pywws/commit/a537fab5061b8967270f972636017cd84a63065f PostMethod httpPost = null; try {/* w ww. java 2 s . c o m*/ String url = String.format("http://%s", host.getHost()); httpPost = new PostMethod(url); httpPost.addParameter("wON", host.getPower() ? "On" : "Off"); httpPost.addParameter("wMODE", host.getMode().getCommand()); httpPost.addParameter("wTEMP", host.getTemp().setScale(0).toPlainString() + "C"); httpPost.addParameter("wFUN", host.getFan().getCommand()); httpPost.addParameter("wSWNG", host.getSwing().getCommand()); httpPost.addParameter("wSETd1", "Set"); httpClient.executeMethod(httpPost); if (httpPost.getStatusCode() != HttpStatus.SC_OK) { logger.warn("Invalid response received from Daikin controller '{}': {}", host.getHost(), httpPost.getStatusCode()); return; } } catch (Exception e) { logger.error("Error attempting to send command", e); return; } finally { if (httpPost != null) httpPost.releaseConnection(); } }
From source file:org.openmicroscopy.shoola.svc.proxy.MessengerRequest.java
/** * Prepares the <code>method</code> to post. * @see Request#marshal()// ww w.ja v a2s .c o m */ public HttpMethod marshal() throws TransportException { //Create request. PostMethod request = new PostMethod(); //Marshal. if (email != null) request.addParameter(EMAIL, email); if (comment != null) request.addParameter(COMMENT, comment); if (error != null) request.addParameter(ERROR, error); if (extra != null) request.addParameter(EXTRA, extra); if (applicationNumber != null) request.addParameter(ProxyUtil.APP_NAME, applicationNumber); if (invoker != null) request.addParameter(INVOKER, invoker); if (applicationVersion != null) request.addParameter(ProxyUtil.APP_VERSION, applicationVersion); Map<String, String> info = ProxyUtil.collectInfo(); Entry entry; Iterator k = info.entrySet().iterator(); while (k.hasNext()) { entry = (Entry) k.next(); request.addParameter((String) entry.getKey(), (String) entry.getValue()); } List<NameValuePair> pairs = new ArrayList<NameValuePair>(); if (mainFile != null) { pairs.add(new NameValuePair(MAIN_FILE_NAME, mainFile.getName())); pairs.add(new NameValuePair(MAIN_FILE_PATH, mainFile.getAbsolutePath())); } if (associatedFiles != null) { Iterator<File> i = associatedFiles.iterator(); File f; while (i.hasNext()) { f = i.next(); pairs.add(new NameValuePair(ADDITIONAL_FILE_NAME, f.getName())); if (f.getParent() != null) pairs.add(new NameValuePair(ADDITIONAL_FILE_PATH, f.getParent())); pairs.add(new NameValuePair(ADDITIONAL_FILE_SIZE, ((Long) f.length()).toString())); } } if (pairs.size() > 0) { Iterator<NameValuePair> j = pairs.iterator(); NameValuePair[] values = new NameValuePair[pairs.size()]; int index = 0; while (j.hasNext()) { values[index] = j.next(); index++; } request.addParameters(values); } return request; }
From source file:org.openrdf.repository.sparql.query.SPARQLQuery.java
protected HttpMethodBase getResponse() throws HttpException, IOException, QueryEvaluationException { PostMethod post = new PostMethod(url); post.addParameter("query", getQueryString()); if (dataset != null) { for (URI graph : dataset.getDefaultGraphs()) { post.addParameter("default-graph-uri", String.valueOf(graph)); }//from www . java 2 s . com for (URI graph : dataset.getNamedGraphs()) { post.addParameter("named-graph-uri", String.valueOf(graph)); } } post.addRequestHeader("Accept", getAccept()); Map<String, String> additionalHeaders = (Map<String, String>) client.getParams() .getParameter(SPARQLConnection.ADDITIONAL_HEADER_NAME); if (additionalHeaders != null) { for (Entry<String, String> additionalHeader : additionalHeaders.entrySet()) post.addRequestHeader(additionalHeader.getKey(), additionalHeader.getValue()); } boolean completed = false; try { if (client.executeMethod(post) >= 400) { throw new QueryEvaluationException(post.getResponseBodyAsString()); } completed = true; return post; } finally { if (!completed) { post.abort(); } } }
From source file:org.paxml.bean.HttpTag.java
private PostMethod setPostBody(PostMethod post) { Map<String, List<String>> value = getNameValuePairs(body, "body"); if (value != null) { for (Map.Entry<String, List<String>> entry : value.entrySet()) { for (String v : entry.getValue()) { post.addParameter(entry.getKey(), v); }/*from w w w .j a va 2 s . co m*/ } } else if (body != null) { post.setRequestBody(body.toString()); } return post; }
From source file:org.pentaho.di.trans.dataservice.jdbc.RemoteClient.java
@Override public DataInputStream query(String sql, int maxRows) throws SQLException { try {//w w w . j a va 2 s .c o m String url = connection.constructUrl(SERVICE_PATH); PostMethod method = new PostMethod(url); method.setDoAuthentication(true); method.getParams().setParameter("http.socket.timeout", 0); // Kept in for backwards compatibility, but should be removed in next major release if (sql.length() < MAX_SQL_LENGTH) { method.addRequestHeader(new Header(SQL, CharMatcher.anyOf("\n\r").collapseFrom(sql, ' '))); method.addRequestHeader(new Header(MAX_ROWS, Integer.toString(maxRows))); } method.addParameter(SQL, CharMatcher.anyOf("\n\r").collapseFrom(sql, ' ')); method.addParameter(MAX_ROWS, Integer.toString(maxRows)); for (Map.Entry<String, String> parameterEntry : connection.getParameters().entrySet()) { method.addParameter(parameterEntry.getKey(), parameterEntry.getValue()); } if (!Strings.isNullOrEmpty(connection.getDebugTransFilename())) { method.addParameter(ThinConnection.ARG_DEBUGTRANS, connection.getDebugTransFilename()); } return new DataInputStream(execMethod(method).getResponseBodyAsStream()); } catch (Exception e) { throw serverException(e); } }
From source file:org.pentaho.pac.server.common.ThreadSafeHttpClient.java
private static void setPostMethodParams(PostMethod method, Map<String, Object> mapParams) { for (Map.Entry<String, Object> entry : mapParams.entrySet()) { Object o = entry.getValue(); if (o instanceof String[]) { for (String s : (String[]) o) { method.addParameter(entry.getKey(), s); }/*w ww . jav a 2 s . c o m*/ } else { method.setParameter(entry.getKey(), (String) o); } } }
From source file:org.pentaho.platform.web.servlet.ProxyServlet.java
protected void doProxy(final HttpServletRequest request, final HttpServletResponse response) throws IOException { if (proxyURL == null) { // Got nothing from web.xml return;//from w ww . j a v a 2s . co m } String servletPath = request.getServletPath(); // System .out.println( ">>>>>>>> REQ: " + request.getRequestURL().toString() ); //$NON-NLS-1$//$NON-NLS-2$ PentahoSystem.systemEntryPoint(); try { String theUrl = proxyURL + servletPath; PostMethod method = new PostMethod(theUrl); // Copy the parameters from the request to the proxy // System .out.print( ">>>>>>>> PARAMS: " ); //$NON-NLS-1$ Map paramMap = request.getParameterMap(); Map.Entry entry; String[] array; for (Iterator it = paramMap.entrySet().iterator(); it.hasNext();) { entry = (Map.Entry) it.next(); array = (String[]) entry.getValue(); for (String element : array) { method.addParameter((String) entry.getKey(), element); // System.out.print( (String)entry.getKey() + "=" + array[i] // + "&" ); //$NON-NLS-1$ //$NON-NLS-2$ } } // System.out.println( "" ); //$NON-NLS-1$ // Just in case someone is trying to spoof the proxy method.removeParameter("_TRUST_USER_"); //$NON-NLS-1$ // Get the user from the session IPentahoSession userSession = getPentahoSession(request); String name = userSession.getName(); // Add the trusted user from the session if ((name != null) && (name.length() > 0)) { method.addParameter("_TRUST_USER_", name); //$NON-NLS-1$ // System.out.println( ">>>>>>>> USR: " + name ); //$NON-NLS-1$ } else if ((errorURL != null) && (errorURL.trim().length() > 0)) { response.sendRedirect(errorURL); // System.out.println( ">>>>>>>> REDIR: " + errorURL ); // //$NON-NLS-1$ return; } // System.out.println( ">>>>>>>> PROXY: " + theUrl ); //$NON-NLS-1$ debug(Messages.getInstance().getString("ProxyServlet.DEBUG_0001_OUTPUT_URL", theUrl)); //$NON-NLS-1$ // Now do the request HttpClient client = new HttpClient(); try { // Execute the method. int statusCode = client.executeMethod(method); if (statusCode != HttpStatus.SC_OK) { error(Messages.getInstance().getErrorString("ProxyServlet.ERROR_0003_REMOTE_HTTP_CALL_FAILED", //$NON-NLS-1$ method.getStatusLine().toString())); return; } setHeader("Content-Type", method, response); //$NON-NLS-1$ setHeader("Content-Length", method, response); //$NON-NLS-1$ InputStream inStr = method.getResponseBodyAsStream(); ServletOutputStream outStr = response.getOutputStream(); int inCnt = 0; byte[] buf = new byte[2048]; while (-1 != (inCnt = inStr.read(buf))) { outStr.write(buf, 0, inCnt); } } catch (HttpException e) { error(Messages.getInstance().getErrorString("ProxyServlet.ERROR_0004_PROTOCOL_FAILURE"), e); //$NON-NLS-1$ e.printStackTrace(); } catch (IOException e) { error(Messages.getInstance().getErrorString("ProxyServlet.ERROR_0005_TRANSPORT_FAILURE"), e); //$NON-NLS-1$ e.printStackTrace(); } finally { method.releaseConnection(); } } finally { PentahoSystem.systemExitPoint(); } }