Java Code Examples for org.apache.commons.httpclient.methods.PostMethod#setRequestEntity()
The following examples show how to use
org.apache.commons.httpclient.methods.PostMethod#setRequestEntity() .
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: SolrWaveIndexerImpl.java From swellrt with Apache License 2.0 | 7 votes |
private void postUpdateToSolr(ReadableWaveletData wavelet, JsonArray docsJson) { PostMethod postMethod = new PostMethod(solrBaseUrl + "/update/json?commit=true"); try { RequestEntity requestEntity = new StringRequestEntity(docsJson.toString(), "application/json", "UTF-8"); postMethod.setRequestEntity(requestEntity); HttpClient httpClient = new HttpClient(); int statusCode = httpClient.executeMethod(postMethod); if (statusCode != HttpStatus.SC_OK) { throw new IndexException(wavelet.getWaveId().serialise()); } } catch (IOException e) { throw new IndexException(String.valueOf(wavelet.getWaveletId()), e); } finally { postMethod.releaseConnection(); } }
Example 2
Source File: PublicApiHttpClient.java From alfresco-remote-api with GNU Lesser General Public License v3.0 | 6 votes |
public HttpResponse post(final RequestContext rq, final String scope, final int version, final String entityCollectionName, final Object entityId, final String relationCollectionName, final Object relationshipEntityId, final String body, String contentType, final Map<String, String> params) throws IOException { RestApiEndpoint endpoint = new RestApiEndpoint(rq.getNetworkId(), scope, version, entityCollectionName, entityId, relationCollectionName, relationshipEntityId, params); String url = endpoint.getUrl(); PostMethod req = new PostMethod(url.toString()); if (body != null) { if (contentType == null || contentType.isEmpty()) { contentType = "application/json"; } StringRequestEntity requestEntity = new StringRequestEntity(body, contentType, "UTF-8"); req.setRequestEntity(requestEntity); } return submitRequest(req, rq); }
Example 3
Source File: BotecoMessage.java From build-notifications-plugin with MIT License | 6 votes |
@Override public void send() { HttpClient client = new HttpClient(); PostMethod post = new PostMethod(endpoint); post.setRequestHeader("Content-Type", "application/json; charset=utf-8"); Map<String, String> values = new HashMap<String, String>(); values.put("title", title); values.put("text", content + "\n\n" + extraMessage); values.put("url", url); values.put("priority", priority); try { post.setRequestEntity(new StringRequestEntity(JSONObject.fromObject(values).toString(), "application/json", "UTF-8")); client.executeMethod(post); } catch (IOException e) { LOGGER.severe("Error while sending notification: " + e.getMessage()); e.printStackTrace(); } }
Example 4
Source File: WebAPI.java From h2o-2 with Apache License 2.0 | 6 votes |
/** * Imports a model from a JSON file. */ public static void importModel() throws Exception { // Upload file to H2O HttpClient client = new HttpClient(); PostMethod post = new PostMethod(URL + "/Upload.json?key=" + JSON_FILE.getName()); Part[] parts = { new FilePart(JSON_FILE.getName(), JSON_FILE) }; post.setRequestEntity(new MultipartRequestEntity(parts, post.getParams())); if( 200 != client.executeMethod(post) ) throw new RuntimeException("Request failed: " + post.getStatusLine()); post.releaseConnection(); // Parse the key into a model GetMethod get = new GetMethod(URL + "/2/ImportModel.json?" // + "destination_key=MyImportedNeuralNet&" // + "type=NeuralNetModel&" // + "json=" + JSON_FILE.getName()); if( 200 != client.executeMethod(get) ) throw new RuntimeException("Request failed: " + get.getStatusLine()); get.releaseConnection(); }
Example 5
Source File: ChatterCommands.java From JavaChatterRESTApi with BSD 3-Clause "New" or "Revised" License | 6 votes |
/** * <p>This creates a HttpMethod with the message as its payload and image attachment. The message should be a properly formatted JSON * String (No validation is done on this).</p> * * <p>The message can be easily created using the {@link #getJsonPayload(Message)} method.</p> * * @param uri The full URI which we will post to * @param message A properly formatted JSON message. UTF-8 is expected * @param image A complete instance of ImageAttachment object * @throws IOException */ public HttpMethod getJsonPostForMultipartRequestEntity(String uri, String message, ImageAttachment image) throws IOException { PostMethod post = new PostMethod(uri); StringPart bodyPart = new StringPart("json", message); bodyPart.setContentType("application/json"); FilePart filePart= new FilePart("feedItemFileUpload", image.retrieveObjectFile()); filePart.setContentType(image.retrieveContentType()); Part[] parts = { bodyPart, filePart, }; post.setRequestEntity(new MultipartRequestEntity(parts, post.getParams())); return post; }
Example 6
Source File: ESBJAVA4846HttpProtocolVersionTestCase.java From micro-integrator with Apache License 2.0 | 6 votes |
@Test(groups = "wso2.esb", description = "Sending HTTP1.1 message") public void sendingHTTP11Message() throws Exception { PostMethod post = new PostMethod(getProxyServiceURLHttp("StockQuoteProxyTestHTTPVersion")); RequestEntity entity = new StringRequestEntity(getPayload(), "text/xml", "UTF-8"); post.setRequestEntity(entity); post.setRequestHeader("SOAPAction", "urn:getQuote"); HttpMethodParams params = new HttpMethodParams(); params.setVersion(HttpVersion.HTTP_1_1); post.setParams(params); HttpClient httpClient = new HttpClient(); String httpVersion = ""; try { httpClient.executeMethod(post); post.getResponseBodyAsString(); httpVersion = post.getStatusLine().getHttpVersion(); } finally { post.releaseConnection(); } Assert.assertEquals(httpVersion, HttpVersion.HTTP_1_1.toString(), "Http version mismatched"); }
Example 7
Source File: GrafanaDashboardServiceImpl.java From cymbal with Apache License 2.0 | 5 votes |
private void addDashboard(String dashboard) throws MonitorException { // format url String url = String.format("%s/%s", grafanaApiUrl, GrafanaDashboardServiceImpl.GRAFANA_ADD_DASHBOARD_URI); PostMethod method = new PostMethod(url); try { // request body method.setRequestEntity(new StringRequestEntity(dashboard, "application/json", CharEncoding.UTF_8)); doHttpAPI(method); } catch (UnsupportedEncodingException e) { new MonitorException(e); } }
Example 8
Source File: PublicApiHttpClient.java From alfresco-remote-api with GNU Lesser General Public License v3.0 | 5 votes |
public HttpResponse post(final Class<?> c, final RequestContext rq, final Object entityId, final Object relationshipEntityId, final String body) throws IOException { RestApiEndpoint endpoint = new RestApiEndpoint(c, rq.getNetworkId(), entityId, relationshipEntityId, null); String url = endpoint.getUrl(); PostMethod req = new PostMethod(url.toString()); if (body != null) { StringRequestEntity requestEntity = new StringRequestEntity(body, "application/json", "UTF-8"); req.setRequestEntity(requestEntity); } return submitRequest(req, rq); }
Example 9
Source File: CreateRouteCommand.java From orion.server with Eclipse Public License 1.0 | 5 votes |
@Override protected ServerStatus _doIt() { try { /* create cloud foundry application */ URI targetURI = URIUtil.toURI(target.getUrl()); URI routesURI = targetURI.resolve("/v2/routes"); //$NON-NLS-1$ PostMethod createRouteMethod = new PostMethod(routesURI.toString()); ServerStatus confStatus = HttpUtil.configureHttpMethod(createRouteMethod, target.getCloud()); if (!confStatus.isOK()) return confStatus; /* set request body */ JSONObject routeRequest = new JSONObject(); routeRequest.put(CFProtocolConstants.V2_KEY_SPACE_GUID, target.getSpace().getCFJSON().getJSONObject(CFProtocolConstants.V2_KEY_METADATA).getString(CFProtocolConstants.V2_KEY_GUID)); routeRequest.put(CFProtocolConstants.V2_KEY_HOST, hostName); routeRequest.put(CFProtocolConstants.V2_KEY_DOMAIN_GUID, domain.getGuid()); createRouteMethod.setRequestEntity(new StringRequestEntity(routeRequest.toString(), "application/json", "utf-8")); //$NON-NLS-1$//$NON-NLS-2$ createRouteMethod.setQueryString("inline-relations-depth=1"); //$NON-NLS-1$ ServerStatus createRouteStatus = HttpUtil.executeMethod(createRouteMethod); if (!createRouteStatus.isOK()) return createRouteStatus; route = new Route().setCFJSON(createRouteStatus.getJsonData()); return createRouteStatus; } catch (Exception e) { String msg = NLS.bind("An error occured when performing operation {0}", commandName); //$NON-NLS-1$ logger.error(msg, e); return new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, msg, e); } }
Example 10
Source File: HttpUtils.java From Java-sdk with Apache License 2.0 | 5 votes |
/** * 处理Post请求 * @param url * @param params post请求参数 * @param jsonString post传递json数据 * @return * @throws HttpException * @throws IOException */ public static JSONObject doPost(String url,Map<String,String> headers,Map<String,String> params,String jsonString) { HttpClient client = new HttpClient(); //post请求 PostMethod postMethod = new PostMethod(url); //设置header setHeaders(postMethod,headers); //设置post请求参数 setParams(postMethod,params); //设置post传递的json数据 if(jsonString!=null&&!"".equals(jsonString)){ postMethod.setRequestEntity(new ByteArrayRequestEntity(jsonString.getBytes())); } String responseStr = ""; try { client.executeMethod(postMethod); responseStr = postMethod.getResponseBodyAsString(); } catch (Exception e) { log.error(e); e.printStackTrace(); responseStr="{status:0}"; } return JSONObject.parseObject(responseStr); }
Example 11
Source File: AbstractSolrQueryHTTPClient.java From alfresco-repository with GNU Lesser General Public License v3.0 | 5 votes |
protected JSONObject postQuery(HttpClient httpClient, String url, JSONObject body) throws UnsupportedEncodingException, IOException, HttpException, URIException, JSONException { PostMethod post = new PostMethod(url); if (body.toString().length() > DEFAULT_SAVEPOST_BUFFER) { post.getParams().setBooleanParameter(HttpMethodParams.USE_EXPECT_CONTINUE, true); } StringRequestEntity requestEntity = new StringRequestEntity(body.toString(), "application/json", "UTF-8"); post.setRequestEntity(requestEntity); try { httpClient.executeMethod(post); if(post.getStatusCode() == HttpStatus.SC_MOVED_PERMANENTLY || post.getStatusCode() == HttpStatus.SC_MOVED_TEMPORARILY) { Header locationHeader = post.getResponseHeader("location"); if (locationHeader != null) { String redirectLocation = locationHeader.getValue(); post.setURI(new URI(redirectLocation, true)); httpClient.executeMethod(post); } } if (post.getStatusCode() != HttpServletResponse.SC_OK) { throw new LuceneQueryParserException("Request failed " + post.getStatusCode() + " " + url.toString()); } Reader reader = new BufferedReader(new InputStreamReader(post.getResponseBodyAsStream(), post.getResponseCharSet())); // TODO - replace with streaming-based solution e.g. SimpleJSON ContentHandler JSONObject json = new JSONObject(new JSONTokener(reader)); return json; } finally { post.releaseConnection(); } }
Example 12
Source File: HttpRobotConnection.java From incubator-retired-wave with Apache License 2.0 | 5 votes |
@Override public String postJson(String url, String body) throws RobotConnectionException { PostMethod method = new PostMethod(url); try { method.setRequestEntity(new StringRequestEntity(body, RobotConnection.JSON_CONTENT_TYPE, Charsets.UTF_8.name())); return fetch(url, method); } catch (IOException e) { String msg = "Robot fetch http failure: " + url + ": " + e; throw new RobotConnectionException(msg, e); } }
Example 13
Source File: DifidoClient.java From difido-reports with Apache License 2.0 | 5 votes |
public int addExecution(ExecutionDetails details) throws Exception { final PostMethod method = new PostMethod(baseUri + "executions/"); method.setRequestHeader(new Header("Content-Type", "application/json")); if (details != null) { final String descriptionJson = new ObjectMapper().writeValueAsString(details); method.setRequestEntity(new StringRequestEntity(descriptionJson,"application/json","UTF-8")); } final int responseCode = client.executeMethod(method); handleResponseCode(method, responseCode); return Integer.parseInt(method.getResponseBodyAsString()); }
Example 14
Source File: CourseGroupMgmtITCase.java From olat with Apache License 2.0 | 5 votes |
@Test public void testUpdateCourseGroup() throws IOException { final HttpClient c = loginWithCookie("administrator", "olat"); final GroupVO vo = new GroupVO(); vo.setKey(g1.getKey()); vo.setName("rest-g1-mod"); vo.setDescription("rest-g1 description"); vo.setMinParticipants(g1.getMinParticipants()); vo.setMaxParticipants(g1.getMaxParticipants()); vo.setType(g1.getType()); final String stringuifiedAuth = stringuified(vo); final RequestEntity entity = new StringRequestEntity(stringuifiedAuth, MediaType.APPLICATION_JSON, "UTF-8"); final String request = "/repo/courses/" + course.getResourceableId() + "/groups/" + g1.getKey(); final PostMethod method = createPost(request, MediaType.APPLICATION_JSON, true); method.setRequestEntity(entity); final int code = c.executeMethod(method); method.releaseConnection(); assertTrue(code == 200 || code == 201); final BusinessGroup bg = businessGroupService.loadBusinessGroup(g1.getKey(), false); assertNotNull(bg); assertEquals(bg.getKey(), vo.getKey()); assertEquals("rest-g1-mod", bg.getName()); assertEquals("rest-g1 description", bg.getDescription()); }
Example 15
Source File: MessageWithoutContentTypeTestCase.java From micro-integrator with Apache License 2.0 | 5 votes |
/** * Sending a message without mentioning Content Type and check the body part at the listening port * <p/> * Public JIRA: WSO2 Carbon/CARBON-6029 * Responses With No Content-Type Header not handled properly * <p/> * Test Artifacts: ESB Sample 0 * * @throws Exception - if the scenario fail */ @SetEnvironment(executionEnvironments = { ExecutionEnvironment.ALL }) @Test(groups = "wso2.esb") public void testMessageWithoutContentType() throws Exception { // Get target URL String strURL = getMainSequenceURL(); // Get SOAP action String strSoapAction = "getQuote"; // Get file to be posted String strXMLFilename = FrameworkPathUtil.getSystemResourceLocation() + "artifacts" + File.separator + "ESB" + File.separator + "synapseconfig" + File.separator + "messagewithoutcontent" + File.separator + "request.xml"; File input = new File(strXMLFilename); // Prepare HTTP post PostMethod post = new PostMethod(strURL); // Request content will be retrieved directly // from the input stream RequestEntity entity = new FileRequestEntity(input, "text/xml"); post.setRequestEntity(entity); // consult documentation for your web service post.setRequestHeader("SOAPAction", strSoapAction); // Get HTTP client HttpClient httpclient = new HttpClient(); // Execute request try { int result = httpclient.executeMethod(post); // Display status code log.info("Response status code: " + result); // Display response log.info("Response body: "); log.info(post.getResponseBodyAsString()); } finally { // Release current connection to the connection pool once you are done post.releaseConnection(); } }
Example 16
Source File: DifidoClient.java From difido-reports with Apache License 2.0 | 5 votes |
public void addTestDetails(int executionId, TestDetails testDetails) throws Exception { PostMethod method = new PostMethod(baseUri + "executions/" + executionId + "/details"); method.setRequestHeader(new Header("Content-Type", "application/json")); final ObjectMapper mapper = new ObjectMapper(); final String json = mapper.writeValueAsString(testDetails); final RequestEntity entity = new StringRequestEntity(json,"application/json","UTF-8"); method.setRequestEntity(entity); final int responseCode = client.executeMethod(method); handleResponseCode(method, responseCode); }
Example 17
Source File: DifidoClient.java From difido-reports with Apache License 2.0 | 5 votes |
public int addExecution(ExecutionDetails details) throws Exception { final PostMethod method = new PostMethod(baseUri + "executions/"); method.setRequestHeader(new Header("Content-Type", "application/json")); if (details != null) { final String descriptionJson = new ObjectMapper().writeValueAsString(details); method.setRequestEntity(new StringRequestEntity(descriptionJson,"application/json","UTF-8")); } final int responseCode = client.executeMethod(method); handleResponseCode(method, responseCode); return Integer.parseInt(method.getResponseBodyAsString()); }
Example 18
Source File: SecurityGroupHttpClient.java From cloudstack with Apache License 2.0 | 5 votes |
public SecurityGroupRuleAnswer call(String agentIp, SecurityGroupRulesCmd cmd) { PostMethod post = new PostMethod(String.format( "http://%s:%s", agentIp, getPort())); try { SecurityGroupVmRuleSet rset = new SecurityGroupVmRuleSet(); rset.getEgressRules().addAll(generateRules(cmd.getEgressRuleSet())); rset.getIngressRules().addAll( generateRules(cmd.getIngressRuleSet())); rset.setVmName(cmd.getVmName()); rset.setVmIp(cmd.getGuestIp()); rset.setVmMac(cmd.getGuestMac()); rset.setVmId(cmd.getVmId()); rset.setSignature(cmd.getSignature()); rset.setSequenceNumber(cmd.getSeqNum()); Marshaller marshaller = context.createMarshaller(); StringWriter writer = new StringWriter(); marshaller.marshal(rset, writer); String xmlContents = writer.toString(); logger.debug(xmlContents); post.addRequestHeader("command", "set_rules"); StringRequestEntity entity = new StringRequestEntity(xmlContents); post.setRequestEntity(entity); if (httpClient.executeMethod(post) != 200) { return new SecurityGroupRuleAnswer(cmd, false, post.getResponseBodyAsString()); } else { return new SecurityGroupRuleAnswer(cmd); } } catch (Exception e) { return new SecurityGroupRuleAnswer(cmd, false, e.getMessage()); } finally { if (post != null) { post.releaseConnection(); } } }
Example 19
Source File: FileUploadWithAttachmentUtil.java From product-es with Apache License 2.0 | 5 votes |
/** * This method uploads a content-type asset (ex: wsdl,policy,wadl,swagger) * to a running G-Reg instance * * @param filePath The absolute path of the file * @param fileVersion Version of the file * @param fileName Name of the file * @param shortName Asset shortname mentioned in the RXT * @param cookieHeader Session cookie * @throws IOException */ public static PostMethod uploadContentTypeAssets(String filePath, String fileVersion, String fileName, String shortName, String cookieHeader, String apiUrl) throws IOException { File file = new File(filePath); //The api implementation requires fileUpload name in the format //of shortname_file (ex: wsdl_file) FilePart fp = new FilePart(shortName + "_file", file); fp.setContentType(MediaType.TEXT_PLAIN); String version = fileVersion; String name = fileName; StringPart sp1 = new StringPart("file_version", version); sp1.setContentType(MediaType.TEXT_PLAIN); StringPart sp2 = new StringPart(shortName + "_file_name", name); sp2.setContentType(MediaType.TEXT_PLAIN); //Set file parts and string parts together final Part[] part = {fp, sp1, sp2}; HttpClient httpClient = new HttpClient(); PostMethod httpMethod = new PostMethod(apiUrl); httpMethod.addRequestHeader("Cookie", cookieHeader); httpMethod.addRequestHeader("Accept", MediaType.APPLICATION_JSON); httpMethod.setRequestEntity( new MultipartRequestEntity(part, httpMethod.getParams()) ); httpClient.executeMethod(httpMethod); return httpMethod; }
Example 20
Source File: ZohoServlet.java From document-management-system with GNU General Public License v2.0 | 4 votes |
/** * */ private Map<String, String> sendToZoho(String zohoUrl, String nodeUuid, String lang) throws PathNotFoundException, AccessDeniedException, RepositoryException, DatabaseException, IOException, OKMException { Map<String, String> result = new HashMap<String, String>(); File tmp = null; try { String path = OKMRepository.getInstance().getNodePath(null, nodeUuid); String fileName = PathUtils.getName(path); tmp = File.createTempFile("okm", ".tmp"); InputStream is = OKMDocument.getInstance().getContent(null, path, false); Document doc = OKMDocument.getInstance().getProperties(null, path); FileOutputStream fos = new FileOutputStream(tmp); IOUtils.copy(is, fos); fos.flush(); fos.close(); String id = UUID.randomUUID().toString(); String saveurl = Config.APPLICATION_BASE + "/extension/ZohoFileUpload"; Part[] parts = {new FilePart("content", tmp), new StringPart("apikey", Config.ZOHO_API_KEY), new StringPart("output", "url"), new StringPart("mode", "normaledit"), new StringPart("filename", fileName), new StringPart("skey", Config.ZOHO_SECRET_KEY), new StringPart("lang", lang), new StringPart("id", id), new StringPart("format", getFormat(doc.getMimeType())), new StringPart("saveurl", saveurl)}; PostMethod filePost = new PostMethod(zohoUrl); filePost.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "UTF-8"); filePost.setRequestEntity(new MultipartRequestEntity(parts, filePost.getParams())); HttpClient client = new HttpClient(); client.getHttpConnectionManager().getParams().setConnectionTimeout(5000); int status = client.executeMethod(filePost); if (status == HttpStatus.SC_OK) { log.debug("OK: " + filePost.getResponseBodyAsString()); ZohoToken zot = new ZohoToken(); zot.setId(id); zot.setUser(getThreadLocalRequest().getRemoteUser()); zot.setNode(nodeUuid); zot.setCreation(Calendar.getInstance()); ZohoTokenDAO.create(zot); // Get the response BufferedReader rd = new BufferedReader(new InputStreamReader(filePost.getResponseBodyAsStream())); String line; while ((line = rd.readLine()) != null) { if (line.startsWith("URL=")) { result.put("url", line.substring(4)); result.put("id", id); break; } } rd.close(); } else { String error = HttpStatus.getStatusText(status) + "\n\n" + filePost.getResponseBodyAsString(); log.error("ERROR: {}", error); throw new OKMException(ErrorCode.get(ErrorCode.ORIGIN_OKMZohoService, ErrorCode.CAUSE_Zoho), error); } } finally { FileUtils.deleteQuietly(tmp); } return result; }