List of usage examples for org.apache.commons.httpclient.methods PostMethod PostMethod
public PostMethod(String paramString)
From source file:net.oauth.client.httpclient3.HttpClient3.java
public HttpResponseMessage execute(HttpMessage request, Map<String, Object> parameters) throws IOException { final String method = request.method; final String url = request.url.toExternalForm(); final InputStream body = request.getBody(); final boolean isDelete = DELETE.equalsIgnoreCase(method); final boolean isPost = POST.equalsIgnoreCase(method); final boolean isPut = PUT.equalsIgnoreCase(method); byte[] excerpt = null; HttpMethod httpMethod;/*www .j a va 2 s . c om*/ if (isPost || isPut) { EntityEnclosingMethod entityEnclosingMethod = isPost ? new PostMethod(url) : new PutMethod(url); if (body != null) { ExcerptInputStream e = new ExcerptInputStream(body); String length = request.removeHeaders(HttpMessage.CONTENT_LENGTH); entityEnclosingMethod.setRequestEntity((length == null) ? new InputStreamRequestEntity(e) : new InputStreamRequestEntity(e, Long.parseLong(length))); excerpt = e.getExcerpt(); } httpMethod = entityEnclosingMethod; } else if (isDelete) { httpMethod = new DeleteMethod(url); } else { httpMethod = new GetMethod(url); } for (Map.Entry<String, Object> p : parameters.entrySet()) { String name = p.getKey(); String value = p.getValue().toString(); if (FOLLOW_REDIRECTS.equals(name)) { httpMethod.setFollowRedirects(Boolean.parseBoolean(value)); } else if (READ_TIMEOUT.equals(name)) { httpMethod.getParams().setIntParameter(HttpMethodParams.SO_TIMEOUT, Integer.parseInt(value)); } } for (Map.Entry<String, String> header : request.headers) { httpMethod.addRequestHeader(header.getKey(), header.getValue()); } HttpClient client = clientPool.getHttpClient(new URL(httpMethod.getURI().toString())); client.executeMethod(httpMethod); return new HttpMethodResponse(httpMethod, excerpt, request.getContentCharset()); }
From source file:com.epam.wilma.test.client.HttpRequestSender.java
/** * Sends a new HTTP request to a server through a proxy. * @param requestParameters a set of parameters that will set the content of the request * and specify the proxy it should go through *//*from ww w . j a v a 2s.c o m*/ public void callWilmaTestServer(final RequestParameters requestParameters, final TestClientParameters clientParameters) { try { HttpClient httpClient = new HttpClient(); String serverUrl = requestParameters.getTestServerUrl(); logger.info("Server URL: " + serverUrl); PostMethod httpPost = new PostMethod(serverUrl); if (clientParameters.isUseProxy()) { String proxyHost = requestParameters.getWilmaHost(); Integer proxyPort = requestParameters.getWilmaPort(); logger.info("Proxy: " + proxyHost + ":" + proxyPort); httpClient.getHostConfiguration().setProxy(proxyHost, proxyPort); } InputStream inputStream = requestParameters.getInputStream(); if (requestParameters.getContentType().contains("fastinfoset")) { logger.info("Compressing it by using FIS."); inputStream = compress(inputStream); } if (requestParameters.getContentEncoding().contains("gzip")) { logger.info("Encoding it by using gzip."); inputStream = encode(inputStream); httpPost.setRequestHeader("Content-Encoding", requestParameters.getContentEncoding()); } InputStreamRequestEntity entity = new InputStreamRequestEntity(inputStream, requestParameters.getContentType()); httpPost.setRequestEntity(entity); String acceptHeader = requestParameters.getAcceptHeader(); logger.info("Accept (header): " + acceptHeader); httpPost.setRequestHeader("Accept", acceptHeader); String acceptEncoding = requestParameters.getAcceptEncoding(); logger.info("Accept-Encoding: " + acceptEncoding); httpPost.addRequestHeader("Accept-Encoding", acceptEncoding); logger.info("Add 'AlterMessage' header."); httpPost.addRequestHeader("AlterMessage", "true"); //always request alter message from Wilma //httpPost.addRequestHeader("0", "WilmaBypass=true"); httpClient.getHttpConnectionManager().getParams() .setSendBufferSize(clientParameters.getRequestBufferSize()); httpClient.getHttpConnectionManager().getParams() .setReceiveBufferSize(clientParameters.getResponseBufferSize()); int statusCode = httpClient.executeMethod(httpPost); logger.info("Response Status Code: " + statusCode); if (clientParameters.getAllowResponseLogging()) { logger.info(getInputStreamAsString(httpPost.getResponseBodyAsStream())); } } catch (UnsupportedEncodingException e) { throw new SystemException("Unsupported encoding.", e); } catch (HttpException e) { throw new SystemException("Http exception occurred.", e); } catch (IOException e) { throw new SystemException("InputStream cannot be read.", e); } }
From source file:edu.du.penrose.systems.util.HttpClientUtils_2.java
static public WebPage academicSearch(URL initialLink) { WebPage wp = new WebPage(); HttpClient client = new HttpClient(); GetMethod getMethod = new GetMethod(initialLink.toString()); getMethod.setFollowRedirects(true);// www . jav a 2 s . c o m try { // System.setProperty("org.apache.commons.logging.Log", "org.apache.commons.logging.impl.SimpleLog"); // System.setProperty("org.apache.commons.logging.simplelog.showdatetime", "true"); // System.setProperty("org.apache.commons.logging.simplelog.log.httpclient.wire.header", "debug"); // System.setProperty("org.apache.commons.logging.simplelog.log.org.apache.commons.httpclient", "debug"); // getMethod.setRequestHeader("User-Agent", "Mozilla/5.001 (windows; U; NT4.0; en-US; rv:1.0) Gecko/25250101"); // in case they check int statusCode = client.executeMethod(getMethod); String contents = getMethod.getResponseBodyAsString(); String formPage = getMethod.getURI().toString(); // page we were sent to. wp.setStatus(statusCode); wp.setWebPage(contents); // System.out.println();System.out.println();System.out.println();System.out.println();System.out.println(contents); String sid = getSID(contents); String postURL = "http://web.ebscohost.com/ehost/search?vid=1&hid=9&sid=" + sid; PostMethod postMethod = new PostMethod( "http://web.ebscohost.com/ehost/search?vid=1&hid=9&sid=c3220986-66e4-4fd1-ba6a-30504f3694ad%40sessionmgr13"); postMethod.setRequestHeader("User-Agent", "Mozilla/5.001 (windows; U; NT4.0; en-US; rv:1.0) Gecko/25250101"); // in case they check // postMethod.setFollowRedirects( true ); causes error postMethod.setParameter(SESSION_ID, sid); setResolution(postMethod, contents); setNonchangingFields(postMethod); statusCode = client.executeMethod(postMethod); if (statusCode > 300) { String resultsPage = getMethod.getURI().toString(); // page we were sent to. getMethod = new GetMethod(resultsPage); getMethod.setRequestHeader("User-Agent", "Mozilla/5.001 (windows; U; NT4.0; en-US; rv:1.0) Gecko/25250101"); // in case they check statusCode = client.executeMethod(getMethod); contents = getMethod.getResponseBodyAsString(); wp.setStatus(statusCode); wp.setWebPage(contents); } contents = postMethod.getResponseBodyAsString(); wp.setStatus(statusCode); wp.setWebPage(contents); System.out.println(); System.out.println(); System.out.println(); System.out.println(); System.out.println(contents); } catch (Exception e) { System.out.println(e); } finally { getMethod.releaseConnection(); } return wp; }
From source file:com.owncloud.android.lib.resources.users.StorePrivateKeyOperation.java
/** * @param client Client object/*from w w w. j a v a 2 s. c o m*/ */ @Override protected RemoteOperationResult run(OwnCloudClient client) { PostMethod postMethod = null; RemoteOperationResult result; try { // remote request postMethod = new PostMethod(client.getBaseUri() + PRIVATE_KEY_URL + JSON_FORMAT); postMethod.addRequestHeader(OCS_API_HEADER, OCS_API_HEADER_VALUE); postMethod.setParameter(PRIVATE_KEY, privateKey); int status = client.executeMethod(postMethod, SYNC_READ_TIMEOUT, SYNC_CONNECTION_TIMEOUT); if (status == HttpStatus.SC_OK) { String response = postMethod.getResponseBodyAsString(); // Parse the response JSONObject respJSON = new JSONObject(response); String key = (String) respJSON.getJSONObject(NODE_OCS).getJSONObject(NODE_DATA) .get(NODE_PRIVATE_KEY); result = new RemoteOperationResult(true, postMethod); ArrayList<Object> keys = new ArrayList<>(); keys.add(key); result.setData(keys); } else { result = new RemoteOperationResult(false, postMethod); client.exhaustResponse(postMethod.getResponseBodyAsStream()); } } catch (Exception e) { result = new RemoteOperationResult(e); Log_OC.e(TAG, "Storing private key failed: " + result.getLogMessage(), result.getException()); } finally { if (postMethod != null) postMethod.releaseConnection(); } return result; }
From source file:es.carebear.rightmanagement.client.RestClient.java
public User logInTest(String username, String password) throws IOException { HttpClient client = new HttpClient(); PostMethod method = new PostMethod(getServiceBaseURI() + "/client/users/login/" + username); method.addParameter("password", password); System.out.println(method.getPath()); int responseCode = client.executeMethod(method); String response = responseToString(method.getResponseBodyAsStream()); System.out.println(response); return XMLHelper.fromXML(response, User.class); }
From source file:net.sourceforge.jwbf.actions.mw.editing.FileUpload.java
/** * /*from ww w . j a v a2s .c o m*/ * @param a the * @param tab internal value set * @param login a * @throws ActionException on problems with file */ public FileUpload(final SimpleFile a, final Hashtable<String, String> tab, LoginData login) throws ActionException { if (!a.getFile().isFile() || !a.getFile().canRead()) { throw new ActionException("no such file " + a.getFile()); } String uS = ""; // try { uS = "/Spezial:Hochladen"; uS = "/index.php?title=Special:Upload"; // uS = "/index.php?title=" + URLEncoder.encode("Spezial:Hochladen", // MediaWikiBot.CHARSET); // + "&action=submit"; // } catch (UnsupportedEncodingException e) { // e.printStackTrace(); // } try { LOG.info("WRITE: " + a.getLabel()); PostMethod post = new PostMethod(uS); Part[] parts; if (a.getText().isEmpty()) { parts = new Part[] { new StringPart("wpDestFile", a.getLabel()), new StringPart("wpIgnoreWarning", "true"), new StringPart("wpSourceType", "file"), new StringPart("wpUpload", "Upload file"), // new StringPart("wpUploadDescription", "false"), // new StringPart("wpWatchthis", "false"), new FilePart("wpUploadFile", a.getFile()) // new FilePart( f.getName(), f) }; } else { parts = new Part[] { new StringPart("wpDestFile", a.getLabel()), new StringPart("wpIgnoreWarning", "true"), new StringPart("wpSourceType", "file"), new StringPart("wpUpload", "Upload file"), // new StringPart("wpUploadDescription", "false"), // new StringPart("wpWatchthis", "false"), new FilePart("wpUploadFile", a.getFile()), // new FilePart( f.getName(), f) new StringPart("wpUploadDescription", a.getText()) }; } post.setRequestEntity(new MultipartRequestEntity(parts, post.getParams())); // int statusCode = hc.executeMethod(post); // log(statusCode); // log(Arrays.asList(post.getResponseHeaders())); // // String res = post.getResponseBodyAsString(); // LOG.debug(res); // post.releaseConnection(); // pm.setRequestBody(new NameValuePair[] { action, wpStarttime, // wpEditToken, wpEdittime, wpTextbox, wpSummary, wpMinoredit }); msgs.add(post); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
From source file:de.mpg.escidoc.services.framework.AdminHelper.java
/** * Logs in the given user with the given password. * /*from w w w. j a v a 2 s . co m*/ * @param userid The id of the user to log in. * @param password The password of the user to log in. * @return The handle for the logged in user. * @throws HttpException * @throws IOException * @throws ServiceException * @throws URISyntaxException */ public static String loginUser(String userid, String password) throws HttpException, IOException, ServiceException, URISyntaxException { String frameworkUrl = ServiceLocator.getLoginUrl(); int delim1 = frameworkUrl.indexOf("//"); int delim2 = frameworkUrl.indexOf(":", delim1); String host; int port; if (delim2 > 0) { host = frameworkUrl.substring(delim1 + 2, delim2); port = Integer.parseInt(frameworkUrl.substring(delim2 + 1)); } else { host = frameworkUrl.substring(delim1 + 2); port = 80; } HttpClient client = new HttpClient(); client.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY); PostMethod login = new PostMethod(frameworkUrl + "/aa/j_spring_security_check"); login.addParameter("j_username", userid); login.addParameter("j_password", password); ProxyHelper.executeMethod(client, login); login.releaseConnection(); CookieSpec cookiespec = CookiePolicy.getDefaultSpec(); Cookie[] logoncookies = cookiespec.match(host, port, "/", false, client.getState().getCookies()); Cookie sessionCookie = logoncookies[0]; PostMethod postMethod = new PostMethod(frameworkUrl + "/aa/login"); postMethod.addParameter("target", frameworkUrl); client.getState().addCookie(sessionCookie); ProxyHelper.executeMethod(client, postMethod); if (HttpServletResponse.SC_SEE_OTHER != postMethod.getStatusCode()) { throw new HttpException("Wrong status code: " + login.getStatusCode()); } String userHandle = null; Header headers[] = postMethod.getResponseHeaders(); for (int i = 0; i < headers.length; ++i) { if ("Location".equals(headers[i].getName())) { String location = headers[i].getValue(); int index = location.indexOf('='); userHandle = new String(Base64.decode(location.substring(index + 1, location.length()))); //System.out.println("location: "+location); //System.out.println("handle: "+userHandle); } } if (userHandle == null) { throw new ServiceException("User not logged in."); } return userHandle; }
From source file:apm.common.utils.HttpTookit.java
/** * HTTP POST?HTML/*from w w w. jav a 2 s. com*/ * * @param url * URL? * @param params * ?,?null * @param charset * * @param pretty * ? * @return ?HTML */ public static String doPost(String url, Map<String, String> params, String charset, boolean pretty) { StringBuffer response = new StringBuffer(); HttpClient client = new HttpClient(); HttpMethod method = new PostMethod(url); // Http Post? if (params != null) { HttpMethodParams p = new HttpMethodParams(); for (Map.Entry<String, String> entry : params.entrySet()) { p.setParameter(entry.getKey(), entry.getValue()); } method.setParams(p); } try { client.executeMethod(method); if (method.getStatusCode() == HttpStatus.SC_OK) { BufferedReader reader = new BufferedReader( new InputStreamReader(method.getResponseBodyAsStream(), charset)); String line; while ((line = reader.readLine()) != null) { if (pretty) { response.append(line).append(System.getProperty("line.separator")); } else { response.append(line); } } reader.close(); } } catch (IOException e) { log.error("HTTP Post" + url + "??", e); } finally { method.releaseConnection(); } return response.toString(); }
From source file:com.owncloud.android.lib.resources.files.LockFileOperation.java
/** * @param client Client object//from w w w . j a v a 2s . c o m */ @Override protected RemoteOperationResult run(OwnCloudClient client) { RemoteOperationResult result; PostMethod postMethod = null; try { postMethod = new PostMethod(client.getBaseUri() + LOCK_FILE_URL + localId + JSON_FORMAT); if (!token.isEmpty()) { postMethod.setParameter(TOKEN, token); } // remote request postMethod.addRequestHeader(OCS_API_HEADER, OCS_API_HEADER_VALUE); postMethod.addRequestHeader(CONTENT_TYPE, FORM_URLENCODED); int status = client.executeMethod(postMethod, SYNC_READ_TIMEOUT, SYNC_CONNECTION_TIMEOUT); if (status == HttpStatus.SC_OK) { String response = postMethod.getResponseBodyAsString(); // Parse the response JSONObject respJSON = new JSONObject(response); String token = (String) respJSON.getJSONObject(NODE_OCS).getJSONObject(NODE_DATA).get(NODE_TOKEN); result = new RemoteOperationResult(true, postMethod); ArrayList<Object> tokenArray = new ArrayList<>(); tokenArray.add(token); result.setData(tokenArray); } else { result = new RemoteOperationResult(false, postMethod); client.exhaustResponse(postMethod.getResponseBodyAsStream()); } } catch (Exception e) { result = new RemoteOperationResult(e); Log_OC.e(TAG, "Lock file with id " + localId + " failed: " + result.getLogMessage(), result.getException()); } finally { if (postMethod != null) postMethod.releaseConnection(); } return result; }
From source file:com.predic8.membrane.core.interceptor.rewrite.SimpleURLRewriteInterceptorIntegrationTest.java
private PostMethod getPostMethod() { PostMethod post = new PostMethod("http://localhost:8000/blz-service?wsdl"); post.setRequestEntity(new InputStreamRequestEntity(this.getClass().getResourceAsStream("/getBank.xml"))); post.setRequestHeader(Header.CONTENT_TYPE, "text/xml;charset=UTF-8"); post.setRequestHeader(Header.SOAP_ACTION, ""); return post;//w ww . ja va 2 s .c om }