List of usage examples for org.apache.commons.httpclient.methods PostMethod setRequestEntity
public void setRequestEntity(RequestEntity paramRequestEntity)
From source file:cuanto.api.CuantoConnector.java
/** * Updates the TestRun with this id on the Cuanto Server to have all the properties specified in this TestRun. If the * TestRun argument does not already have an id, it needs to be retrieved from the server as you can't set the ID on a * TestRun directly. You can either retrieve the TestRun from the server by querying by ID or other values. If the * TestRun does not already exist, then use createTestRun instead. * * @param testRun a TestRun with the updated values. *//* w ww. ja va 2 s . c o m*/ public void updateTestRun(TestRun testRun) { if (testRun == null) { throw new NullPointerException("null is not a valid testRunId"); } testRun.setProjectKey(getProjectKey()); PostMethod post = (PostMethod) getHttpMethod(HTTP_POST, getCuantoUrl() + "/api/updateTestRun"); try { post.setRequestEntity(new StringRequestEntity(testRun.toJSON(), "application/json", null)); int httpStatus = getHttpClient().executeMethod(post); if (httpStatus != HttpStatus.SC_OK) { throw new RuntimeException("Adding the TestRun failed with HTTP status code " + httpStatus + ": \n" + getResponseBodyAsString(post)); } } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } catch (IOException e) { throw new RuntimeException(e); } }
From source file:cuanto.api.CuantoConnector.java
/** * Updates a TestOutcome on the Cuanto server with the details provided. * * @param testOutcome The new details that will replace the corresponding values of the existing TestOutcome. *///w w w. jav a 2s . c om public void updateTestOutcome(TestOutcome testOutcome) { if (testOutcome.getId() == null) { throw new IllegalArgumentException( "The specified TestOutcome has no ID value. Any TestOutcome you wish to" + " update should be fetched from the server first."); } PostMethod post = (PostMethod) getHttpMethod(HTTP_POST, getCuantoUrl() + "/api/updateTestOutcome"); try { post.setRequestEntity(new StringRequestEntity(testOutcome.toJSON(), "application/json", null)); int httpStatus = getHttpClient().executeMethod(post); if (httpStatus != HttpStatus.SC_CREATED) { throw new RuntimeException("Adding the TestRun failed with HTTP status code " + httpStatus + ": \n" + getResponseBodyAsString(post)); } } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } catch (IOException e) { throw new RuntimeException(e); } }
From source file:eu.learnpad.core.impl.sim.XwikiBridgeInterfaceRestResource.java
@Override public String addProcessInstance(String processId, Collection<UserData> potentialUsers, String currentUser) throws LpRestException { HttpClient httpClient = this.getAnonymousClient(); String uri = String.format("%s/learnpad/sim/bridge/instances/%s", this.restPrefix, processId); PostMethod postMethod = new PostMethod(uri); postMethod.addRequestHeader("Content-Type", "application/json"); NameValuePair[] queryString = new NameValuePair[1]; queryString[0] = new NameValuePair("currentuser", currentUser); postMethod.setQueryString(queryString); StringRequestEntity requestEntity = null; String potentialUsersJson = "[]"; try {//from w ww .j a v a 2 s . c o m potentialUsersJson = this.objectWriter.writeValueAsString(potentialUsers); requestEntity = new StringRequestEntity(potentialUsersJson, "application/json", "UTF-8"); postMethod.setRequestEntity(requestEntity); httpClient.executeMethod(postMethod); return IOUtils.toString(postMethod.getResponseBodyAsStream()); } catch (IOException e) { throw new LpRestExceptionXWikiImpl(e.getMessage(), e.getCause()); } }
From source file:edu.uci.ics.pregelix.example.util.TestExecutor.java
public InputStream executeAnyAQLAsync(String str, boolean defer, OutputFormat fmt, String url) throws Exception { // Create a method instance. PostMethod method = new PostMethod(url); if (defer) {//from w w w . j a va 2s.c o m method.setQueryString(new NameValuePair[] { new NameValuePair("mode", "asynchronous-deferred") }); } else { method.setQueryString(new NameValuePair[] { new NameValuePair("mode", "asynchronous") }); } method.setRequestEntity(new StringRequestEntity(str)); method.setRequestHeader("Accept", fmt.mimeType()); // Provide custom retry handler is necessary method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false)); executeHttpMethod(method); InputStream resultStream = method.getResponseBodyAsStream(); String theHandle = IOUtils.toString(resultStream, "UTF-8"); // take the handle and parse it so results can be retrieved InputStream handleResult = getHandleResult(theHandle, fmt); return handleResult; }
From source file:de.laeubisoft.tools.ant.validation.W3CMarkupValidationTask.java
/** * Creates the actual request to the validation server for a given * {@link URL} and returns an inputstream the result can be read from * /*from w w w . j av a 2s . c om*/ * @param uriToCheck * the URL to check * @return the stream to read the response from * @throws IOException * if unrecoverable communication error occurs * @throws BuildException * if server returned unexspected results */ private InputStream buildConnection(final URL uriToCheck) throws IOException, BuildException { List<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new NameValuePair("output", VALIDATOR_FORMAT_OUTPUT)); if (uriToCheck != null) { params.add(new NameValuePair("uri", uriToCheck.toString())); } else { if (fragment != null) { params.add(new NameValuePair("fragment", fragment)); } } if (debug) { params.add(new NameValuePair("debug", "1")); } if (charset != null) { params.add(new NameValuePair("charset", charset)); } if (doctype != null) { params.add(new NameValuePair("doctype", doctype)); } HttpClient httpClient = new HttpClient(); HttpMethodBase method; if (uriToCheck != null) { //URIs must be checked wia traditonal GET... GetMethod getMethod = new GetMethod(validator); getMethod.setQueryString(params.toArray(new NameValuePair[0])); method = getMethod; } else { PostMethod postMethod = new PostMethod(validator); if (fragment != null) { //Fragment request can be checked via FORM Submission postMethod.addParameters(params.toArray(new NameValuePair[0])); } else { //Finally files must be checked with multipart-forms.... postMethod.setRequestEntity(Tools.createFileUpload(uploaded_file, "uploaded_file", charset, params, postMethod.getParams())); } method = postMethod; } int result = httpClient.executeMethod(method); if (result == HttpStatus.SC_OK) { return method.getResponseBodyAsStream(); } else { throw new BuildException("Server returned " + result + " " + method.getStatusText()); } }
From source file:com.sai.b2blogistic.RegisterActivity.java
/** */ public String uploadPic(String pic_path) { PostMethod postMethod = new PostMethod(HttpRestClient.getAbsoluteUrl("/driver/upload")); try {// w w w . j av a 2s.com File file = new File(pic_path); // FilePart FilePart fp = new FilePart("file", file); Part[] parts = { fp }; // MIMEhttpclientMulitPartRequestEntity MultipartRequestEntity mre = new MultipartRequestEntity(parts, postMethod.getParams()); postMethod.setRequestEntity(mre); HttpClient client = new HttpClient(); client.getHttpConnectionManager().getParams().setConnectionTimeout(50000);// int status = client.executeMethod(postMethod); if (status == HttpStatus.SC_OK) { return postMethod.getResponseBodyAsString(); } else { ToolKits.showShortTips(this, ""); } } catch (Exception e) { e.printStackTrace(); ToolKits.showShortTips(this, "" + e.getMessage()); } finally { // postMethod.releaseConnection(); } return null; }
From source file:com.zimbra.cs.dav.service.DavMethod.java
public HttpMethod toHttpMethod(DavContext ctxt, String targetUrl) throws IOException, DavException { if (ctxt.getUpload() != null && ctxt.getUpload().getSize() > 0) { PostMethod method = new PostMethod(targetUrl) { @Override//from w w w.j a va 2s . c o m public String getName() { return getMethodName(); } }; RequestEntity reqEntry; if (ctxt.hasRequestMessage()) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); XMLWriter writer = new XMLWriter(baos); writer.write(ctxt.getRequestMessage()); reqEntry = new ByteArrayRequestEntity(baos.toByteArray()); } else { // this could be a huge upload reqEntry = new InputStreamRequestEntity(ctxt.getUpload().getInputStream(), ctxt.getUpload().getSize()); } method.setRequestEntity(reqEntry); return method; } return new GetMethod(targetUrl) { @Override public String getName() { return getMethodName(); } }; }
From source file:com.zimbra.qa.unittest.TestFileUpload.java
@Test public void testMissingCsrfAdminUpload() throws Exception { SoapHttpTransport transport = new SoapHttpTransport(TestUtil.getAdminSoapUrl()); com.zimbra.soap.admin.message.AuthRequest req = new com.zimbra.soap.admin.message.AuthRequest( LC.zimbra_ldap_user.value(), LC.zimbra_ldap_password.value()); req.setCsrfSupported(true);//from ww w . java 2 s . c o m Element response = transport.invoke(JaxbUtil.jaxbToElement(req, SoapProtocol.SoapJS.getFactory())); com.zimbra.soap.admin.message.AuthResponse authResp = JaxbUtil.elementToJaxb(response); String authToken = authResp.getAuthToken(); int port = 7071; try { port = Provisioning.getInstance().getLocalServer().getIntAttr(Provisioning.A_zimbraAdminPort, 0); } catch (ServiceException e) { ZimbraLog.test.error("Unable to get admin SOAP port", e); } String Url = "https://localhost:" + port + ADMIN_UPLOAD_URL; PostMethod post = new PostMethod(Url); FilePart part = new FilePart(FILE_NAME, new ByteArrayPartSource(FILE_NAME, "some file content".getBytes())); String contentType = "application/x-msdownload"; part.setContentType(contentType); HttpClient client = ZimbraHttpConnectionManager.getInternalHttpConnMgr().newHttpClient(); HttpState state = new HttpState(); state.addCookie(new org.apache.commons.httpclient.Cookie("localhost", ZimbraCookie.authTokenCookieName(true), authToken, "/", null, false)); client.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY); client.setState(state); post.setRequestEntity(new MultipartRequestEntity(new Part[] { part }, post.getParams())); int statusCode = HttpClientUtil.executeMethod(client, post); assertEquals("This request should succeed. Getting status code " + statusCode, HttpStatus.SC_OK, statusCode); String resp = post.getResponseBodyAsString(); assertNotNull("Response should not be empty", resp); assertTrue("Incorrect HTML response", resp.contains(RESP_STR)); }
From source file:com.zimbra.qa.unittest.TestFileUpload.java
@Test public void testAdminUploadWithCsrfInHeader() throws Exception { SoapHttpTransport transport = new SoapHttpTransport(TestUtil.getAdminSoapUrl()); com.zimbra.soap.admin.message.AuthRequest req = new com.zimbra.soap.admin.message.AuthRequest( LC.zimbra_ldap_user.value(), LC.zimbra_ldap_password.value()); req.setCsrfSupported(true);//from w w w.java 2 s.com Element response = transport.invoke(JaxbUtil.jaxbToElement(req, SoapProtocol.SoapJS.getFactory())); com.zimbra.soap.admin.message.AuthResponse authResp = JaxbUtil.elementToJaxb(response); String authToken = authResp.getAuthToken(); String csrfToken = authResp.getCsrfToken(); int port = 7071; try { port = Provisioning.getInstance().getLocalServer().getIntAttr(Provisioning.A_zimbraAdminPort, 0); } catch (ServiceException e) { ZimbraLog.test.error("Unable to get admin SOAP port", e); } String Url = "https://localhost:" + port + ADMIN_UPLOAD_URL; PostMethod post = new PostMethod(Url); FilePart part = new FilePart(FILE_NAME, new ByteArrayPartSource(FILE_NAME, "some file content".getBytes())); String contentType = "application/x-msdownload"; part.setContentType(contentType); HttpClient client = ZimbraHttpConnectionManager.getInternalHttpConnMgr().newHttpClient(); HttpState state = new HttpState(); state.addCookie(new org.apache.commons.httpclient.Cookie("localhost", ZimbraCookie.authTokenCookieName(true), authToken, "/", null, false)); client.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY); client.setState(state); post.setRequestEntity(new MultipartRequestEntity(new Part[] { part }, post.getParams())); post.addRequestHeader(Constants.CSRF_TOKEN, csrfToken); int statusCode = HttpClientUtil.executeMethod(client, post); assertEquals("This request should succeed. Getting status code " + statusCode, HttpStatus.SC_OK, statusCode); String resp = post.getResponseBodyAsString(); assertNotNull("Response should not be empty", resp); assertTrue("Incorrect HTML response", resp.contains(RESP_STR)); }
From source file:com.cubeia.backoffice.users.client.UserServiceClientHTTP.java
@Override public AuthenticationResponse authenticate(Long operatorId, String username, String password) { PostMethod method = new PostMethod(baseUrl + AUTHENTICATE); AuthenticationRequest request = new AuthenticationRequest(); request.setOperatorId(operatorId);//from ww w. j a v a2 s . co m request.setUserName(username); request.setPassword(password); try { String data = serialize(request); method.setRequestEntity(new StringRequestEntity(data, "application/json", "UTF-8")); // Execute the HTTP Call int statusCode = getClient().executeMethod(method); if (statusCode == HttpStatus.SC_NOT_FOUND) { return null; } if (statusCode == HttpStatus.SC_UNAUTHORIZED) { AuthenticationResponse response = new AuthenticationResponse(); response.setAuthenticated(false); return response; } else if (statusCode == HttpStatus.SC_OK) { InputStream body = method.getResponseBodyAsStream(); return parseJson(body, AuthenticationResponse.class); } else { throw new RuntimeException("Failed to authenticate user, RESPONSE CODE: " + statusCode); } } catch (Exception e) { throw new RuntimeException(e); } finally { method.releaseConnection(); } }