List of usage examples for org.apache.commons.httpclient.methods PostMethod setRequestEntity
public void setRequestEntity(RequestEntity paramRequestEntity)
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);//from w w w. j a v a 2 s . co 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:edu.indiana.d2i.registryext.RegistryExtAgent.java
/** * post multiple resources through a single call, all resources are posted * under 'repoPath'/* w w w . ja v a 2s .co m*/ * * @param repoPath * path in registry where resources should be posted * @param resourceList * list of resources to be posted * @return * @throws HttpException * @throws IOException * @throws RegistryExtException * @throws OAuthSystemException * @throws OAuthProblemException */ public String postMultiResources(String repoPath, List<ResourceFileType> resourceList) throws HttpException, IOException, RegistryExtException, OAuthSystemException, OAuthProblemException { Map<String, Object> session = ActionContext.getContext().getSession(); int statusCode = 200; String accessToken = (String) session.get(Constants.SESSION_TOKEN); String requestURL = composeURL(FILEOPPREFIX, repoPath); if (logger.isDebugEnabled()) { logger.debug("Post request URL=" + requestURL); } HttpClient httpclient = new HttpClient(); PostMethod post = new PostMethod(requestURL); post.addRequestHeader("Content-Type", "multipart/form-data"); post.addRequestHeader("Authorization", "Bearer " + accessToken); Part[] parts = new Part[resourceList.size()]; for (int i = 0; i < resourceList.size(); i++) { parts[i] = new FilePart(resourceList.get(i).getName(), new FilePartSource(resourceList.get(i).getName(), resourceList.get(i).getFile())); } post.setRequestEntity(new MultipartRequestEntity(parts, post.getParams())); try { httpclient.executeMethod(post); statusCode = post.getStatusLine().getStatusCode(); /* handle token expiration */ if (statusCode == 401) { logger.info(String.format("Access token %s expired, going to refresh it", accessToken)); refreshToken(session); // use refreshed access token accessToken = (String) session.get(Constants.SESSION_TOKEN); post.addRequestHeader("Authorization", "Bearer " + accessToken); // re-send the request httpclient.executeMethod(post); statusCode = post.getStatusLine().getStatusCode(); } if (post.getStatusLine().getStatusCode() != 204) { throw new RegistryExtException( "Failed in post resources : HTTP error code : " + post.getStatusLine().getStatusCode()); } } finally { if (post != null) post.releaseConnection(); } return repoPath; }
From source file:com.apifest.oauth20.tests.OAuth20BasicTest.java
public String registerNewScope(String scope, String description, int ccExpiresIn, int passExpiresIn) { PostMethod post = new PostMethod(baseOAuth20Uri + SCOPE_ENDPOINT); String response = null;// w w w . ja va 2s .co m try { JSONObject json = new JSONObject(); json.put("scope", scope); json.put("description", description); json.put("cc_expires_in", ccExpiresIn); json.put("pass_expires_in", passExpiresIn); String requestBody = json.toString(); RequestEntity requestEntity = new StringRequestEntity(requestBody, "application/json", "UTF-8"); post.setRequestHeader(HttpHeaders.CONTENT_TYPE, "application/json"); post.setRequestEntity(requestEntity); response = readResponse(post); log.info(response); } catch (IOException e) { log.error("cannot register new scope", e); } catch (JSONException e) { log.error("cannot register new scope", e); } return response; }
From source file:com.apifest.oauth20.tests.OAuth20BasicTest.java
public String registerNewClient(String clientName, String scope, String redirectUri) { PostMethod post = new PostMethod(baseOAuth20Uri + APPLICATION_ENDPOINT); String response = null;/*www . j a v a 2 s . com*/ try { JSONObject json = new JSONObject(); json.put("name", clientName); json.put("description", DEFAULT_DESCRIPTION); json.put("scope", scope); json.put("redirect_uri", redirectUri); String requestBody = json.toString(); RequestEntity requestEntity = new StringRequestEntity(requestBody, "application/json", "UTF-8"); post.setRequestHeader(HttpHeaders.CONTENT_TYPE, "application/json"); post.setRequestEntity(requestEntity); response = readResponse(post); log.info(response); } catch (IOException e) { log.error("cannot register new client app", e); } catch (JSONException e) { log.error("cannot register new client app", e); } return response; }
From source file:ccc.api.http.SiteBrowserImpl.java
/** {@inheritDoc} */ @Override//from w w w . j av a 2s . co m public String postMultipart(final ResourceSummary rs, final Map<String, String> params) { /* This method deliberately elides charset values to replicate the * behaviour of a typical browser. */ final String boundary = UUID.randomUUID().toString().substring(0, 7); final String newLine = "\r\n"; final PostMethod post = new PostMethod(_hostUrl + rs.getAbsolutePath()); post.setRequestHeader("Content-Type", "multipart/form-data; boundary=" + boundary); final StringBuilder buffer = new StringBuilder(); buffer.append("Content-Type: multipart/form-data"); buffer.append("; boundary="); buffer.append(boundary); buffer.append(newLine); buffer.append(newLine); for (final Map.Entry<String, String> param : params.entrySet()) { buffer.append("--"); buffer.append(boundary); buffer.append(newLine); buffer.append("Content-Disposition: form-data; name=\""); buffer.append(param.getKey()); buffer.append("\""); buffer.append(newLine); buffer.append(newLine); buffer.append(param.getValue()); buffer.append(newLine); } buffer.append("--"); buffer.append(boundary); buffer.append("--"); buffer.append(newLine); post.setRequestEntity(new StringRequestEntity(buffer.toString())); return invoke(post); }
From source file:gr.upatras.ece.nam.fci.uop.UoPGWClient.java
/** * It makes a POST towards the gateway//from w ww . j a v a2 s . com * @author ctranoris * @param resourceInstance sets the name of the resource Instance, e.g.: uop.rubis_db-27 * @param ptmAlias sets the name of the provider URI, e.g.: uop * @param content sets the name of the content; send in utf8 */ public boolean POSTExecute(String resourceInstance, String ptmAlias, String content) { boolean status = false; log.info("content body=" + "\n" + content); HttpClient client = new HttpClient(); String tgwcontent = content; // resource instance is like uop.rubis_db-6 so we need to make it like // this /uop/uop.rubis_db-6 String ptm = ptmAlias; String url = uopGWAddress + "/" + ptm + "/" + resourceInstance; log.info("Request: " + url); // Create a method instance. PostMethod post = new PostMethod(url); post.setRequestHeader("User-Agent", userAgent); post.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); // Provide custom retry handler is necessary post.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(0, false)); //HttpMethodParams. RequestEntity requestEntity = null; try { requestEntity = new StringRequestEntity(tgwcontent, "application/x-www-form-urlencoded", "utf-8"); } catch (UnsupportedEncodingException e1) { e1.printStackTrace(); } post.setRequestEntity(requestEntity); try { // Execute the method. int statusCode = client.executeMethod(post); if (statusCode != HttpStatus.SC_OK) { System.err.println("Method failed: " + post.getStatusLine()); } // Deal with the response. // Use caution: ensure correct character encoding and is not binary // data // print the status and response InputStream responseBody = post.getResponseBodyAsStream(); CopyInputStream cis = new CopyInputStream(responseBody); response_stream = cis.getCopy(); log.info("Response body=" + "\n" + convertStreamToString(response_stream)); response_stream.reset(); // log.info("for address: " + url + " the response is:\n " // + post.getResponseBodyAsString()); status = true; } catch (HttpException e) { System.err.println("Fatal protocol violation: " + e.getMessage()); e.printStackTrace(); return false; } catch (IOException e) { System.err.println("Fatal transport error: " + e.getMessage()); e.printStackTrace(); return false; } finally { // Release the connection. post.releaseConnection(); } return status; }
From source file:com.ephesoft.gxt.batchinstance.server.CopyTroubleshootingArtifacts.java
/** * Creates a post request for the calling a web service with given url. * /*from w ww . j av a2s . c o m*/ * @param tempLogFolderLocation {@link String} the temporary log folder path * @param webServiceURL {@link String} the url of web service * @param serverRegistry {@link ServerRegistry} the server information * @return {@link PostMethod} a post request */ private PostMethod createRequest(final String tempLogFolderLocation, final String webServiceURL, final ServerRegistry serverRegistry) { PostMethod postMethod = new PostMethod(webServiceURL); Part[] partArray = new Part[1]; String zipFolderPath = EphesoftStringUtil.concatenate(tempLogFolderLocation, File.separator, JAVA_APP_SERVER_LOG_FOLDER, File.separator, serverRegistry.getIpAddress()); partArray[0] = new StringPart(BatchInfoConstants.ZIP_FOLDER_PATH, zipFolderPath); LOGGER.debug(EphesoftStringUtil.concatenate("Log folder path for multiple server logs : ", zipFolderPath)); MultipartRequestEntity entity = new MultipartRequestEntity(partArray, postMethod.getParams()); postMethod.setRequestEntity(entity); return postMethod; }
From source file:hoot.services.controllers.ogr.TranslatorResource.java
/** * <NAME>OGR-LTDS Translation Service</NAME> * <DESCRIPTION>/*from w ww. ja va 2 s . com*/ * WARNING: THIS END POINT WILL BE DEPRECATED SOON * To translate osm element into OGR/LTDS format 2 services are available * http://localhost:8080/hoot-services/ogr/ltds/translate/{OSM element id}?translation={translation script} * </DESCRIPTION> * <PARAMETERS> * <translation> * relative path of translation script * </translation> * </PARAMETERS> * <OUTPUT> * TDS output * </OUTPUT> * <EXAMPLE> * <URL>http://localhost:8080/hoot-services/ogr/ltds/translate/-1669795?translation=MGCP.js</URL> * <REQUEST_TYPE>POST</REQUEST_TYPE> * <INPUT> * {some OSM XML} * </INPUT> * <OUTPUT>{"attrs":{"FCODE":"AP030","HCT":"0","UID":"d9c4b1df-066c-4ece-a583-76fec0056b58"},"tableName":"LAP030"}</OUTPUT> * </EXAMPLE> * @param id * @param translation * @param osmXml * @return */ @POST @Path("/ltds/translate/{id}") @Consumes(MediaType.TEXT_PLAIN) @Produces(MediaType.APPLICATION_JSON) public Response translateOsm(@PathParam("id") String id, @QueryParam("translation") final String translation, String osmXml) { String outStr = "unknown"; try { PostMethod mpost = new PostMethod("http://localhost:" + currentPort + "/osmtotds"); try { osmXml = osmXml.replace('"', '\''); JSONObject requestParams = new JSONObject(); requestParams.put("command", "translate"); requestParams.put("uid", id); requestParams.put("input", osmXml); requestParams.put("script", homeFolder + "/translations" + translation); requestParams.put("direction", "toogr"); StringRequestEntity requestEntity = new StringRequestEntity(requestParams.toJSONString(), "text/plain", "UTF-8"); mpost.setRequestEntity(requestEntity); mclient.executeMethod(mpost); String response = mpost.getResponseBodyAsString(); //r = client.execute(post); // String response = EntityUtils.toString(r.getEntity()); JSONParser par = new JSONParser(); JSONObject transRes = (JSONObject) par.parse(response); String tdsOSM = transRes.get("output").toString(); DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); StringReader strReader = new StringReader(tdsOSM); InputSource is = new InputSource(strReader); Document document = builder.parse(is); strReader.close(); String sFCode = null; JSONObject attrib = new JSONObject(); NodeList nodeList = document.getDocumentElement().getChildNodes(); for (int i = 0; i < nodeList.getLength(); i++) { Node node = nodeList.item(i); if (node instanceof Element) { NodeList childNodes = node.getChildNodes(); for (int j = 0; j < childNodes.getLength(); j++) { Node cNode = childNodes.item(j); if (cNode instanceof Element) { String k = ((Element) cNode).getAttribute("k"); String v = ((Element) cNode).getAttribute("v"); attrib.put(k, v); if (k.equalsIgnoreCase("Feature Code")) { String[] parts = v.split(":"); sFCode = parts[0].trim(); } } } } } String sFields = getFields(sFCode); JSONObject ret = new JSONObject(); ret.put("tablenName", ""); ret.put("attrs", attrib); ret.put("fields", sFields); outStr = ret.toJSONString(); } catch (Exception ee) { ResourceErrorHandler.handleError("Failed upload: " + ee.toString(), Status.INTERNAL_SERVER_ERROR, log); } finally { mpost.releaseConnection(); } } catch (Exception e) { ResourceErrorHandler.handleError("Translation error: " + e.toString(), Status.INTERNAL_SERVER_ERROR, log); } return Response.ok(outStr, MediaType.APPLICATION_JSON).build(); }
From source file:com.evolveum.midpoint.model.impl.bulkmodify.PostXML.java
public String searchRolesByNamePostMethod(String roleName) throws Exception { String returnOid = ""; // Get target URL String strURL = "http://localhost:8080/midpoint/ws/rest/roles/search"; // Prepare HTTP post PostMethod post = new PostMethod(strURL); //AUTHENTICATION BY GURER //String username = "administrator"; //String password = "5ecr3t"; String userPass = this.getUsername() + ":" + this.getPassword(); String basicAuth = "Basic " + javax.xml.bind.DatatypeConverter.printBase64Binary(userPass.getBytes("UTF-8")); post.addRequestHeader("Authorization", basicAuth); //construct searching string. place "name" attribute into <values> tags. String sendingXml = XML_TEMPLATE_SEARCH_IGNORECASE; sendingXml = sendingXml.replace("<value></value>", "<value>" + roleName + "</value>"); RequestEntity userSearchEntity = new StringRequestEntity(sendingXml, "application/xml", "UTF-8"); post.setRequestEntity(userSearchEntity); // Get HTTP client HttpClient httpclient = new HttpClient(); // Execute request try {// w w w.ja va2 s .com int result = httpclient.executeMethod(post); // Display status code //System.out.println("Response status code: " + result); // Display response //System.out.println("Response body: "); // System.out.println(post.getResponseBodyAsString()); String sbf = new String(post.getResponseBodyAsString()); //System.out.println(sbf); //find oid if (sbf.contains("oid")) { int begin = sbf.indexOf("oid"); returnOid = (sbf.substring(begin + 5, begin + 41)); } } finally { // Release current connection to the connection pool once you are done post.releaseConnection(); } return returnOid; }
From source file:com.wso2telco.openidtokenbuilder.MIFEOpenIDTokenBuilder.java
/** * Creates the acr./*www .jav a2 s . c o m*/ * * @param msisdn the msisdn * @return the string * @throws IdentityOAuth2Exception the identity o auth2 exception */ public String createACR(String msisdn) throws IdentityOAuth2Exception { StringBuilder requestURLBuilder = new StringBuilder(); requestURLBuilder.append(ACR_HOST_URI); requestURLBuilder.append("/"); //$NON-NLS-1$ requestURLBuilder.append(CREATE_SERVICE); requestURLBuilder.append("/"); //$NON-NLS-1$ requestURLBuilder.append(SERVICE_PROVIDER); requestURLBuilder.append("/"); //$NON-NLS-1$ requestURLBuilder.append(acrAppID); String requestURL = requestURLBuilder.toString(); JSONObject requestBody = new JSONObject(); JSONObject createRequest = null; try { requestBody.put("MSISDN", (Object) new JSONArray().put(msisdn)); //$NON-NLS-1$ createRequest = new JSONObject().put("createAcrRequest", requestBody); //$NON-NLS-1$ StringRequestEntity requestEntity = new StringRequestEntity(createRequest.toString(), "application/json", "UTF-8"); //$NON-NLS-1$ //$NON-NLS-2$ PostMethod postMethod = new PostMethod(requestURL); postMethod.addRequestHeader("Authorization-ACR", "ServiceKey " + SERVICE_KEY); //$NON-NLS-1$ //$NON-NLS-2$ postMethod.addRequestHeader("Authorization", "Bearer " + ACR_ACCESS_TOKEN); //$NON-NLS-1$ //$NON-NLS-2$ postMethod.setRequestEntity(requestEntity); if (DEBUG) { log.debug("Connecting to ACR engine @ " + ACR_HOST_URI); //$NON-NLS-1$ log.debug("Service name : " + CREATE_SERVICE); //$NON-NLS-1$ log.debug("Service provider : " + SERVICE_PROVIDER); //$NON-NLS-1$ log.debug("App key : " + acrAppID); //$NON-NLS-1$ log.debug("Request - create ACR : " + requestEntity.getContent()); //$NON-NLS-1$ } httpClient = new HttpClient(); httpClient.executeMethod(postMethod); return new String(postMethod.getResponseBody(), "UTF-8"); //$NON-NLS-1$ } catch (UnsupportedEncodingException e) { log.error("Error occured while creating request", e); //$NON-NLS-1$ throw new IdentityOAuth2Exception("Error occured while creating request", e); //$NON-NLS-1$ } catch (JSONException e) { log.error("Error occured while creating request", e); //$NON-NLS-1$ throw new IdentityOAuth2Exception("Error occured while creating request", e); //$NON-NLS-1$ } catch (HttpException e) { log.error("Error occured while creating ACR", e); //$NON-NLS-1$ throw new IdentityOAuth2Exception("Error occured while creating ACR", e); //$NON-NLS-1$ } catch (IOException e) { log.error("Error occured while creating ACR", e); //$NON-NLS-1$ throw new IdentityOAuth2Exception("Error occured while creating ACR", e); //$NON-NLS-1$ } }