Package org.apache.http.client.methods

Examples of org.apache.http.client.methods.HttpPost


    private Document doSendRequest(final Document requestDocument, final SoapAction soapAction) {
        final DefaultHttpClient client = new DefaultHttpClient();
        try {
            configureHttpClient(client);
            final HttpContext context = new BasicHttpContext();
            final HttpPost request = new HttpPost(targetURL.toURI());

            if (soapAction != null) {
                request.setHeader("SOAPAction", soapAction.getValue());
            }

            final String requestBody = toString(requestDocument);
            logger.trace("Request:\nPOST {}\n{}", targetURL, requestBody);

            final HttpEntity entity = createEntity(requestBody);
            request.setEntity(entity);

            final HttpResponse response = client.execute(request, context);

            logResponseHeaders(response);
View Full Code Here


   
    if (logger.isLoggable(Level.FINEST)) {
        logger.entering(sourceClass, "getAccessTokenForAuthorizedUsingPOST", new Object[] { });
        }
   
    HttpPost method = null;
    int responseCode = HttpStatus.SC_OK;
    String responseBody = null;
    InputStream content = null;
    try {
      HttpClient client = new DefaultHttpClient();
      if(forceTrustSSLCertificate)
        client = (DefaultHttpClient)SSLUtil.wrapHttpClient((DefaultHttpClient)client);
      StringBuffer url = new StringBuffer(2048);
     
      // This works for Smartcloud
/*      url.append(getAccessTokenURL()).append("?");
      url.append(Configuration.OAUTH2_CALLBACK_URI).append('=').append(URLEncoder.encode(client_uri, "UTF-8"));
      url.append('&');
      url.append(Configuration.OAUTH2_CLIENT_ID).append('=').append(URLEncoder.encode(consumerKey, "UTF-8"));
      url.append('&');
      url.append(Configuration.OAUTH2_CLIENT_SECRET).append('=').append(URLEncoder.encode(consumerSecret, "UTF-8"));
      url.append('&');
      url.append(Configuration.OAUTH2_GRANT_TYPE).append('=').append(Configuration.OAUTH2_AUTHORIZATION_CODE);
      url.append('&');
      url.append(Configuration.OAUTH2_CODE).append('=').append(URLEncoder.encode(authorization_code, "UTF-8"));
      System.err.println("url used here "+url);
      method = new HttpPost(url.toString());*/
     
     
      // This works for connections
      // add parameters to the post method 
      method = new HttpPost(getAccessTokenURL());
      List <NameValuePair> parameters = new ArrayList <NameValuePair>();  
      parameters.add(new BasicNameValuePair(Configuration.OAUTH2_CALLBACK_URI, URLEncoder.encode(client_uri, "UTF-8")));  
      parameters.add(new BasicNameValuePair(Configuration.OAUTH2_CLIENT_ID, URLEncoder.encode(consumerKey, "UTF-8")));  
      parameters.add(new BasicNameValuePair(Configuration.OAUTH2_CLIENT_SECRET, URLEncoder.encode(consumerSecret, "UTF-8")));  
      parameters.add(new BasicNameValuePair(Configuration.OAUTH2_GRANT_TYPE, Configuration.OAUTH2_AUTHORIZATION_CODE));  
      parameters.add(new BasicNameValuePair(Configuration.OAUTH2_CODE, URLEncoder.encode(authorization_code, "UTF-8")));  
      UrlEncodedFormEntity sendentity = new UrlEncodedFormEntity(parameters, HTTP.UTF_8)
      method.setEntity(sendentity);  
      HttpResponse httpResponse =client.execute(method);
      responseCode = httpResponse.getStatusLine().getStatusCode();
     
      if (logger.isLoggable(Level.FINEST)) {
          logger.log(Level.FINEST, "OAuth2.0 network call to fetch token :" + getAccessTokenURL(), responseCode);
View Full Code Here

      signatureParamsMap.put(Configuration.TIMESTAMP, timeStamp);
      signatureParamsMap.put(Configuration.VERSION, Configuration.OAUTH_VERSION1);

      String consumerSecret = getConsumerSecret();
      String requestPostUrl = getRequestTokenURL();
      HttpPost method = new HttpPost(requestPostUrl);
      String signature = HMACEncryptionUtility.generateHMACSignature(requestPostUrl,
          method.getMethod(), consumerSecret, "", signatureParamsMap);

      StringBuilder headerStr = new StringBuilder();
      headerStr.append("OAuth ").append(Configuration.CALLBACK).append("=\"").append(callbackUrl)
          .append("\"");
      headerStr.append(",").append(Configuration.CONSUMER_KEY).append("=\"").append(consumerKey)
          .append("\"");
      headerStr.append(",").append(Configuration.SIGNATURE_METHOD).append("=\"")
          .append(getSignatureMethod()).append("\"");
      headerStr.append(",").append(Configuration.TIMESTAMP).append("=\"").append(timeStamp)
          .append("\"");
      headerStr.append(",").append(Configuration.NONCE).append("=\"").append(nonce).append("\"");
      headerStr.append(",").append(Configuration.VERSION).append("=\"")
          .append(Configuration.OAUTH_VERSION1).append("\"");
      headerStr.append(",").append(Configuration.SIGNATURE).append("=\"")
          .append(URLEncoder.encode(signature, "UTF-8")).append("\"");
      method.setHeader("Authorization", headerStr.toString());

      HttpResponse httpResponse = client.execute(method);
      responseCode = httpResponse.getStatusLine().getStatusCode();
      InputStream content = httpResponse.getEntity().getContent();
      BufferedReader reader = new BufferedReader(new InputStreamReader(content));
View Full Code Here

      StringBuilder requestPostUrl = new StringBuilder(getAccessTokenURL());
      // adding the oauth_verifier to the request.
      requestPostUrl.append("?");
      requestPostUrl.append(Configuration.OAUTH_VERIFIER).append('=')
          .append(URLEncoder.encode(verifierCode, "UTF-8"));
      HttpPost method = new HttpPost(requestPostUrl.toString());
      // Collecting parameters for preparing the Signature
      String consumerKey = getConsumerKey();
      String requestToken = getRequestToken();
      String nonce = getNonce();
      String timeStamp = getTimestamp();
      /*
       * Generate a map of parameters which are required for creating signature. We are using a Linked
       * HashMap to preserver the order in which parameters are added to the Map, as the parameters need
       * to be sorted for Twitter Signature generation.
       */
      LinkedHashMap<String, String> signatureParamsMap = new LinkedHashMap<String, String>();
      signatureParamsMap.put(Configuration.CONSUMER_KEY, consumerKey);
      signatureParamsMap.put(Configuration.NONCE, nonce);
      signatureParamsMap.put(Configuration.OAUTH_TOKEN, requestToken);
      signatureParamsMap.put(Configuration.SIGNATURE_METHOD, getSignatureMethod());
      signatureParamsMap.put(Configuration.TIMESTAMP, timeStamp);
      signatureParamsMap.put(Configuration.VERSION, Configuration.OAUTH_VERSION1);

      String requestTokenSecret = getRequestTokenSecret();
      String consumerSecret = getConsumerSecret();
      String signature = HMACEncryptionUtility.generateHMACSignature(requestPostUrl.toString(),
          method.getMethod(), consumerSecret, requestTokenSecret, signatureParamsMap);

      // Preparing the Header for getting access token
      StringBuilder headerStr = new StringBuilder();

      headerStr.append("OAuth ").append(Configuration.CONSUMER_KEY).append("=\"").append(consumerKey)
          .append("\"");
      headerStr.append(",").append(Configuration.SIGNATURE_METHOD).append("=\"")
          .append(getSignatureMethod()).append("\"");
      headerStr.append(",").append(Configuration.TIMESTAMP).append("=\"").append(timeStamp)
          .append("\"");
      headerStr.append(",").append(Configuration.NONCE).append("=\"").append(nonce).append("\"");
      headerStr.append(",").append(Configuration.VERSION).append("=\"")
          .append(Configuration.OAUTH_VERSION1).append("\"");
      // This is the request token which is obtained from getRequestTokenFromServer() method.
      headerStr.append(",").append(Configuration.OAUTH_TOKEN).append("=\"").append(requestToken)
          .append("\"");
      headerStr.append(",").append(Configuration.SIGNATURE).append("=\"")
          .append(URLEncoder.encode(signature, "UTF-8")).append("\"");
      method.setHeader("Authorization", headerStr.toString());

      method.setHeader("Authorization", headerStr.toString());

      HttpResponse httpResponse = client.execute(method);
      responseCode = httpResponse.getStatusLine().getStatusCode();
      InputStream content = httpResponse.getEntity().getContent();
      BufferedReader reader = new BufferedReader(new InputStreamReader(content));
View Full Code Here

    // Extract request and reset buffer
    byte[] data = requestBuffer_.toByteArray();
    requestBuffer_.reset();

    HttpPost post = null;
   
    InputStream is = null;
   
    try {     
      // Set request to path + query string
      post = new HttpPost(this.url_.getFile());
     
      //
      // Headers are added to the HttpPost instance, not
      // to HttpClient.
      //
     
      post.setHeader("Content-Type", "application/x-thrift");
      post.setHeader("Accept", "application/x-thrift");
      post.setHeader("User-Agent", "Java/THttpClient/HC");
     
      if (null != customHeaders_) {
        for (Map.Entry<String, String> header : customHeaders_.entrySet()) {
          post.setHeader(header.getKey(), header.getValue());
        }
      }

      post.setEntity(new ByteArrayEntity(data));
     
      HttpResponse response = this.client.execute(this.host, post);
      int responseCode = response.getStatusLine().getStatusCode();

      //     
      // Retrieve the inputstream BEFORE checking the status code so
      // resources get freed in the finally clause.
      //

      is = response.getEntity().getContent();
     
      if (responseCode != HttpStatus.SC_OK) {
        throw new TTransportException("HTTP Response code: " + responseCode);
      }

      // Read the responses into a byte array so we can release the connection
      // early. This implies that the whole content will have to be read in
      // memory, and that momentarily we might use up twice the memory (while the
      // thrift struct is being read up the chain).
      // Proceeding differently might lead to exhaustion of connections and thus
      // to app failure.
     
      byte[] buf = new byte[1024];
      ByteArrayOutputStream baos = new ByteArrayOutputStream();
     
      int len = 0;
      do {
        len = is.read(buf);
        if (len > 0) {
          baos.write(buf, 0, len);
        }
      } while (-1 != len);
     
      try {
        // Indicate we're done with the content.
        EntityUtils.consume(response.getEntity());
      } catch (IOException ioe) {
        // We ignore this exception, it might only mean the server has no
        // keep-alive capability.
      }
           
      inputStream_ = new ByteArrayInputStream(baos.toByteArray());
    } catch (IOException ioe) {
      // Abort method so the connection gets released back to the connection manager
      if (null != post) {
        post.abort();
      }
      throw new TTransportException(ioe);
    } finally {
      if (null != is) {
        // Close the entity's input stream, this will release the underlying connection
View Full Code Here

     * @param guess
     * @return
     * @throws UnsupportedEncodingException
     */
    private static HttpUriRequest buildPostRequest(String url, String sessionId, String viewState, String guess) throws UnsupportedEncodingException {
        HttpPost post = new HttpPost(url);

        List<NameValuePair> list = new LinkedList<NameValuePair> ();

        list.add(new BasicNameValuePair("javax.faces.ViewState", viewState));
        list.add(new BasicNameValuePair("numberGuess", "numberGuess"));
        list.add(new BasicNameValuePair("numberGuess:guessButton", "Guess"));
        list.add(new BasicNameValuePair("numberGuess:inputGuess", guess));

        post.setEntity(new StringEntity(URLEncodedUtils.format(list, "UTF-8"), "application/x-www-form-urlencoded", "UTF-8"));
        if (sessionId != null) {
            post.setHeader("Cookie", "JSESSIONID=" + sessionId);
        }

        return post;
    }
View Full Code Here

                    System.out.println("- " + cookies.get(i).toString());
                }
            }

            // We should now login with the user name and password
            HttpPost httpost = new HttpPost(getURL() + "j_security_check");

            List<NameValuePair> nvps = new ArrayList<NameValuePair>();
            nvps.add(new BasicNameValuePair("j_username", user));
            nvps.add(new BasicNameValuePair("j_password", pass));

            httpost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));

            response = httpclient.execute(httpost);
            entity = response.getEntity();
            if (entity != null)
                EntityUtils.consume(entity);
View Full Code Here

                    System.out.println("- " + cookies.get(i).toString());
                }
            }
            req = url.toExternalForm() + "secured/j_security_check";
            // We should now login with the user name and password
            HttpPost httpPost = new HttpPost(req);

            List<NameValuePair> nvps = new ArrayList<NameValuePair>();
            nvps.add(new BasicNameValuePair("j_username", user));
            nvps.add(new BasicNameValuePair("j_password", pass));

            httpPost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));

            response = httpclient.execute(httpPost);
            entity = response.getEntity();
            if (entity != null)
                EntityUtils.consume(entity);
View Full Code Here

                sessionID = k.getValue();
        }
        log.info("Saw JSESSIONID=" + sessionID);

        // Submit the login form
        HttpPost formPost = new HttpPost(baseURLNoAuth + "j_security_check");
        formPost.addHeader("Referer", baseURLNoAuth + "restricted/login.html");

        List<NameValuePair> formparams = new ArrayList<NameValuePair>();
        formparams.add(new BasicNameValuePair("j_username", "baduser"));
        formparams.add(new BasicNameValuePair("j_password", "badpass"));
        formPost.setEntity(new UrlEncodedFormEntity(formparams, "UTF-8"));

        log.info("Executing request " + formPost.getRequestLine());
        HttpResponse postResponse = httpclient.execute(formPost);

        statusCode = postResponse.getStatusLine().getStatusCode();
        errorHeaders = postResponse.getHeaders("X-NoJException");
        assertTrue("Should see HTTP_OK. Got " + statusCode, statusCode == HttpURLConnection.HTTP_OK);
View Full Code Here

        assertTrue("Wrong response code: " + statusCode, statusCode == HttpURLConnection.HTTP_OK);
        assertTrue("X-NoJException(" + Arrays.toString(errorHeaders) + ") is null", errorHeaders.length == 0);
        EntityUtils.consume(response.getEntity());

        // Submit the form to /restricted/SecuredPostServlet
        HttpPost restrictedPost = new HttpPost(baseURLNoAuth + "restricted/SecuredPostServlet");

        List<NameValuePair> restrictedParams = new ArrayList<NameValuePair>();
        restrictedParams.add(new BasicNameValuePair("checkParam", "123456"));
        restrictedPost.setEntity(new UrlEncodedFormEntity(restrictedParams, "UTF-8"));

        log.info("Executing request " + restrictedPost.getRequestLine());
        HttpResponse restrictedResponse = httpclient.execute(restrictedPost);

        statusCode = restrictedResponse.getStatusLine().getStatusCode();
        errorHeaders = restrictedResponse.getHeaders("X-NoJException");
        assertTrue("Wrong response code: " + statusCode, statusCode == HttpURLConnection.HTTP_OK);
        assertTrue("X-NoJException(" + Arrays.toString(errorHeaders) + ") is null", errorHeaders.length == 0);

        HttpEntity entity = restrictedResponse.getEntity();
        if ((entity != null) && (entity.getContentLength() > 0)) {
            String body = EntityUtils.toString(entity);
            assertTrue("Redirected to login page", body.indexOf("j_security_check") > 0);
        } else {
            fail("Empty body in response");
        }

        String sessionID = null;
        for (Cookie k : httpclient.getCookieStore().getCookies()) {
            if (k.getName().equalsIgnoreCase("JSESSIONID"))
                sessionID = k.getValue();
        }
        log.info("Saw JSESSIONID=" + sessionID);

        // Submit the login form
        HttpPost formPost = new HttpPost(baseURLNoAuth + "j_security_check");
        formPost.addHeader("Referer", baseURLNoAuth + "restricted/login.html");

        List<NameValuePair> formparams = new ArrayList<NameValuePair>();
        formparams.add(new BasicNameValuePair("j_username", "user1"));
        formparams.add(new BasicNameValuePair("j_password", "password1"));
        formPost.setEntity(new UrlEncodedFormEntity(formparams, "UTF-8"));

        log.info("Executing request " + formPost.getRequestLine());
        HttpResponse postResponse = httpclient.execute(formPost);

        statusCode = postResponse.getStatusLine().getStatusCode();
        errorHeaders = postResponse.getHeaders("X-NoJException");
        assertTrue("Should see HTTP_MOVED_TEMP. Got " + statusCode, statusCode == HttpURLConnection.HTTP_MOVED_TEMP);
View Full Code Here

TOP

Related Classes of org.apache.http.client.methods.HttpPost

Copyright © 2018 www.massapicom. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.