List of usage examples for org.apache.commons.httpclient.methods StringRequestEntity StringRequestEntity
public StringRequestEntity(String paramString1, String paramString2, String paramString3) throws UnsupportedEncodingException
From source file:com.intuit.tank.httpclient3.TankHttpClient3.java
@Override public void doPost(BaseRequest request) { try {//from www. j av a2s . c o m PostMethod httppost = new PostMethod(request.getRequestUrl()); String requestBody = request.getBody(); RequestEntity entity = null; if (BaseRequest.CONTENT_TYPE_MULTIPART.equalsIgnoreCase(request.getContentType())) { List<Part> parts = buildParts(request); entity = new MultipartRequestEntity(parts.toArray(new Part[parts.size()]), httppost.getParams()); } else { entity = new StringRequestEntity(requestBody, request.getContentType(), request.getContentTypeCharSet()); } httppost.setRequestEntity(entity); sendRequest(request, httppost, requestBody); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } }
From source file:com.temenos.interaction.example.odata.notes.CreateReadUpdateDeleteITCase.java
/** * Tests create with application/x-www-form-urlencoded request Content-Type. * /* w w w . j a v a 2 s . co m*/ * @throws HttpException * @throws IOException */ @Test public void testCreateUrlEncodedForm() throws HttpException, IOException { ODataConsumer consumer = ODataJerseyConsumer.newBuilder(Configuration.TEST_ENDPOINT_URI).build(); EdmDataServices metadata = consumer.getMetadata(); HttpClient client = new HttpClient(); PostMethod postMethod = new PostMethod(Configuration.TEST_ENDPOINT_URI + PERSONS_RESOURCE); postMethod.setRequestEntity( new StringRequestEntity("name=RonOnForm&abcd=", "application/x-www-form-urlencoded", "UTF-8")); postMethod.addRequestHeader("Content-Type", PostMethod.FORM_URL_ENCODED_CONTENT_TYPE); postMethod.addRequestHeader("Accept", "application/atom+xml"); String personId = null; try { client.executeMethod(postMethod); assertEquals(201, postMethod.getStatusCode()); InputStream is = postMethod.getResponseBodyAsStream(); InputStreamReader isr = new InputStreamReader(is); char[] buffer = new char[1]; int read = 0; int offset = 0; while ((read = isr.read(buffer, offset, buffer.length - offset)) != -1) { offset += read; if (offset >= buffer.length) { buffer = Arrays.copyOf(buffer, buffer.length * 2); } } char[] carr = Arrays.copyOf(buffer, offset); int checkEOF = is.read(); assertEquals(-1, checkEOF); String str = new String(carr); assertEquals("application/atom+xml", postMethod.getResponseHeader("Content-Type").getValue()); FormatParser<Entry> parser = FormatParserFactory.getParser(Entry.class, FormatType.ATOM, new Settings(ODataConstants.DATA_SERVICE_VERSION, metadata, PERSON_ENTITYSET_NAME, null, null)); Entry entry = parser.parse(new StringReader(str)); personId = entry.getEntity().getProperty("id").getValue().toString(); assertEquals("RonOnForm", entry.getEntity().getProperty("name").getValue().toString()); } finally { postMethod.releaseConnection(); } assertNotNull(personId); // read the person to check it was created ok OEntity person = consumer.getEntity(PERSON_ENTITYSET_NAME, Integer.valueOf(personId)).execute(); assertTrue(person != null); assertEquals("RonOnForm", person.getProperty("name").getValue()); }
From source file:eu.eco2clouds.scheduler.em.EMClientHC.java
private String postMethod(String url, String payload, String contentType, Boolean exception) { // Create an instance of HttpClient. HttpClient client = getHttpClient(); logger.debug("Connecting to: " + url); // Create a method instance. PostMethod method = new PostMethod(url); //setHeaders(method, contentType); setHeaders(method, Configuration.bonfireApiGroup); // Provide custom retry handler is necessary method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false)); String response = ""; try {//www.ja v a 2 s. c o m RequestEntity requestEntity = new StringRequestEntity(payload, contentType, null); method.setRequestEntity(requestEntity); // Execute the method. int statusCode = client.executeMethod(method); if (statusCode >= 200 && statusCode > 300) { //TODO test for this case... logger.warn( "post managed experiments information... : " + url + " failed: " + method.getStatusLine()); } else { // Read the response body. byte[] responseBody = method.getResponseBody(); response = new String(responseBody); } } catch (HttpException e) { logger.warn("Fatal protocol violation: " + e.getMessage()); e.printStackTrace(); exception = true; } catch (IOException e) { logger.warn("Fatal transport error: " + e.getMessage()); e.printStackTrace(); exception = true; } finally { // Release the connection. method.releaseConnection(); } return response; }
From source file:com.atlantbh.jmeter.plugins.rest.RestSampler.java
/** * Method invoked by JMeter when a sample needs to happen. It's actually an * indirect call from the main sampler interface. it's resolved in the base * class.//from w ww . java 2 s . c om * * This is a copy and paste from the HTTPSampler2 - quick and dirty hack as * that class is not very extensible. The reason to extend and slightly * modify is that I needed to get the body content from a text field in the * GUI rather than a file. */ public SampleResult sample() { HttpMethodBase httpMethod = null; HttpClient client = null; InputStream instream = null; SampleResult res = new SampleResult(); try { res.setSuccessful(false); res.setResponseCode("000"); res.setSampleLabel(getName()); res.setURL(getUrl()); res.setDataEncoding("UTF-8"); res.setDataType("text/xml"); res.setMonitor(isMonitor()); res.sampleStart(); String urlStr = getUrl().toString(); String request = getMethod().toString() + " " + urlStr + "\n"; request += getRequestBody().toString(); res.setSamplerData(request); log.debug("Start : sample " + urlStr); log.debug("method " + getMethod()); httpMethod = createHttpMethod(getMethod(), urlStr); // Set any default request headers setDefaultRequestHeaders(httpMethod); // Setup connection client = setupConnection(getUrl(), httpMethod); // Handle the various methods if (httpMethod instanceof EntityEnclosingMethod) { ((EntityEnclosingMethod) httpMethod) .setRequestEntity(new StringRequestEntity(getRequestBody(), "text/xml", "UTF-8")); //res.setQueryString(getRequestBody()); //String postBody = sendData((EntityEnclosingMethod) httpMethod); //res.setResponseData(postBody.getBytes()); //String postBody = ""; //try { postBody = Base64Util.processStargateRequest(getRequestBody());} //catch (Exception e) {postBody =getRequestBody(); e.printStackTrace();} // //res.setSamplerData(/*res.getSamplerData() + "\r\n*/"ORIGINAL CONTENT:\r\n\r\n" + getRequestBody() + "\r\n\r\nSENT CONTENT:\r\n\r\n" + postBody); } overrideHeaders(httpMethod); res.setRequestHeaders(getConnectionHeaders(httpMethod)); int statusCode = -1; try { statusCode = client.executeMethod(httpMethod); } catch (RuntimeException e) { log.error("Exception when executing '" + httpMethod + "'", e); throw e; } // Request sent. Now get the response: instream = httpMethod.getResponseBodyAsStream(); if (instream != null) {// will be null for HEAD Header responseHeader = httpMethod.getResponseHeader(HEADER_CONTENT_ENCODING); if (responseHeader != null && ENCODING_GZIP.equals(responseHeader.getValue())) { instream = new GZIPInputStream(instream); } res.setResponseData(readResponse(res, instream, (int) httpMethod.getResponseContentLength())); } //if (res.getResponseDataAsString().length() != 0) // try{ // String response = Base64Util.processStargateResponse(res.getResponseDataAsString()); // res.setResponseData(response); // } catch (Exception e) // { // log.error(e.getMessage()); // } res.sampleEnd(); // Done with the sampling proper. // Now collect the results into the HTTPSampleResult: // res.setSampleLabel(httpMethod.getURI().toString()); // Pick up Actual path (after redirects) res.setResponseCode(Integer.toString(statusCode)); res.setSuccessful(isSuccessCode(statusCode)); res.setResponseMessage(httpMethod.getStatusText()); String ct = null; org.apache.commons.httpclient.Header h = httpMethod.getResponseHeader(HEADER_CONTENT_TYPE); if (h != null)// Can be missing, e.g. on redirect { ct = h.getValue(); res.setContentType(ct);// e.g. text/html; charset=ISO-8859-1 res.setEncodingAndType(ct); } String responseHeaders = getResponseHeaders(httpMethod); res.setResponseHeaders(responseHeaders); /*if (res.isRedirect()) { final Header headerLocation = httpMethod.getResponseHeader(HEADER_LOCATION); if (headerLocation == null) { // HTTP protocol violation, but // avoids NPE throw new IllegalArgumentException("Missing location header"); } res.setRedirectLocation(headerLocation.getValue()); } // If we redirected automatically, the URL may have changed if (getAutoRedirects()) { res.setURL(new URL(httpMethod.getURI().toString())); } // Store any cookies received in the cookie manager: saveConnectionCookies(httpMethod, res.getURL(), getCookieManager()); // Save cache information final CacheManager cacheManager = getCacheManager(); if (cacheManager != null) { cacheManager.saveDetails(httpMethod, res); } // Follow redirects and download page resources if appropriate: res = resultProcessing(areFollowingRedirect, frameDepth, res); */ log.debug("End : sample"); httpMethod.releaseConnection(); return res; } catch (MalformedURLException e) { res.sampleEnd(); log.warn(e.getMessage()); res.setResponseMessage(e.getMessage()); return res; } catch (IllegalArgumentException e)// e.g. some kinds of invalid URL { res.sampleEnd(); //SampleResult err = errorResult(e, res); //err.setSampleLabel("Error: " + url.toString()); log.warn(e.getMessage()); res.setResponseMessage(e.getMessage()); return res; } catch (IOException e) { res.sampleEnd(); log.warn(e.getMessage()); res.setResponseMessage(e.getMessage()); return res; } finally { JOrphanUtils.closeQuietly(instream); if (httpMethod != null) { httpMethod.releaseConnection(); return res; } } }
From source file:com.atlantbh.jmeter.plugins.oauth.OAuthSampler.java
@Override public SampleResult sample() { HttpMethodBase httpMethod = null;/*w w w .j a v a 2 s . c o m*/ HttpClient client = null; InputStream instream = null; SampleResult res = new SampleResult(); try { res.setSuccessful(false); res.setResponseCode("000"); res.setSampleLabel(getName()); res.setURL(getUrl()); res.setDataEncoding("UTF-8"); res.setDataType("text/xml"); res.setSamplerData(getRequestBody()); res.setMonitor(isMonitor()); res.sampleStart(); String urlStr = getUrl().toString(); log.debug("Start : sample " + urlStr); log.debug("method " + getMethod()); httpMethod = createHttpMethod(getMethod(), urlStr); setDefaultRequestHeaders(httpMethod); client = setupConnection(getUrl(), httpMethod); if (httpMethod instanceof EntityEnclosingMethod) { ((EntityEnclosingMethod) httpMethod) .setRequestEntity(new StringRequestEntity(getRequestBody(), "text/xml", "UTF-8")); } overrideHeaders(httpMethod, urlStr, getMethod()); res.setRequestHeaders(getConnectionHeaders(httpMethod)); int statusCode = -1; try { statusCode = client.executeMethod(httpMethod); } catch (RuntimeException e) { log.error("Exception when executing '" + httpMethod + "'", e); throw e; } instream = httpMethod.getResponseBodyAsStream(); if (instream != null) { Header responseHeader = httpMethod.getResponseHeader(HEADER_CONTENT_ENCODING); if (responseHeader != null && ENCODING_GZIP.equals(responseHeader.getValue())) { instream = new GZIPInputStream(instream); } res.setResponseData(readResponse(res, instream, (int) httpMethod.getResponseContentLength())); } res.sampleEnd(); res.setResponseCode(Integer.toString(statusCode)); res.setSuccessful(isSuccessCode(statusCode)); res.setResponseMessage(httpMethod.getStatusText()); String ct = null; org.apache.commons.httpclient.Header h = httpMethod.getResponseHeader(HEADER_CONTENT_TYPE); if (h != null) { ct = h.getValue(); res.setContentType(ct); res.setEncodingAndType(ct); } String responseHeaders = getResponseHeaders(httpMethod); res.setResponseHeaders(responseHeaders); log.debug("End : sample"); httpMethod.releaseConnection(); return res; } catch (MalformedURLException e) { res.sampleEnd(); log.warn(e.getMessage()); res.setResponseMessage(e.getMessage()); return res; } catch (IllegalArgumentException e) { res.sampleEnd(); log.warn(e.getMessage()); res.setResponseMessage(e.getMessage()); return res; } catch (IOException e) { res.sampleEnd(); log.warn(e.getMessage()); res.setResponseMessage(e.getMessage()); return res; } finally { JOrphanUtils.closeQuietly(instream); if (httpMethod != null) { httpMethod.releaseConnection(); return res; } } }
From source file:eu.learnpad.core.impl.cw.XwikiBridgeInterfaceRestResource.java
@Override public void notifyRecommendations(String modelSetId, String simulationid, String userId, Recommendations rec) throws LpRestException { String contentType = "application/xml"; HttpClient httpClient = this.getClient(); String uri = String.format("%s/learnpad/cw/bridge/notify/%s", DefaultRestResource.REST_URI, modelSetId); PutMethod putMethod = new PutMethod(uri); putMethod.addRequestHeader("Accept", contentType); NameValuePair[] queryString = new NameValuePair[2]; queryString[0] = new NameValuePair("simulationid", simulationid); queryString[1] = new NameValuePair("userid", userId); putMethod.setQueryString(queryString); try {//from w ww . j a v a 2 s . c o m JAXBContext jc = JAXBContext.newInstance(Recommendations.class); Writer recWriter = new StringWriter(); Marshaller marshaller = jc.createMarshaller(); marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); marshaller.marshal(rec, recWriter); RequestEntity requestEntity = new StringRequestEntity(recWriter.toString(), contentType, "UTF-8"); putMethod.setRequestEntity(requestEntity); httpClient.executeMethod(putMethod); } catch (JAXBException | IOException e) { throw new LpRestExceptionXWikiImpl(e.getMessage(), e.getCause()); } }
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(/* www .ja va2s . co m*/ new StringRequestEntity(STRING_WITH_DIACRITICS, "text/plain", ISO_8859_2_CHARSET.name())); int status = client.executeMethod(method); assertThat(status, is(201)); }
From source file:com.cubeia.backoffice.users.client.UserServiceClientHTTP.java
@Override public AuthenticationResponse authenticateSessionToken(String sessionToken) { PostMethod method = new PostMethod(baseUrl + AUTHENTICATE_TOKEN); AuthenticationTokenRequest request = new AuthenticationTokenRequest(); request.setSessionToken(sessionToken); try {// w w w .j a v a 2 s . co m 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_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(); } }
From source file:eu.learnpad.core.impl.cw.XwikiCoreFacadeRestResource.java
@Override public String startSimulation(String modelId, String currentUser, UserDataCollection potentialUsers) throws LpRestException { HttpClient httpClient = this.getClient(); String uri = String.format("%s/learnpad/cw/corefacade/simulation/start/%s", DefaultRestResource.REST_URI, modelId);// w ww .ja va2 s . c o m PostMethod postMethod = new PostMethod(uri); postMethod.addRequestHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON); postMethod.addRequestHeader(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON); NameValuePair[] queryString = new NameValuePair[1]; queryString[0] = new NameValuePair("currentuser", currentUser); postMethod.setQueryString(queryString); StringRequestEntity requestEntity = null; ObjectMapper om = new ObjectMapper(); String potentialUsersJson = "[]"; try { potentialUsersJson = om.writeValueAsString(potentialUsers); requestEntity = new StringRequestEntity(potentialUsersJson, "application/json", "UTF-8"); postMethod.setRequestEntity(requestEntity); httpClient.executeMethod(postMethod); } catch (IOException e) { // UnsupportedEncodingException is also caught here! throw new LpRestExceptionXWikiImpl(e.getMessage(), e); } try { return IOUtils.toString(postMethod.getResponseBodyAsStream()); } catch (IOException e) { return null; } }
From source file:edina.eframework.gefcdemo.controllers.ProcessErosionController.java
/** * Brokers the WPS request and response. Supports two different WPS requests, * the landcover preview and the process soil erosion model requests. * /*from w w w. ja va2 s . c o m*/ * @param params parameters used when calculating the soil erosion model * @param wpsResponse results from the WPS process are written to this object * @param template the VM template to use to generate the WPS request * @param wpsOutputFile the filename to write the TIFF result file * @throws IOException * @throws JAXBException */ private void generateWpsRequest(SoilErosionWps params, WpsResponse wpsResponse, String template, String wpsOutputFile) throws IOException, JAXBException { Writer wpsRequest = new StringWriter(); Map<String, Object> velocityMap = new HashMap<String, Object>(); velocityMap.put("params", params); VelocityEngineUtils.mergeTemplate(velocityEngine, template, velocityMap, wpsRequest); wpsRequest.close(); log.debug(wpsRequest.toString()); log.debug("Submitting to " + wpsServer); RequestEntity entity = null; try { entity = new StringRequestEntity(wpsRequest.toString(), "text/xml", "UTF-8"); } catch (UnsupportedEncodingException e) { throw new MalformedURLException("Apparantly 'UTF-8' is an unsupported encoding type."); } PostMethod post = new PostMethod(wpsServer.toString()); post.setRequestEntity(entity); HttpClient client = new HttpClient(new SimpleHttpConnectionManager()); client.getHttpConnectionManager().getParams().setSoTimeout(0); client.getHttpConnectionManager().getParams().setConnectionTimeout(0); client.executeMethod(post); JAXBContext jaxbContext = JAXBContext.newInstance("edina.eframework.gefcdemo.generated.wps"); Unmarshaller unmarshaller = jaxbContext.createUnmarshaller(); ExecuteResponse executeResponse = null; // First save post data into a String so we can log any potential errors. // Response isn't very large from the WPS so this shouldn't be a problem. // Trying to access post data if a direct InputStream is passed to unmarshal // doesn't work. String postData = post.getResponseBodyAsString(); try { executeResponse = (ExecuteResponse) unmarshaller .unmarshal(new ByteArrayInputStream(postData.getBytes())); } catch (ClassCastException e) { log.error("Error from WPS:\n" + postData); throw e; } //executeResponse.getStatus().getProcessAccepted(); // TODO check for failed String resultUrl = executeResponse.getProcessOutputs().getOutput().get(0).getReference().getHref(); log.debug("Output " + resultUrl); wpsResponse.setOutputUrl(new URL(resultUrl)); wpsResponse.setOutputId(resultUrl.substring(resultUrl.lastIndexOf("id=") + 3, resultUrl.length())); wpsResponse.setStatus(200); // Save the WPS output data to a file mapserver can use File resultOutputFile = new File(wpsOutputFile); resultOutputFile.getParentFile().mkdirs(); FileOutputStream resultFileStream = new FileOutputStream(resultOutputFile); InputStream resultInputFile = null; try { resultInputFile = wpsResponse.getOutputUrl().openStream(); byte[] buffer = new byte[4096]; int i; while ((i = resultInputFile.read(buffer)) != -1) { resultFileStream.write(buffer, 0, i); } resultFileStream.flush(); } finally { try { resultInputFile.close(); } catch (Exception e) { } try { resultFileStream.close(); } catch (Exception e) { } } log.debug("Result saved to " + resultOutputFile); }