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.epam.wilma.service.http.WilmaHttpClient.java
/** * Posting the given stream to the given URL via HTTP POST method and returns * {@code true} if the request was successful. * * @param url the given URL/*w w w.j a v a2s. c o m*/ * @param resource the given string that will be uploaded as resource * @return {@code true} if the request is successful, otherwise return {@code false} */ public boolean uploadString(String url, String resource) { boolean requestSuccessful = false; PostMethod method = new PostMethod(url); try { method.setRequestEntity(new StringRequestEntity(resource, null, null)); int statusCode = httpclient.executeMethod(method); if (HttpStatus.SC_OK == statusCode) { requestSuccessful = true; } } catch (HttpException e) { LOG.error("Protocol exception occurred when called: " + url, e); } catch (IOException e) { LOG.error("I/O (transport) error occurred when called: " + url, e); } finally { method.releaseConnection(); } return requestSuccessful; }
From source file:com.linkedin.pinot.common.utils.FileUploadUtils.java
public static int sendSegmentJson(final String host, final String port, final JSONObject segmentJson) { PostMethod postMethod = null;//from ww w .j av a 2 s . co m try { RequestEntity requestEntity = new StringRequestEntity(segmentJson.toString(), ContentType.APPLICATION_JSON.getMimeType(), ContentType.APPLICATION_JSON.getCharset().name()); postMethod = new PostMethod("http://" + host + ":" + port + "/" + SEGMENTS_PATH); postMethod.setRequestEntity(requestEntity); postMethod.setRequestHeader(UPLOAD_TYPE, FileUploadType.JSON.toString()); int statusCode = FILE_UPLOAD_HTTP_CLIENT.executeMethod(postMethod); if (statusCode >= 400) { String errorString = "POST Status Code: " + statusCode + "\n"; if (postMethod.getResponseHeader("Error") != null) { errorString += "ServletException: " + postMethod.getResponseHeader("Error").getValue(); } throw new HttpException(errorString); } return statusCode; } catch (Exception e) { LOGGER.error("Caught exception while sending json: {}", segmentJson.toString(), e); Utils.rethrowException(e); throw new AssertionError("Should not reach this"); } finally { if (postMethod != null) { postMethod.releaseConnection(); } } }
From source file:cuanto.api.CuantoConnector.java
/** * Creates a new TestRun on the Cuanto server using the values provided. A TestRun represents tests that were * executed together. The projectKey will be assigned the same projectKey as this CuantoConnector. The testRun * passed in will have it's id value assigned to the server-assigned ID of the created TestRun. * * @param testRun The test run to create. * @return The server-assigned ID of the created TestRun. *///from w w w. j av a 2 s.c o m public Long addTestRun(TestRun testRun) { testRun.setProjectKey(getProjectKey()); PostMethod post = (PostMethod) getHttpMethod(HTTP_POST, getCuantoUrl() + "/api/addTestRun"); try { post.setRequestEntity(new StringRequestEntity(testRun.toJSON(), "application/json", null)); int httpStatus = getHttpClient().executeMethod(post); if (httpStatus == HttpStatus.SC_CREATED) { TestRun created = TestRun.fromJSON(getResponseBodyAsString(post)); testRun.setProjectKey(this.projectKey); testRun.setId(created.getId()); return created.getId(); } else { 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); } catch (ParseException e) { throw new RuntimeException("Error parsing server response", e); } }
From source file:com.zimbra.cs.index.elasticsearch.ElasticSearchIndex.java
private void initializeIndex() { if (haveMappingInfo) { return;/*from w w w .j a v a2 s . c o m*/ } if (!refreshIndexIfNecessary()) { try { ElasticSearchConnector connector = new ElasticSearchConnector(); JSONObject mappingInfo = createMappingInfo(); PutMethod putMethod = new PutMethod(ElasticSearchConnector.actualUrl(indexUrl)); putMethod.setRequestEntity(new StringRequestEntity(mappingInfo.toString(), MimeConstants.CT_APPLICATION_JSON, MimeConstants.P_CHARSET_UTF8)); int statusCode = connector.executeMethod(putMethod); if (statusCode == HttpStatus.SC_OK) { haveMappingInfo = true; refreshIndexIfNecessary(); // Sometimes searches don't seem to honor mapping info. Try to force it } else { ZimbraLog.index.error("Problem Setting mapping information for index with key=%s httpstatus=%d", key, statusCode); } } catch (HttpException e) { ZimbraLog.index.error("Problem Getting mapping information for index with key=" + key, e); } catch (IOException e) { ZimbraLog.index.error("Problem Getting mapping information for index with key=" + key, e); } catch (JSONException e) { ZimbraLog.index.error("Problem Setting mapping information for index with key=" + key, e); } } }
From source file:com.github.pires.example.tests.UserServiceIntegrationTest.java
@Test public void shouldCreateAndRetriveUserWithREST() throws Exception { String payload = "{ " + "\"name\": \"manel joao\", " + "\"properties\": {" + "\"value\": {" + "\"num1\":{" + "\"type\":\"number\", " + "\"value\":\"1\", " + "\"mandatory\":\"false\"}, " + "\"string1\":{" + "\"type\":\"string\", " + "\"value\":\"teste\", " + "\"mandatory\":\"false\"}" + "}}}"; try {//w w w . ja v a2 s .c o m //create user PutMethod put = new PutMethod(USER_MANAGER_URL); put.addRequestHeader("Accept", "application/json"); RequestEntity entity = new StringRequestEntity(payload, "application/json", "UTF-8"); put.setRequestEntity(entity); HttpClient httpclient = new HttpClient(); int result = 0; try { result = httpclient.executeMethod(put); //System.err.println(result); assertTrue(result == 204); } catch (Exception e) { org.junit.Assert.fail("Unable to create user"); } finally { put.releaseConnection(); } //get user URL url = new URL(USER_MANAGER_URL); InputStream in = null; try { in = url.openStream(); } catch (Exception e) { org.junit.Assert.fail("Connection error"); } String res = getStringFromInputStream(in); System.err.println(res); assertTrue(res.contains("\"name\":\"manel joao\"") && res.contains("\"string1\":{") && res.contains("\"num1\":{")); } catch (Exception e) { System.err.println(e.getMessage()); org.junit.Assert.fail("test failed"); } }
From source file:com.inbravo.scribe.rest.service.crm.ms.auth.SOAPExecutor.java
/** * /* w w w . jav a 2 s. c o m*/ * @param url * @param soapEnvelope * @return * @throws UnsupportedEncodingException */ public final String getSOAPResponse(final String url, final String soapEnvelope) throws UnsupportedEncodingException { /* Post the SOAP to MS CRM */ final PostMethod postMethod = new PostMethod(url); postMethod.addRequestHeader("Content-Type", "application/soap+xml; charset=UTF-8"); /* Create new HTTP client */ final HttpClient httpclient = new HttpClient(); RequestEntity entity = new StringRequestEntity(soapEnvelope, "application/x-www-form-urlencoded", null); postMethod.setRequestEntity(entity); try { try { if (logger.isDebugEnabled()) { logger.debug("----Inside execute url: " + postMethod.getURI()); } final int result = httpclient.executeMethod(postMethod); if (logger.isDebugEnabled()) { logger.debug("----Inside execute response code: " + result); } return postMethod.getResponseBodyAsString(); } catch (final Exception exception) { /* Send user error */ throw new ScribeException(ScribeResponseCodes._1008 + "Problem in calling MS CRM URL: " + url); } } finally { if (postMethod != null) { postMethod.releaseConnection(); } } }
From source file:com.owncloud.android.lib.resources.shares.UpdateRemoteShareOperation.java
@Override protected RemoteOperationResult run(OwnCloudClient client) { RemoteOperationResult result = null; int status = -1; /// prepare array of parameters to update List<Pair<String, String>> parametersToUpdate = new ArrayList<Pair<String, String>>(); if (mPassword != null) { parametersToUpdate.add(new Pair<String, String>(PARAM_PASSWORD, mPassword)); }// w w w .j a va 2 s .c o m if (mExpirationDateInMillis < 0) { // clear expiration date parametersToUpdate.add(new Pair(PARAM_EXPIRATION_DATE, "")); } else if (mExpirationDateInMillis > 0) { // set expiration date DateFormat dateFormat = new SimpleDateFormat(FORMAT_EXPIRATION_DATE); Calendar expirationDate = Calendar.getInstance(); expirationDate.setTimeInMillis(mExpirationDateInMillis); String formattedExpirationDate = dateFormat.format(expirationDate.getTime()); parametersToUpdate.add(new Pair(PARAM_EXPIRATION_DATE, formattedExpirationDate)); } // else, ignore - no update /* TODO complete rest of parameters if (mPermissions > 0) { parametersToUpdate.add(new Pair("permissions", Integer.toString(mPermissions))); } if (mPublicUpload != null) { parametersToUpdate.add(new Pair("publicUpload", mPublicUpload.toString()); } */ /// perform required PUT requests PutMethod put = null; String uriString = null; try { Uri requestUri = client.getBaseUri(); Uri.Builder uriBuilder = requestUri.buildUpon(); uriBuilder.appendEncodedPath(ShareUtils.SHARING_API_PATH.substring(1)); uriBuilder.appendEncodedPath(Long.toString(mRemoteId)); uriString = uriBuilder.build().toString(); for (Pair<String, String> parameter : parametersToUpdate) { if (put != null) { put.releaseConnection(); } put = new PutMethod(uriString); put.addRequestHeader(OCS_API_HEADER, OCS_API_HEADER_VALUE); put.setRequestEntity(new StringRequestEntity(parameter.first + "=" + parameter.second, ENTITY_CONTENT_TYPE, ENTITY_CHARSET)); status = client.executeMethod(put); if (status == HttpStatus.SC_OK) { String response = put.getResponseBodyAsString(); // Parse xml response ShareToRemoteOperationResultParser parser = new ShareToRemoteOperationResultParser( new ShareXMLParser()); parser.setOwnCloudVersion(client.getOwnCloudVersion()); parser.setServerBaseUri(client.getBaseUri()); result = parser.parse(response); } else { result = new RemoteOperationResult(false, status, put.getResponseHeaders()); } } } catch (Exception e) { result = new RemoteOperationResult(e); Log_OC.e(TAG, "Exception while updating remote share ", e); if (put != null) { put.releaseConnection(); } } finally { if (put != null) { put.releaseConnection(); } } return result; }
From source file:net.jadler.JadlerStubbingIntegrationTest.java
@Test public void havingUTF8Body() throws Exception { onRequest().havingBodyEqualTo(STRING_WITH_DIACRITICS).respond().withStatus(201); final PostMethod method = new PostMethod("http://localhost:" + port()); method.setRequestEntity(//from ww w.j av a 2s . co m new StringRequestEntity(STRING_WITH_DIACRITICS, "text/plain", UTF_8_CHARSET.name())); int status = client.executeMethod(method); assertThat(status, is(201)); }
From source file:com.cubeia.backoffice.operator.client.OperatorServiceClientHTTP.java
@Override public void createOperator(OperatorDTO operator) { PostMethod method = new PostMethod(baseUrl + CREATE_OPERATOR); prepareMethod(method);//from w w w . j a va 2s.c o m try { String data = serialize(operator); method.setRequestEntity(new StringRequestEntity(data, "application/json", "UTF-8")); // Execute the method. int statusCode = getClient().executeMethod(method); if (statusCode == HttpStatus.SC_NOT_FOUND) { return; } assertResponseCodeOK(method, statusCode); } catch (Exception e) { throw new RuntimeException(e); } finally { method.releaseConnection(); } }
From source file:com.intuit.tank.http.BaseRequest.java
/** * Execute the post. Use this to force the type of response * //w w w . j a v a 2s . c o m * @param newResponse * The response object to populate */ public void doPut(BaseResponse response) { PutMethod httpput = null; try { URL url = BaseRequestHandler.buildUrl(protocol, host, port, path, urlVariables); httpput = new PutMethod(url.toString()); String requestBody = this.getBody(); // Multiple calls can be // expensive, so get it once StringRequestEntity entity; entity = new StringRequestEntity(requestBody, getContentType(), contentTypeCharSet); httpput.setRequestEntity(entity); sendRequest(response, httpput, requestBody); } catch (Exception ex) { throw new RuntimeException(ex); } finally { if (null != httpput) httpput.releaseConnection(); } }