List of usage examples for org.apache.commons.httpclient.methods PostMethod setRequestEntity
public void setRequestEntity(RequestEntity paramRequestEntity)
From source file:net.jadler.JadlerStubbingIntegrationTest.java
@Test public void havingISOBody() throws Exception { onRequest().havingBodyEqualTo(STRING_WITH_DIACRITICS).respond().withStatus(201); final PostMethod method = new PostMethod("http://localhost:" + port()); method.setRequestEntity( new StringRequestEntity(STRING_WITH_DIACRITICS, "text/plain", ISO_8859_2_CHARSET.name())); int status = client.executeMethod(method); assertThat(status, is(201));//from ww w . j a v a2s. c o m }
From source file:com.xerox.amazonws.sqs.MessageQueue.java
/** * Sends a message to a specified queue. The message must be between 1 and 256K bytes long. * * @param msg the message to be sent//from w w w. ja v a 2s . c o m */ public String sendMessage(String msg) throws SQSException { Map<String, String> params = new HashMap<String, String>(); String encodedMsg = enableEncoding ? new String(Base64.encodeBase64(msg.getBytes())) : msg; PostMethod method = new PostMethod(); try { method.setRequestEntity(new StringRequestEntity(encodedMsg, "text/plain", null)); SendMessageResponse response = makeRequest(method, "SendMessage", params, SendMessageResponse.class); return response.getMessageId(); } catch (JAXBException ex) { throw new SQSException("Problem parsing returned message.", ex); } catch (HttpException ex) { throw new SQSException(ex.getMessage(), ex); } catch (IOException ex) { throw new SQSException(ex.getMessage(), ex); } finally { method.releaseConnection(); } }
From source file:eu.learnpad.core.impl.sim.XwikiBridgeInterfaceRestResource.java
@Override public String addProcessInstance(ProcessInstanceData data) throws LpRestException { HttpClient httpClient = this.getAnonymousClient(); String uri = String.format("%s/learnpad/sim/bridge/instances", this.restPrefix); PostMethod postMethod = new PostMethod(uri); postMethod.addRequestHeader("Content-Type", "application/json"); try {/*from w ww .j av a2 s .co m*/ // Not fully tested, but is looks working for our purposes -- Gulyx String mashelledData = objectWriter.writeValueAsString(data); RequestEntity requestEntity = new StringRequestEntity(mashelledData, "application/json", "UTF-8"); postMethod.setRequestEntity(requestEntity); httpClient.executeMethod(postMethod); // Not fully tested, but is looks working for our purposes -- Gulyx return objectReaderString.readValue(postMethod.getResponseBodyAsStream()); } catch (IOException e) { throw new LpRestExceptionXWikiImpl(e.getMessage(), e.getCause()); } }
From source file:com.aptana.jira.core.JiraManager.java
/** * Adds an attachment to a JIRA ticket./*from w w w . jav a 2 s. c om*/ * * @param path * the path of the file to be attached * @param issue * the JIRA ticket * @throws JiraException */ public void addAttachment(IPath path, JiraIssue issue) throws JiraException { if (path == null || issue == null) { return; } if (user == null) { throw new JiraException(Messages.JiraManager_ERR_NotLoggedIn); } // Use Apache HTTPClient to POST the file HttpClient httpclient = new HttpClient(); UsernamePasswordCredentials creds = new UsernamePasswordCredentials(user.getUsername(), user.getPassword()); httpclient.getState().setCredentials(new AuthScope(HOST_NAME, 443), creds); httpclient.getParams().setAuthenticationPreemptive(true); PostMethod filePost = null; try { filePost = new PostMethod(createAttachmentURL(issue)); File file = path.toFile(); // MUST USE "file" AS THE NAME!!! Part[] parts = { new FilePart("file", file) }; //$NON-NLS-1$ filePost.setRequestEntity(new MultipartRequestEntity(parts, filePost.getParams())); filePost.setContentChunked(true); filePost.setDoAuthentication(true); // Special header to tell JIRA not to do XSFR checking filePost.setRequestHeader("X-Atlassian-Token", "nocheck"); //$NON-NLS-1$ //$NON-NLS-2$ int responseCode = httpclient.executeMethod(filePost); if (responseCode != HttpURLConnection.HTTP_OK && responseCode != HttpURLConnection.HTTP_CREATED) { // TODO This is a JSON response that we should parse out "errorMessages" value(s) (its an array of // strings). throw new JiraException(filePost.getResponseBodyAsString()); } String json = filePost.getResponseBodyAsString(); IdeLog.logInfo(JiraCorePlugin.getDefault(), json); } catch (JiraException e) { throw e; } catch (Exception e) { throw new JiraException(e.getMessage(), e); } finally { if (filePost != null) { filePost.releaseConnection(); } } }
From source file:com.cloudfoundry.bae.cloudpush.RequestCore.java
private void executeRequest() { HttpClient client = new HttpClient(); HttpConnectionManagerParams hcManagerParams = client.getHttpConnectionManager().getParams(); hcManagerParams.setConnectionTimeout(connectionOption.connectionTimeout); hcManagerParams.setSoTimeout(connectionOption.optTimeout); PostMethod post = new PostMethod(requestUrl); if (requestHeaders != null && !requestHeaders.isEmpty()) { Set<String> headerKeySet = requestHeaders.keySet(); for (String headerKey : headerKeySet) { String headerValue = requestHeaders.get(headerKey); post.addRequestHeader(headerKey, headerValue); }//w w w. jav a 2 s . c o m } post.setRequestEntity(new StringRequestEntity(requestBody)); try { responseCode = client.executeMethod(post); responseBody = post.getResponseBodyAsString(); logger.info(responseBody); Header[] rspHeaders = post.getResponseHeaders(); responseHeaders = new HashMap<String, String>(); for (Header rspHeader : rspHeaders) { responseHeaders.put(rspHeader.getName(), rspHeader.getValue()); } } catch (IOException ex) { logger.error(ex); } }
From source file:edu.virginia.speclab.juxta.author.view.export.WebServiceClient.java
public String beginExport(final File jxtFile, final String name, final String desc, boolean overwrite) throws IOException { PostMethod post = null; if (overwrite) { post = new PostMethod(this.baseUrl + "/import?overwrite"); } else {/* w w w.ja va 2 s .c o m*/ post = new PostMethod(this.baseUrl + "/import"); } Part[] parts = { new StringPart("token", this.authToken), new StringPart("setName", name), new StringPart("description", desc), new FilePart("jxtFile", jxtFile) }; post.setRequestEntity(new MultipartRequestEntity(parts, post.getParams())); execRequest(post); String response = getResponseString(post); post.releaseConnection(); return response; }
From source file:com.funambol.json.dao.AuthenticatorDAOImpl.java
public JsonResponse logout(JsonUser user) throws HttpException, IOException { String request = Utility.getUrl(serverUrl, LOGOUT_URL); if (log.isTraceEnabled()) { log.trace("Logout Request: " + request); }/* w ww . j av a 2 s. c o m*/ String t = user.getSessionID(); PostMethod post = new PostMethod(request); post.setRequestHeader(Utility.TOKEN_HEADER_NAME, t); // //{"data":{ // "sessionid":"4B339C8F5437B7A9506D8C69901833BF" // } //} JSONObject jsonRoot = new JSONObject(); JSONObject jsonData = new JSONObject(); jsonData.element(JsonAuthResponseModel.SESSIONID.getValue(), t); jsonRoot.element(JsonAuthResponseModel.DATA.getValue(), jsonData); post.setRequestEntity(new StringRequestEntity(jsonRoot.toString())); int statusCode = 0; String responseBody = null; try { statusCode = httpClient.executeMethod(post); responseBody = post.getResponseBodyAsString(); } finally { post.releaseConnection(); } if (log.isTraceEnabled()) { log.trace("---------> statusCode: " + statusCode + " responseBody: " + responseBody); } JsonResponse jsonServerResponse = new JsonResponse(statusCode, responseBody); return jsonServerResponse; }
From source file:com.mindquarry.search.serializer.IndexPostSerializer.java
@Override public void endDocument() throws SAXException { super.endDocument(); Node node = this.res.getNode(); Element root = (Element) ((Document) node).getFirstChild(); String action = root.getAttribute("action"); //$NON-NLS-1$ NodeList children = root.getChildNodes(); if (true) { // should resolve the action and find out wether it is a // cycle through all children of the root element for (int i = 0; i < children.getLength(); i++) { Node child = children.item(i); // for every child element... if (child instanceof Element) { // block source which can be posted by creating a new // servlet request URL url = null;//from w w w . j av a 2 s. c o m try { url = new URL(action); } catch (MalformedURLException e1) { e1.printStackTrace(); } HttpClient client = new HttpClient(); client.getState().setCredentials( new AuthScope(url.getHost(), url.getPort(), AuthScope.ANY_REALM), new UsernamePasswordCredentials(login, password)); PostMethod pMethod = new PostMethod(action); pMethod.setDoAuthentication(true); pMethod.addRequestHeader("accept", "text/xml"); //$NON-NLS-1$ //$NON-NLS-2$ ByteArrayOutputStream baos = new ByteArrayOutputStream(); TransformerFactory tf = TransformerFactory.newInstance(); try { tf.newTransformer().transform(new DOMSource(child), new StreamResult(baos)); pMethod.setRequestEntity(new ByteArrayRequestEntity(baos.toByteArray())); client.executeMethod(pMethod); } catch (TransformerConfigurationException e) { getLogger().error("Failed to configure transformer prior to posting", e); } catch (TransformerException e) { getLogger().error("Failed to transform prior to posting", e); } catch (HttpException e) { getLogger().error("Failed to post", e); } catch (IOException e) { getLogger().error("Something went wrong", e); } } } } }
From source file:net.jadler.JadlerStubbingIntegrationTest.java
@Test public void havingParameterPOST() throws Exception { final String body = "p1=p1v1&p2=p2v1&p2=p2v2&p3=&p4"; onRequest().havingParameter("p1").havingParameter("p1", hasSize(1)) .havingParameter("p1", everyItem(not(isEmptyOrNullString()))) .havingParameter("p1", contains("p1v1")).havingParameterEqualTo("p1", "p1v1").havingParameter("p2") .havingParameter("p2", hasSize(3)).havingParameter("p2", hasItems("p2v1", "p2v2", "p2v3")) .havingParameterEqualTo("p2", "p2v1").havingParameterEqualTo("p2", "p2v2") .havingParameterEqualTo("p2", "p2v3").havingParameters("p1", "p2").havingParameter("p3") .havingParameter("p3", contains("")).havingParameterEqualTo("p3", "").havingParameter("p4") .havingParameter("p4", contains("")).havingParameterEqualTo("p4", "") .havingParameter("p5", nullValue()).havingBodyEqualTo(body).respond().withStatus(201); final PostMethod method = new PostMethod("http://localhost:" + port() + "?p2=p2v3"); method.setRequestEntity(new StringRequestEntity(body, "application/x-www-form-urlencoded", "UTF-8")); int status = client.executeMethod(method); assertThat(status, is(201));/* w w w .ja v a 2s . c o m*/ }
From source file:com.wfreitas.camelsoap.SoapClient.java
public String sendRequest(String address, String message, String action) throws Exception { String responseBodyAsString;/* ww w . ja va 2 s . com*/ PostMethod postMethod = new PostMethod(address); try { HttpClient client = new HttpClient(); postMethod.setRequestHeader("SOAPAction", action); postMethod.setRequestEntity( new InputStreamRequestEntity(new ByteArrayInputStream(message.getBytes("UTF-8")), "text/xml") ); client.executeMethod(postMethod); responseBodyAsString = postMethod.getResponseBodyAsString(); } finally { postMethod.releaseConnection(); } return responseBodyAsString; }