Example usage for org.apache.http.client.methods HttpPost HttpPost

List of usage examples for org.apache.http.client.methods HttpPost HttpPost

Introduction

In this page you can find the example usage for org.apache.http.client.methods HttpPost HttpPost.

Prototype

public HttpPost(final String uri) 

Source Link

Usage

From source file:com.thed.zapi.cloud.sample.CreateTestWithTestSteps.java

public static void main(String[] args) throws JSONException, URISyntaxException, ParseException, IOException {
    final String createTestUri = API_CREATE_TEST.replace("{SERVER}", jiraBaseURL);
    final String createTestStepUri = API_CREATE_TEST_STEP.replace("{SERVER}", zephyrBaseUrl);

    /**//from   w  w  w  .  ja va 2 s  .  co  m
     * Create Test Parameters, declare Create Test Issue fields Declare more
     * field objects if required
     */

    JSONObject projectObj = new JSONObject();
    projectObj.put("id", projectId); // Project ID where the Test to be
    // Created

    JSONObject issueTypeObj = new JSONObject();
    issueTypeObj.put("id", issueTypeId); // IssueType ID which is Test isse
    // type

    JSONObject assigneeObj = new JSONObject();
    assigneeObj.put("name", userName); // Username of the assignee

    JSONObject reporterObj = new JSONObject();
    reporterObj.put("name", userName); // Username of the Reporter

    String testSummary = "Sample Test case With Steps created through ZAPI Cloud"; // Test
    // Case
    // Summary/Name

    /**
     * Create JSON payload to POST Add more field objects if required
     * 
     * ***DONOT EDIT BELOW ***
     */

    JSONObject fieldsObj = new JSONObject();
    fieldsObj.put("project", projectObj);
    fieldsObj.put("summary", testSummary);
    fieldsObj.put("issuetype", issueTypeObj);
    fieldsObj.put("assignee", assigneeObj);
    fieldsObj.put("reporter", reporterObj);

    JSONObject createTestObj = new JSONObject();
    createTestObj.put("fields", fieldsObj);
    System.out.println(createTestObj.toString());
    byte[] bytesEncoded = Base64.encodeBase64((userName + ":" + password).getBytes());
    String authorizationHeader = "Basic " + new String(bytesEncoded);
    Header header = new BasicHeader(HttpHeaders.AUTHORIZATION, authorizationHeader);

    StringEntity createTestJSON = null;
    try {
        createTestJSON = new StringEntity(createTestObj.toString());
    } catch (UnsupportedEncodingException e1) {
        e1.printStackTrace();
    }

    HttpResponse response = null;
    HttpClient restClient = new DefaultHttpClient();
    try {
        // System.out.println(issueSearchURL);
        HttpPost createTestReq = new HttpPost(createTestUri);
        createTestReq.addHeader(header);
        createTestReq.addHeader("Content-Type", "application/json");
        createTestReq.setEntity(createTestJSON);

        response = restClient.execute(createTestReq);
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    String testId = null;
    int statusCode = response.getStatusLine().getStatusCode();
    // System.out.println(statusCode);
    HttpEntity entity1 = response.getEntity();
    if (statusCode >= 200 && statusCode < 300) {

        String string1 = null;
        try {
            string1 = EntityUtils.toString(entity1);
            System.out.println(string1);
        } catch (ParseException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        JSONObject createTestResp = new JSONObject(string1);
        testId = createTestResp.getString("id");
        System.out.println("testId :" + testId);
    } else {

        try {
            String string = null;
            string = EntityUtils.toString(entity1);
            JSONObject executionResponseObj = new JSONObject(string);
            System.out.println(executionResponseObj.toString());
            throw new ClientProtocolException("Unexpected response status: " + statusCode);

        } catch (ClientProtocolException e) {
            e.printStackTrace();
        }
    }

    /** Create test Steps ***/

    /**
     * Create Steps Replace the step,data,result values as required
     */

    JSONObject testStepJsonObj = new JSONObject();
    testStepJsonObj.put("step", "Sample Test Step");
    testStepJsonObj.put("data", "Sample Test Data");
    testStepJsonObj.put("result", "Sample Expected Result");

    /** DONOT EDIT FROM HERE ***/

    StringEntity createTestStepJSON = null;
    try {
        createTestStepJSON = new StringEntity(testStepJsonObj.toString());
    } catch (UnsupportedEncodingException e1) {
        e1.printStackTrace();
    }
    String finalURL = createTestStepUri + testId + "?projectId=" + projectId;
    URI uri = new URI(finalURL);
    int expirationInSec = 360;
    JwtGenerator jwtGenerator = client.getJwtGenerator();
    String jwt = jwtGenerator.generateJWT("POST", uri, expirationInSec);
    System.out.println(uri.toString());
    System.out.println(jwt);

    HttpResponse responseTestStep = null;

    HttpPost addTestStepReq = new HttpPost(uri);
    addTestStepReq.addHeader("Content-Type", "application/json");
    addTestStepReq.addHeader("Authorization", jwt);
    addTestStepReq.addHeader("zapiAccessKey", accessKey);
    addTestStepReq.setEntity(createTestStepJSON);

    try {
        responseTestStep = restClient.execute(addTestStepReq);
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    int testStepStatusCode = responseTestStep.getStatusLine().getStatusCode();
    System.out.println(testStepStatusCode);
    System.out.println(response.toString());

    if (statusCode >= 200 && statusCode < 300) {
        HttpEntity entity = responseTestStep.getEntity();
        String string = null;
        String stepId = null;
        try {
            string = EntityUtils.toString(entity);
            JSONObject testStepObj = new JSONObject(string);
            stepId = testStepObj.getString("id");
            System.out.println("stepId :" + stepId);
            System.out.println(testStepObj.toString());
        } catch (ParseException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    } else {
        try {
            throw new ClientProtocolException("Unexpected response status: " + statusCode);
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        }
    }

}

From source file:CourserankConnector.java

public static void main(String[] args) throws Exception {
    ///////////////////////////////////////
    //Tagger init

    //MaxentTagger tagger = new MaxentTagger("models/english-left3words-distsim.tagger");
    ////*from ww w  . java  2  s  . c  o  m*/
    //CLIENT INITIALIZATION
    ImportData importCourse = new ImportData();
    HttpClient httpclient = new DefaultHttpClient();
    httpclient = WebClientDevWrapper.wrapClient(httpclient);
    try {
        /*
         httpclient.getCredentialsProvider().setCredentials(
            new AuthScope(null, -1),
            new UsernamePasswordCredentials("eadrian", "eactresp1"));
        */
        //////////////////////////////////////////////////
        //Get Course Bulletin Departments page
        List<Course> courses = new ArrayList<Course>();

        HttpGet httpget = new HttpGet("http://explorecourses.stanford.edu");

        System.out.println("executing request" + httpget.getRequestLine());
        HttpResponse response = httpclient.execute(httpget);
        HttpEntity entity = response.getEntity();

        System.out.println("----------------------------------------");
        System.out.println(response.getStatusLine());
        String bulletinpage = "";

        //STORE RETURNED HTML TO BULLETINPAGE

        if (entity != null) {
            //System.out.println("Response content length: " + entity.getContentLength());
            InputStream i = entity.getContent();
            BufferedReader br = new BufferedReader(new InputStreamReader(i));
            String line;
            while ((line = br.readLine()) != null) {
                bulletinpage += line;
                //System.out.println(line);
            }
            br.close();
            i.close();
        }
        EntityUtils.consume(entity);

        ///////////////////////////////////////////////////////////////////////////////
        //Login to Courserank

        httpget = new HttpGet("https://courserank.com/stanford/main");

        System.out.println("executing request" + httpget.getRequestLine());
        response = httpclient.execute(httpget);
        entity = response.getEntity();

        System.out.println("----------------------------------------");
        System.out.println(response.getStatusLine());
        String page = "";
        if (entity != null) {
            System.out.println("Response content length: " + entity.getContentLength());
            InputStream i = entity.getContent();
            BufferedReader br = new BufferedReader(new InputStreamReader(i));
            String line;
            while ((line = br.readLine()) != null) {
                page += line;
                //System.out.println(line);
            }
            br.close();
            i.close();
        }
        EntityUtils.consume(entity);
        ////////////////////////////////////////////////////
        //POST REQUEST LOGIN

        HttpPost post = new HttpPost("https://www.courserank.com/stanford/main");

        List<NameValuePair> pairs = new ArrayList<NameValuePair>(2);

        pairs.add(new BasicNameValuePair("RT", ""));
        pairs.add(new BasicNameValuePair("action", "login"));
        pairs.add(new BasicNameValuePair("password", "trespass"));
        pairs.add(new BasicNameValuePair("username", "eaconte@stanford.edu"));
        post.setEntity(new UrlEncodedFormEntity(pairs));
        System.out.println("executing request" + post.getRequestLine());
        HttpResponse resp = httpclient.execute(post);
        HttpEntity ent = resp.getEntity();

        System.out.println("----------------------------------------");
        if (ent != null) {
            System.out.println("Response content length: " + ent.getContentLength());
            InputStream i = ent.getContent();
            BufferedReader br = new BufferedReader(new InputStreamReader(i));
            String line;
            while ((line = br.readLine()) != null) {
                //System.out.println(line);
            }
            br.close();
            i.close();
        }
        EntityUtils.consume(ent);
        ///////////////////////////////////////////////////
        //THIS STEP MAY NOT BE NEEDED BUT GETS MAIN PROFILE PAGE

        HttpGet gethome = new HttpGet("https://www.courserank.com/stanford/home");

        System.out.println("executing request" + gethome.getRequestLine());
        HttpResponse gresp = httpclient.execute(gethome);
        HttpEntity gent = gresp.getEntity();

        System.out.println("----------------------------------------");
        if (ent != null) {
            System.out.println("Response content length: " + gent.getContentLength());
            InputStream i = gent.getContent();
            BufferedReader br = new BufferedReader(new InputStreamReader(i));
            String line;
            while ((line = br.readLine()) != null) {
                //System.out.println(line);
            }
            br.close();
            i.close();
        }

        /////////////////////////////////////////////////////////////////////////////////
        //Parse Bulletin

        String results = getToken(bulletinpage, "RESULTS HEADER", "Additional Searches");
        String[] depts = results.split("href");

        //SPLIT FOR EACH DEPARTMENT LINK, ITERATE
        boolean ready = false;
        for (int i = 1; i < depts.length; i++) {
            //EXTRACT LINK, DEPARTMENT NAME AND ABBREVIATION
            String dept = new String(depts[i]);
            String abbr = getToken(dept, "(", ")");
            String name = getToken(dept, ">", "(");
            name.trim();
            //System.out.println(tagger.tagString(name));
            String link = getToken(dept, "=\"", "\">");
            System.out.println(name + " : " + abbr + " : " + link);

            System.out.println("======================================================================");

            if (i <= 10 || i >= 127) //values to keep it to undergraduate courses. Excludes law, med, business, overseas
                continue;
            /*if (i<=46)
               continue; */ //Start at BIOHOP
            /*if (abbr.equals("INTNLREL"))
               ready = true;
            if (!ready)
               continue;*/
            //Construct department course search URL
            //Then request page
            String URL = "http://explorecourses.stanford.edu/" + link
                    + "&filter-term-Autumn=on&filter-term-Winter=on&filter-term-Spring=on";
            httpget = new HttpGet(URL);

            //System.out.println("executing request" + httpget.getRequestLine());
            response = httpclient.execute(httpget);
            entity = response.getEntity();

            //ystem.out.println("----------------------------------------");
            //System.out.println(response.getStatusLine());
            String rpage = "";
            if (entity != null) {
                //System.out.println("Response content length: " + entity.getContentLength());
                InputStream in = entity.getContent();
                BufferedReader br = new BufferedReader(new InputStreamReader(in));
                String line;
                while ((line = br.readLine()) != null) {
                    rpage += line;
                    //System.out.println(line);
                }
                br.close();
                in.close();
            }
            EntityUtils.consume(entity);

            //Process results page
            List<Course> deptCourses = new ArrayList<Course>();
            List<Course> result = processResultPage(rpage);
            deptCourses.addAll(result);

            //While there are more result pages, keep going
            boolean more = (!(result.size() == 0) && (result.get((result.size() - 1)).courseNumber < 299));
            boolean morepages = anotherPage(rpage);
            while (morepages && more) {
                URL = nextURL(URL);
                httpget = new HttpGet(URL);

                //System.out.println("executing request" + httpget.getRequestLine());
                response = httpclient.execute(httpget);
                entity = response.getEntity();

                //System.out.println("----------------------------------------");
                //System.out.println(response.getStatusLine());
                rpage = "";
                if (entity != null) {
                    //System.out.println("Response content length: " + entity.getContentLength());
                    InputStream in = entity.getContent();
                    BufferedReader br = new BufferedReader(new InputStreamReader(in));
                    String line;
                    while ((line = br.readLine()) != null) {
                        rpage += line;
                        //System.out.println(line);
                    }
                    br.close();
                    in.close();
                }
                EntityUtils.consume(entity);
                morepages = anotherPage(rpage);
                result = processResultPage(rpage);
                deptCourses.addAll(result);
                more = (!(result.size() == 0) && (result.get((result.size() - 1)).courseNumber < 299));
                /*String mores = more? "yes": "no";
                String pagess = morepages?"yes":"no";
                System.out.println("more: "+mores+" morepages: "+pagess);
                System.out.println("more");*/
            }

            //Get course ratings for all department courses via courserank
            deptCourses = getRatings(httpclient, abbr, deptCourses);
            for (int j = 0; j < deptCourses.size(); j++) {
                Course c = deptCourses.get(j);
                System.out.println("" + c.title + " : " + c.rating);
                c.tags = name;
                c.code = c.code.trim();
                c.department = name;
                c.deptAB = abbr;
                c.writeToDatabase();
                //System.out.println(tagger.tagString(c.title));
            }

        }

        if (!page.equals(""))
            return;

        ///////////////////////////////////////////////////
        //Get Course Bulletin Department courses 

        /*
                
         httpget = new HttpGet("https://courserank.com/stanford/main");
                
         System.out.println("executing request" + httpget.getRequestLine());
         response = httpclient.execute(httpget);
         entity = response.getEntity();
                
         System.out.println("----------------------------------------");
         System.out.println(response.getStatusLine());
         page = "";
         if (entity != null) {
        System.out.println("Response content length: " + entity.getContentLength());
        InputStream i = entity.getContent();
        BufferedReader br = new BufferedReader(new InputStreamReader(i));
        String line;
        while ((line = br.readLine()) != null) {
           page +=line;
           //System.out.println(line);
        }
        br.close();
        i.close();
         }
         EntityUtils.consume(entity);
         ////////////////////////////////////////////////////
         //POST REQUEST LOGIN
                 
                 
         HttpPost post = new HttpPost("https://www.courserank.com/stanford/main");
                 
         List<NameValuePair> pairs = new ArrayList<NameValuePair>(2);
                 
                 
         pairs.add(new BasicNameValuePair("RT", ""));
         pairs.add(new BasicNameValuePair("action", "login"));
         pairs.add(new BasicNameValuePair("password", "trespass"));
         pairs.add(new BasicNameValuePair("username", "eaconte@stanford.edu"));
         post.setEntity(new UrlEncodedFormEntity(pairs));
         System.out.println("executing request" + post.getRequestLine());
         HttpResponse resp = httpclient.execute(post);
         HttpEntity ent = resp.getEntity();
                 
         System.out.println("----------------------------------------");
         if (ent != null) {
        System.out.println("Response content length: " + ent.getContentLength());
        InputStream i = ent.getContent();
        BufferedReader br = new BufferedReader(new InputStreamReader(i));
        String line;
        while ((line = br.readLine()) != null) {
           //System.out.println(line);
        }
        br.close();
        i.close();
         }
         EntityUtils.consume(ent);
         ///////////////////////////////////////////////////
         //THIS STEP MAY NOT BE NEEDED BUT GETS MAIN PROFILE PAGE
                 
         HttpGet gethome = new HttpGet("https://www.courserank.com/stanford/home");
                 
                 
         System.out.println("executing request" + gethome.getRequestLine());
         HttpResponse gresp = httpclient.execute(gethome);
         HttpEntity gent = gresp.getEntity();
                 
         System.out.println("----------------------------------------");
         if (ent != null) {
        System.out.println("Response content length: " + gent.getContentLength());
        InputStream i = gent.getContent();
        BufferedReader br = new BufferedReader(new InputStreamReader(i));
        String line;
        while ((line = br.readLine()) != null) {
           //System.out.println(line);
        }
        br.close();
        i.close();
         }
                 
                 
         ////////////////////////////////////////
         //GETS FIRST PAGE OF RESULTS
         EntityUtils.consume(gent);
                 
         post = new HttpPost("https://www.courserank.com/stanford/search_results");
                 
         pairs = new ArrayList<NameValuePair>(2);
                 
                 
         pairs.add(new BasicNameValuePair("filter_term_currentYear", "on"));
         pairs.add(new BasicNameValuePair("query", ""));
         post.setEntity(new UrlEncodedFormEntity(pairs));
         System.out.println("executing request" + post.getRequestLine());
         resp = httpclient.execute(post);
         ent = resp.getEntity();
                 
         System.out.println("----------------------------------------");
                 
         String rpage = "";
         if (ent != null) {
        System.out.println("Response content length: " + ent.getContentLength());
        InputStream i = ent.getContent();
        BufferedReader br = new BufferedReader(new InputStreamReader(i));
        String line;
        while ((line = br.readLine()) != null) {
           rpage += line;
           System.out.println(line);
        }
        br.close();
        i.close();
         }
         EntityUtils.consume(ent);
                 
         ////////////////////////////////////////////////////
         //PARSE FIRST PAGE OF RESULTS
                 
         //int index = rpage.indexOf("div class=\"searchItem");
         String []classSplit = rpage.split("div class=\"searchItem");
         for (int i=1; i<classSplit.length; i++) {
            String str = classSplit[i];
                    
            //ID
            String CID = getToken(str, "course?id=","\">");
                    
            // CODE 
            String CODE = getToken(str,"class=\"code\">" ,":</");
                    
            //TITLE 
            String NAME = getToken(str, "class=\"title\">","</");
                    
            //DESCRIP
            String DES = getToken(str, "class=\"description\">","</");
                    
            //TERM
            String TERM = getToken(str, "Terms:", "|");
                    
            //UNITS
            String UNITS = getToken(str, "Units:", "<br/>");
                
            //WORKLOAD
                    
            String WLOAD = getToken(str, "Workload:", "|");
                    
            //GER
            String GER = getToken(str, "GERs:", "</d");
                    
            //RATING
            int searchIndex = 0;
            float rating = 0;
            while (true) {
          int ratingIndex = str.indexOf("large_Full", searchIndex);
          if (ratingIndex ==-1) {
             int halfratingIndex = str.indexOf("large_Half", searchIndex);
             if (halfratingIndex == -1)
                break;
             else
                rating += .5;
             break;
          }
          searchIndex = ratingIndex+1;
          rating++;
                     
            }
            String RATING = ""+rating;
                    
            //GRADE
            String GRADE = getToken(str, "div class=\"unofficialGrade\">", "</");
            if (GRADE.equals("NOT FOUND")) {
          GRADE = getToken(str, "div class=\"officialGrade\">", "</");
            }
                    
            //REVIEWS
            String REVIEWS = getToken(str, "class=\"ratings\">", " ratings");
                    
                    
            System.out.println(""+CODE+" : "+NAME + " : "+CID);
            System.out.println("----------------------------------------");
            System.out.println("Term: "+TERM+" Units: "+UNITS+ " Workload: "+WLOAD + " Grade: "+ GRADE);
            System.out.println("Rating: "+RATING+ " Reviews: "+REVIEWS);
            System.out.println("==========================================");
            System.out.println(DES);
            System.out.println("==========================================");
                    
                    
                    
         }
                 
                 
         ///////////////////////////////////////////////////
         //GETS SECOND PAGE OF RESULTS
         post = new HttpPost("https://www.courserank.com/stanford/search_results");
                 
         pairs = new ArrayList<NameValuePair>(2);
                 
                 
         pairs.add(new BasicNameValuePair("filter_term_currentYear", "on"));
         pairs.add(new BasicNameValuePair("page", "2"));
         pairs.add(new BasicNameValuePair("query", ""));
         post.setEntity(new UrlEncodedFormEntity(pairs));
         System.out.println("executing request" + post.getRequestLine());
         resp = httpclient.execute(post);
         ent = resp.getEntity();
                 
         System.out.println("----------------------------------------");
         if (ent != null) {
        System.out.println("Response content length: " + ent.getContentLength());
        InputStream i = ent.getContent();
        BufferedReader br = new BufferedReader(new InputStreamReader(i));
        String line;
        while ((line = br.readLine()) != null) {
           //System.out.println(line);
        }
        br.close();
        i.close();
         }
         EntityUtils.consume(ent);
                 
         /*
         httpget = new HttpGet("https://github.com/");
                
         System.out.println("executing request" + httpget.getRequestLine());
         response = httpclient.execute(httpget);
         entity = response.getEntity();
                
         System.out.println("----------------------------------------");
         System.out.println(response.getStatusLine());
         page = "";
         if (entity != null) {
        System.out.println("Response content length: " + entity.getContentLength());
        InputStream i = entity.getContent();
        BufferedReader br = new BufferedReader(new InputStreamReader(i));
        String line;
        while ((line = br.readLine()) != null) {
           page +=line;
           System.out.println(line);
        }
        br.close();
        i.close();
         }*/
        EntityUtils.consume(entity);

    } finally {
        // When HttpClient instance is no longer needed,
        // shut down the connection manager to ensure
        // immediate deallocation of all system resources
        httpclient.getConnectionManager().shutdown();
    }
}

From source file:simauthenticator.SimAuthenticator.java

/**
 * @param args the command line arguments
 *//*from  ww w .  ja v a2  s. c o m*/
public static void main(String[] args) throws Exception {

    cliOpts = new Options();
    cliOpts.addOption("U", "url", true, "Connection URL");
    cliOpts.addOption("u", "user", true, "User name");
    cliOpts.addOption("p", "password", true, "User password");
    cliOpts.addOption("d", "domain", true, "Domain name");
    cliOpts.addOption("v", "verbose", false, "Verbose output");
    cliOpts.addOption("k", "keystore", true, "KeyStore path");
    cliOpts.addOption("K", "keystorepass", true, "KeyStore password");
    cliOpts.addOption("h", "help", false, "Print help info");

    CommandLineParser clip = new GnuParser();
    cmd = clip.parse(cliOpts, args);

    if (cmd.hasOption("help")) {
        help();
        return;
    } else {
        boolean valid = init(args);
        if (!valid) {
            return;
        }
    }

    HttpClientContext clientContext = HttpClientContext.create();

    KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
    char[] keystorePassword = passwk.toCharArray();
    FileInputStream kfis = null;
    try {
        kfis = new FileInputStream(keyStorePath);
        ks.load(kfis, keystorePassword);
    } finally {
        if (kfis != null) {
            kfis.close();
        }
    }

    SSLContext sslContext = SSLContexts.custom().useSSL().loadTrustMaterial(ks).build();
    SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext);

    HttpClientBuilder httpClientBuilder = HttpClientBuilder.create().setSslcontext(sslContext)
            .setSSLSocketFactory(sslsf).setUserAgent(userAgent);
    ;

    cookieStore = new BasicCookieStore();
    /* BasicClientCookie cookie = new BasicClientCookie("SIM authenticator", "Utility for getting event details");
     cookie.setVersion(0);
     cookie.setDomain(".astelit.ukr");
     cookie.setPath("/");
     cookieStore.addCookie(cookie);*/

    CloseableHttpClient client = httpClientBuilder.build();

    try {

        NTCredentials creds = new NTCredentials(usern, passwu, InetAddress.getLocalHost().getHostName(),
                domain);
        CredentialsProvider credsProvider = new BasicCredentialsProvider();
        credsProvider.setCredentials(AuthScope.ANY, creds);
        HttpClientContext context = HttpClientContext.create();
        context.setCredentialsProvider(credsProvider);
        context.setCookieStore(cookieStore);
        HttpGet httpget = new HttpGet(eventUrl);
        if (verbose) {
            System.out.println("executing request " + httpget.getRequestLine());
        }
        HttpResponse response = client.execute(httpget, context);
        HttpEntity entity = response.getEntity();

        HttpPost httppost = new HttpPost(eventUrl);
        List<Cookie> cookies = cookieStore.getCookies();

        if (verbose) {
            System.out.println("----------------------------------------------");
            System.out.println(response.getStatusLine());
            System.out.print("Initial set of cookies: ");
            if (cookies.isEmpty()) {
                System.out.println("none");
            } else {
                for (int i = 0; i < cookies.size(); i++) {
                    System.out.println("- " + cookies.get(i).toString());
                }
            }
        }

        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        nvps.add(new BasicNameValuePair("usernameInput", usern));
        nvps.add(new BasicNameValuePair("passwordInput", passwu));
        nvps.add(new BasicNameValuePair("domainInput", domain));
        //nvps.add(new BasicNameValuePair("j_username", domain + "\\" + usern));
        //nvps.add(new BasicNameValuePair("j_password", ipAddr + ";" + passwu));
        if (entity != null && verbose) {
            System.out.println("Responce content length: " + entity.getContentLength());

        }

        //System.out.println(EntityUtils.toString(entity));

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

        HttpResponse afterPostResponse = client.execute(httppost, context);
        HttpEntity afterPostEntity = afterPostResponse.getEntity();
        cookies = cookieStore.getCookies();
        if (entity != null && verbose) {
            System.out.println("----------------------------------------------");
            System.out.println(afterPostResponse.getStatusLine());
            System.out.println("Responce content length: " + afterPostEntity.getContentLength());
            System.out.print("After POST set of cookies: ");
            if (cookies.isEmpty()) {
                System.out.println("none");
            } else {
                for (int i = 0; i < cookies.size(); i++) {
                    System.out.println("- " + cookies.get(i).toString());
                }
            }
        }

        System.out.println(EntityUtils.toString(afterPostEntity));
        EntityUtils.consume(entity);
        EntityUtils.consume(afterPostEntity);

    } finally {

        client.getConnectionManager().shutdown();
    }

}

From source file:com.cloudhopper.httpclient.util.HttpPostMain.java

static public void main(String[] args) throws Exception {
    ////from  ww  w  . j a  v a  2  s  .  co m
    // target urls
    //
    String strURL = "http://209.226.31.233:9009/SendSmsService/b98183b99a1f473839ce569c78b84dbd";

    // Username: Twitter
    // Password: Twitter123

    TrustManager easyTrustManager = new X509TrustManager() {
        public void checkClientTrusted(java.security.cert.X509Certificate[] arg0, String arg1)
                throws CertificateException {
            // allow all
        }

        public void checkServerTrusted(java.security.cert.X509Certificate[] arg0, String arg1)
                throws CertificateException {
            // allow all
        }

        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
            return null;
        }
    };

    Scheme http = new Scheme("http", PlainSocketFactory.getSocketFactory(), 80);

    SSLContext sslcontext = SSLContext.getInstance("TLS");
    sslcontext.init(null, new TrustManager[] { easyTrustManager }, null);
    SSLSocketFactory sf = new SSLSocketFactory(sslcontext);
    sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
    Scheme https = new Scheme("https", sf, 443);

    //SchemeRegistry sr = new SchemeRegistry();
    //sr.register(http);
    //sr.register(https);

    // create and initialize scheme registry
    //SchemeRegistry schemeRegistry = new SchemeRegistry();
    //schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));

    // create an HttpClient with the ThreadSafeClientConnManager.
    // This connection manager must be used if more than one thread will
    // be using the HttpClient.
    //ThreadSafeClientConnManager cm = new ThreadSafeClientConnManager(schemeRegistry);
    //cm.setMaxTotalConnections(1);

    DefaultHttpClient client = new DefaultHttpClient();

    client.getConnectionManager().getSchemeRegistry().register(https);

    //        for (int i = 0; i < 1; i++) {
    //
    // create a new ticket id
    //
    //String ticketId = TicketUtil.generate(1, System.currentTimeMillis());

    /**
    StringBuilder string0 = new StringBuilder(200)
        .append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n")
        .append("<S:Envelope xmlns:S=\"http://schemas.xmlsoap.org/soap/envelope/\">\n")
        .append("       <S:Header>\n")
        .append("               <ns3:TransactionID xmlns:ns4=\"http://vmp.vzw.com/schema\"\n")
        .append("xmlns:ns3=\"http://www.3gpp.org/ftp/Specs/archive/23_series/23.140/schema/REL-6-MM7-1-4\">" + ticketId + "</ns3:TransactionID>\n")
        .append("       </S:Header>\n")
        .append("       <S:Body>\n")
        .append("               <ns2:OptinReq xmlns:ns4=\"http://schemas.xmlsoap.org/soap/envelope/\"\n")
        .append("xmlns:ns3=\"http://www.3gpp.org/ftp/Specs/archive/23_series/23.140/schema/REL-6-MM7-1-4\"\n")
        .append("xmlns:ns2=\"http://vmp.vzw.com/schema\">\n")
        .append("                      <ns2:VASPID>twitter</ns2:VASPID>\n")
        .append("                      <ns2:VASID>tm33t!</ns2:VASID>\n")
        .append("                      <ns2:ShortCode>800080008001</ns2:ShortCode>\n")
        .append("                      <ns2:Number>9257089093</ns2:Number>\n")
        .append("                      <ns2:Source>provider</ns2:Source>\n")
        .append("                      <ns2:Message/>\n")
        .append("               </ns2:OptinReq>\n")
        .append("       </S:Body>\n")
        .append("</S:Envelope>");
     */

    // simple send sms
    StringBuilder string1 = new StringBuilder(200).append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n")
            .append("<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:loc=\"http://www.csapi.org/schema/parlayx/sms/send/v2_3/local\">\n")
            .append("   <soapenv:Header/>\n").append("   <soapenv:Body>\n").append("      <loc:sendSms>\n")
            .append("         <loc:addresses>tel:+16472260233</loc:addresses>\n")
            .append("         <loc:senderName>6388</loc:senderName>\n")
            .append("         <loc:message>Test Message &</loc:message>\n").append("      </loc:sendSms>\n")
            .append("   </soapenv:Body>\n").append("</soapenv:Envelope>\n");

    // startSmsNotification - place to deliver SMS to

    String req = string1.toString();
    logger.debug("Request XML -> \n" + req);

    HttpPost post = new HttpPost(strURL);

    StringEntity postEntity = new StringEntity(req, "ISO-8859-1");
    postEntity.setContentType("text/xml; charset=\"ISO-8859-1\"");
    post.addHeader("SOAPAction", "\"\"");
    post.setEntity(postEntity);

    long start = System.currentTimeMillis();

    client.getCredentialsProvider().setCredentials(new AuthScope("209.226.31.233", AuthScope.ANY_PORT),
            new UsernamePasswordCredentials("Twitter", "Twitter123"));

    BasicHttpContext localcontext = new BasicHttpContext();

    // Generate BASIC scheme object and stick it to the local 
    // execution context
    BasicScheme basicAuth = new BasicScheme();
    localcontext.setAttribute("preemptive-auth", basicAuth);

    // Add as the first request interceptor
    client.addRequestInterceptor(new PreemptiveAuth(), 0);

    HttpResponse httpResponse = client.execute(post, localcontext);
    HttpEntity responseEntity = httpResponse.getEntity();

    //
    // was the request OK?
    //
    if (httpResponse.getStatusLine().getStatusCode() != 200) {
        logger.error("Request failed with StatusCode=" + httpResponse.getStatusLine().getStatusCode());
    }

    // get an input stream
    String responseBody = EntityUtils.toString(responseEntity);

    long stop = System.currentTimeMillis();

    logger.debug("----------------------------------------");
    logger.debug("Response took " + (stop - start) + " ms");
    logger.debug(responseBody);
    logger.debug("----------------------------------------");
    //        }

    // When HttpClient instance is no longer needed,
    // shut down the connection manager to ensure
    // immediate deallocation of all system resources
    client.getConnectionManager().shutdown();
}

From source file:Main.java

public static HttpPost getHttpPost(String url) {
    return new HttpPost(url);
}

From source file:Main.java

public static HttpPost getHttpPost(String url) {
    HttpPost request = new HttpPost(url);
    return request;
}

From source file:Main.java

/**
 * Method to initialize and prepare an HttpPost object
 * @param file/*from  w w w.  j  ava  2  s .  c o  m*/
 * @param url
 * @param chunked
 * @return HttpPost
 */
public static HttpPost prepareRequest(File file, String url, boolean chunked) {
    HttpPost post = new HttpPost(url);

    FileEntity reqEntity = new FileEntity(file, "binary/octet-stream");
    reqEntity.setContentType("binary/octet-stream");
    reqEntity.setChunked(chunked);
    post.setEntity(reqEntity);

    return post;
}

From source file:Main.java

public static String getNetPostStirng(String url) {
    HttpClient httpClient = new DefaultHttpClient();
    String data = null;//from   ww w .  ja  v a  2 s .  c om
    HttpPost httpPost = new HttpPost(url);
    try {
        HttpResponse response = httpClient.execute(httpPost);
        if (response.getStatusLine().getStatusCode() == 200) {
            data = EntityUtils.toString(response.getEntity(), "utf-8");
            //            EntityUtils.toByteArray(response.getEntity());
            //            Log.i("ll", "--->"+data);
        } else {
            return null;
        }
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return data;
}

From source file:Main.java

public static HttpResponse postJson(String path, ArrayList<NameValuePair> params) throws Exception {

    DefaultHttpClient httpClient = new DefaultHttpClient();
    HttpPost httpPost = new HttpPost(path);
    httpPost.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));

    httpPost.setHeader("Content-type", "application/x-www-form-urlencoded; charset=UTF-8");
    httpPost.setHeader("X-Requested-With", "XMLHttpRequest");

    return httpClient.execute(httpPost);
}

From source file:Main.java

public static String getJSONFromUrl(String url) {

    try {/*from ww  w  .jav  a 2  s.co m*/
        HttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(url);

        //            httpPost.setEntity(new UrlEncodedFormEntity(params));

        HttpResponse httpResponse = httpClient.execute(httpPost);
        String tempResponse = EntityUtils.toString(httpResponse.getEntity());

        return tempResponse;

    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    return "";
}