List of usage examples for org.apache.commons.httpclient.methods PostMethod setRequestEntity
public void setRequestEntity(RequestEntity paramRequestEntity)
From source file:com.thoughtworks.twist.mingle.core.MingleClient.java
public void attachFile(String taskId, String comment, String description, AbstractTaskAttachmentSource source, String filename, IProgressMonitor monitor) { PostMethod post = new PostMethod(attachmentUrl(taskId)); List<PartBase> parts = new ArrayList<PartBase>(); String fileName = source.getName(); parts.add(new FilePart("attachments[0]", new AttachmentPartSource(source))); post.setRequestEntity(new MultipartRequestEntity(parts.toArray(new Part[1]), post.getParams())); try {/*from w ww . ja va 2s . c om*/ int executeMethod = getClient().executeMethod(post); String responseBodyAsString = post.getResponseBodyAsString(); System.out.println(); } catch (HttpException e) { throw new RuntimeException(e); } catch (IOException e) { throw new RuntimeException(e); } finally { post.releaseConnection(); } }
From source file:eu.learnpad.cw.rest.internal.DefaultXWikiPackage.java
private void postObject(File objectFile, String spaceName, String pageName, String className) throws XWikiRestException { HttpClient httpClient = new HttpClient(); httpClient.getParams().setAuthenticationPreemptive(true); Credentials defaultcreds = new UsernamePasswordCredentials("Admin", "admin"); httpClient.getState().setCredentials(new AuthScope("localhost", 8080, AuthScope.ANY_REALM), defaultcreds); PostMethod postMethod = new PostMethod("http://localhost:8080/xwiki/rest/wikis/xwiki/spaces/" + spaceName + "/pages/" + pageName + "/objects"); postMethod.addRequestHeader("Accept", "application/xml"); postMethod.addRequestHeader("Accept-Ranges", "bytes"); RequestEntity fileRequestEntity = new FileRequestEntity(objectFile, "application/xml"); postMethod.setRequestEntity(fileRequestEntity); try {/*from w w w . j a va 2 s . co m*/ httpClient.executeMethod(postMethod); } catch (HttpException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
From source file:guru.nidi.atlassian.remote.script.RemoteConfluence.java
Object executeImpl(String command, Object... parameters) throws RpcException { PostMethod post = new PostMethod(serverUrl + "/rpc/json-rpc/confluenceservice-v2/" + command); post.setRequestHeader("Content-Type", "application/json"); HttpUtils.setAuthHeader(post, username, password); ObjectMapper mapper = new ObjectMapper(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); try {// w w w .j a v a 2s . c o m mapper.writeValue(baos, parameters); post.setRequestEntity(new ByteArrayRequestEntity(baos.toByteArray())); int status = client.executeMethod(post); if (status != HttpStatus.SC_OK) { throw new IOException("not ok"); } try { ErrorResponse errorResponse = mapper.readValue(post.getResponseBodyAsString(MAX_RESPONSE_SIZE), ErrorResponse.class); throw new RpcException(errorResponse); } catch (JsonParseException e) { //ignore } catch (JsonMappingException e) { //ignore } try { return mapper.readValue(post.getResponseBodyAsString(MAX_RESPONSE_SIZE), new TypeReference<HashMap<String, Object>>() { }); } catch (JsonParseException e) { //ignore } catch (JsonMappingException e) { //ignore } return mapper.readValue(post.getResponseBodyAsString(MAX_RESPONSE_SIZE), new TypeReference<ArrayList<Object>>() { }); } catch (IOException e) { e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. } return null; }
From source file:guru.nidi.atlassian.remote.script.RemoteJira.java
Object executeImpl(String command, Object... parameters) throws RpcException { PostMethod post = new PostMethod(serverUrl + "/rpc/json-rpc/jirasoapservice-v2/" + command); post.setRequestHeader("Content-Type", "application/json"); HttpUtils.setAuthHeader(post, username, password); ObjectMapper mapper = new ObjectMapper(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); try {/*from ww w . j ava 2s . co m*/ mapper.writeValue(baos, parameters); post.setRequestEntity(new ByteArrayRequestEntity(baos.toByteArray())); int status = client.executeMethod(post); if (status != HttpStatus.SC_OK) { throw new IOException("not ok: " + status + " " + post.getResponseBodyAsString(MAX_RESPONSE_SIZE)); } try { ErrorResponse errorResponse = mapper.readValue(post.getResponseBodyAsString(MAX_RESPONSE_SIZE), ErrorResponse.class); throw new RpcException(errorResponse); } catch (JsonParseException e) { //ignore } catch (JsonMappingException e) { //ignore } try { return mapper.readValue(post.getResponseBodyAsString(MAX_RESPONSE_SIZE), new TypeReference<HashMap<String, Object>>() { }); } catch (JsonParseException e) { //ignore } catch (JsonMappingException e) { //ignore } try { return mapper.readValue(post.getResponseBodyAsString(MAX_RESPONSE_SIZE), new TypeReference<ArrayList<Object>>() { }); } catch (JsonParseException e) { //ignore } catch (JsonMappingException e) { //ignore } return mapper.readValue(post.getResponseBodyAsString(MAX_RESPONSE_SIZE), String.class); } catch (IOException e) { e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. } return null; }
From source file:io.hawt.web.JBossPostApp.java
@Test public void testPostWithCredentials() throws Exception { System.out.println("Using URL: " + url + " user: " + userName + " password: " + password); HttpClient client = new HttpClient(); PostMethod method = new PostMethod(url); //client.getParams().setAuthenticationPreemptive(true); method.setDoAuthentication(true);// ww w . j ava2 s .c o m Credentials defaultcreds = new UsernamePasswordCredentials(userName, password); client.getState().setCredentials(new AuthScope(host, port, AuthScope.ANY_REALM), defaultcreds); //client.getState().setProxyCredentials(new AuthScope(host, port, AuthScope.ANY_REALM), defaultcreds); method.setRequestEntity(new StringRequestEntity(data, "application/json", "UTF-8")); int result = client.executeMethod(method); System.out.println("Status: " + result); String response = method.getResponseBodyAsString(); System.out.println(response); }
From source file:edu.virginia.speclab.juxta.author.view.export.WebServiceClient.java
/** * Create a juxta user account. This will throw if create request failed. * /*w w w. jav a2 s . co m*/ * @param email * @param pass * @param confirm * @param confirm2 * @throws IOException */ public void createAccount(final String name, final String email, final String pass, final String confirm) throws IOException { PostMethod post = new PostMethod(this.baseUrl + "/login/create"); String json = "{\"user\": {" + "\"name\": \"" + name + "\", \"email\": \"" + email + "\", \"password\": \"" + pass + "\", \"password_confirmation\": \"" + confirm + "\"} }"; post.setRequestEntity(new StringRequestEntity(json, "application/json", "utf-8")); post.setRequestHeader("accept", "application/json"); int respCode = execRequest(post, false); if (respCode != 200) { final String msg = getResponseString(post); post.releaseConnection(); throw new IOException("Unable to create account: " + msg); } String out = getResponseString(post); System.out.println(out); post.releaseConnection(); }
From source file:de.laeubisoft.tools.ant.validation.W3CCSSValidationTask.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 ww. j a va 2 s . com * @param uriToCheck * the URL to check (or <code>null</code> if text or file should * be used as input * @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 (text != null) { params.add(new NameValuePair("text", text)); } } if (usermedium != null) { params.add(new NameValuePair("usermedium", usermedium)); } if (profile != null) { params.add(new NameValuePair("profile", profile)); } if (lang != null) { params.add(new NameValuePair("lang", lang)); } if (warning != null) { params.add(new NameValuePair("warning", warning)); } HttpClient httpClient = new HttpClient(); HttpMethodBase method; if (uriToCheck != null) { //URIs must be checked via traditonal GET... GetMethod getMethod = new GetMethod(validator); getMethod.setQueryString(params.toArray(new NameValuePair[0])); method = getMethod; } else { PostMethod postMethod = new PostMethod(validator); if (text != null) { //Text request must be multipart encoded too... postMethod.setRequestEntity(new MultipartRequestEntity(Tools.nvToParts(params).toArray(new Part[0]), postMethod.getParams())); } else { //Finally files must be checked with multipart-forms.... postMethod.setRequestEntity( Tools.createFileUpload(file, "file", null, 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:edu.wfu.inotado.helper.RestClientHelper.java
/** * /* w w w .jav a 2 s.com*/ * * @param strURL * @param xml * @return */ public String postXml(String strURL, String xml) { // either get the previously stored post or create a new one PostMethod post = this.postHolder.get() != null ? this.postHolder.get() : new PostMethod(strURL); InputStream xmlStream = null; String responseStr = null; try { xmlStream = new ByteArrayInputStream(xml.getBytes("UTF-8")); } catch (UnsupportedEncodingException e) { log.error("Unsupport encoding for string: " + xml); } try { post.setRequestEntity(new InputStreamRequestEntity(xmlStream, xml.length())); post.addRequestHeader("Content-type", "text/xml; charset=ISO-8859-1"); HttpClient httpclient = new HttpClient(); int result = httpclient.executeMethod(post); log.debug("Response status code: " + result); log.debug("Response body: "); responseStr = convertStreamToString(post.getResponseBodyAsStream()); log.debug(responseStr); } catch (IOException e) { log.error("error occurred.", e); } finally { post.releaseConnection(); // clean up the holder postHolder.remove(); } return responseStr; }
From source file:net.sf.sail.webapp.domain.webservice.http.impl.HttpRestTransportImpl.java
/** * @see net.sf.sail.webapp.domain.webservice.http.HttpRestTransport#post(net.sf.sail.webapp.domain.webservice.http.HttpPostRequest) *///from w w w . j a v a 2s . co m public Map<String, String> post(final HttpPostRequest httpPostRequestData) throws HttpStatusCodeException { final PostMethod method = new PostMethod(this.baseUrl + httpPostRequestData.getRelativeUrl()); this.setHeaders(httpPostRequestData, method); // set body data final String bodyData = httpPostRequestData.getBodyData(); if (StringUtils.hasText(bodyData)) { method.setRequestEntity(new StringRequestEntity(bodyData)); } // set parameters final Map<String, String> requestParameters = httpPostRequestData.getRequestParameters(); if (requestParameters != null && !requestParameters.isEmpty()) { final Set<String> keys = requestParameters.keySet(); for (Iterator<String> i = keys.iterator(); i.hasNext();) { String key = i.next(); method.addParameter(key, requestParameters.get(key)); } } final Map<String, String> responseHeaders = new HashMap<String, String>(); try { // Execute the method. logRequest(method, bodyData); final int statusCode = this.client.executeMethod(method); httpPostRequestData.isValidResponseStatus(method, statusCode); final Header[] headers = method.getResponseHeaders(); for (int i = 0; i < headers.length; i++) { responseHeaders.put(headers[i].getName(), headers[i].getValue()); } } catch (HttpException e) { logAndThrowRuntimeException(e); } catch (IOException e) { logAndThrowRuntimeException(e); } finally { method.releaseConnection(); } return responseHeaders; }
From source file:com.clarkparsia.sbol.editor.sparql.StardogEndpoint.java
@Override public void validate(RDFInput constraints, String namedGraph) throws Exception { RequestEntity entity = createEntity(constraints); PostMethod post = new PostMethod(url + "/icv/violations"); if (namedGraph != null) { post.setQueryString(new NameValuePair[] { new NameValuePair("graph-uri", namedGraph) }); }//from w w w. j ava 2 s. com post.setRequestEntity(entity); execute(post); ByteStreams.copy(post.getResponseBodyAsStream(), System.out); }