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

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

Introduction

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

Prototype

public void setEntity(final HttpEntity entity) 

Source Link

Usage

From source file:drmaas.sandbox.http.LoginTest.java

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

    //1. For SSL/*from  ww w.  j  a  va 2s  .  c  o m*/
    DefaultHttpClient base = new DefaultHttpClient();
    SSLContext ctx = SSLContext.getInstance("TLS");

    X509TrustManager tm = new X509TrustManager() {
        public void checkClientTrusted(X509Certificate[] xcs, String string) throws CertificateException {
        }

        public void checkServerTrusted(X509Certificate[] xcs, String string) throws CertificateException {
        }

        public X509Certificate[] getAcceptedIssuers() {
            return null;
        }
    };

    X509HostnameVerifier verifier = new X509HostnameVerifier() {

        @Override
        public void verify(String string, SSLSocket ssls) throws IOException {
        }

        @Override
        public void verify(String string, X509Certificate xc) throws SSLException {
        }

        @Override
        public void verify(String string, String[] strings, String[] strings1) throws SSLException {
        }

        @Override
        public boolean verify(String string, SSLSession ssls) {
            return true;
        }
    };

    ctx.init(null, new TrustManager[] { tm }, null);
    SSLSocketFactory ssf = new SSLSocketFactory(ctx, verifier);
    ClientConnectionManager ccm = base.getConnectionManager();
    SchemeRegistry sr = ccm.getSchemeRegistry();
    sr.register(new Scheme("https", 443, ssf));
    DefaultHttpClient httpclient = new DefaultHttpClient(ccm, base.getParams());
    httpclient.setRedirectStrategy(new LaxRedirectStrategy());

    try {
        HttpPost httpost;
        HttpResponse response;
        HttpEntity entity;
        List<Cookie> cookies;
        BufferedReader rd;
        String line;
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();

        //log in
        httpost = new HttpPost("myloginurl");

        nvps = new ArrayList<NameValuePair>();
        nvps.add(new BasicNameValuePair("login", "Log In"));
        nvps.add(new BasicNameValuePair("os_username", "foo"));
        nvps.add(new BasicNameValuePair("os_password", "foobar"));
        nvps.add(new BasicNameValuePair("os_cookie", "true"));
        nvps.add(new BasicNameValuePair("os_destination", ""));

        httpost.setEntity(new UrlEncodedFormEntity(nvps));
        response = httpclient.execute(httpost);
        System.out.println(response.toString());
        rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
        line = "";
        while ((line = rd.readLine()) != null) {
            System.out.println(line);
        }

    } 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:org.camunda.bpm.RestDeployment.java

public static void main(String[] args) throws IOException {
    if (args.length == 0) {
        System.err.println("No process files specified");
        System.exit(1);//from ww  w .  j a  v a 2s.c o  m
    }

    CloseableHttpClient httpClient = HttpClients.createDefault();

    HttpPost httpPost = new HttpPost("http://localhost:8080/engine-rest/deployment/create");

    StringBody deploymentName = new StringBody("myDeployment", ContentType.TEXT_PLAIN);
    StringBody enableDuplicateFiltering = new StringBody("true", ContentType.TEXT_PLAIN);
    StringBody deployChangedOnly = new StringBody("true", ContentType.TEXT_PLAIN);

    MultipartEntityBuilder builder = MultipartEntityBuilder.create().addPart("deployment-name", deploymentName)
            .addPart("enable-duplicate-filtering", enableDuplicateFiltering)
            .addPart("deploy-changed-only", deployChangedOnly);

    for (String resource : args) {
        File resourceFile = new File(resource);
        FileBody fileBody = new FileBody(resourceFile);
        builder.addPart(resourceFile.getName(), fileBody);
    }

    HttpEntity httpEntity = builder.build();
    httpPost.setEntity(httpEntity);

    HttpResponse response = httpClient.execute(httpPost);

    logResponse(response);
}

From source file:ATTHackPause.Main.java

public static void main(String[] args) throws Exception {
    CloseableHttpClient httpclient = HttpClients.createDefault();
    try {//from w  w  w  .j a  v  a  2s  . co  m
        HttpGet httpGet = new HttpGet(
                "https://api-m2x.att.com/v2/devices/ecbcc13b43417c6d9e1dc7618bbb1e6c/streams/");
        CloseableHttpResponse response1 = httpclient.execute(httpGet);
        // The underlying HTTP connection is still held by the response object
        // to allow the response content to be streamed directly from the network socket.
        // In order to ensure correct deallocation of system resources
        // the user MUST call CloseableHttpResponse#close() from a finally clause.
        // Please note that if response content is not fully consumed the underlying
        // connection cannot be safely re-used and will be shut down and discarded
        // by the connection manager.
        try {
            System.out.println(response1.getStatusLine());
            HttpEntity entity1 = response1.getEntity();
            // do something useful with the response body
            // and ensure it is fully consumed
            EntityUtils.consume(entity1);
        } finally {
            response1.close();
        }

        HttpPost httpPost = new HttpPost(
                "https://api-m2x.att.com/v2/devices/ecbcc13b43417c6d9e1dc7618bbb1e6c/streams/Distance/values");
        // List <NameValuePair> nvps = new ArrayList <NameValuePair>();
        // nvps.add(new BasicNameValuePair("value", "15"));
        // nvps.add(new BasicNameValuePair("timestamp", "2016-04-09T19:37:42+00:00"));
        // httpPost.setEntity(new UrlEncodedFormEntity(nvps));

        String jsonString = "{\"values\":[{\"value\": \"99\",\"timestamp\": \"2016-04-09T20:43:49+00:00\"}]}";
        //System.out.println("\n\njsonString: " + jsonString);
        //            JSONArray jsonArray = new JSONArray(jsonString);
        //            System.out.println("\n\njsonArray: " + jsonArray);
        StringEntity se = new StringEntity(jsonString);
        httpPost.setEntity(se);

        httpPost.setHeader("Content-type", "application/json");
        httpPost.setHeader("X-M2X-KEY", "20bfa4a4f5ed88f94d772e8389e9a6d0");
        CloseableHttpResponse response2 = httpclient.execute(httpPost);

        try {
            System.out.println(response2.getStatusLine());
            HttpEntity entity2 = response2.getEntity();
            // do something useful with the response body
            // and ensure it is fully consumed
            EntityUtils.consume(entity2);
        } finally {
            response2.close();
        }
    } finally {
        httpclient.close();
    }
}

From source file:com.music.tools.SongDBDownloader.java

public static void main(String[] args) throws Exception {
    HttpClient client = new DefaultHttpClient();

    //        HttpHost proxy = new HttpHost("localhost", 8888);
    //        client.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);

    HttpContext ctx = new BasicHttpContext();

    HttpUriRequest req = new HttpGet(
            "http://www.hooktheory.com/analysis/view/the-beatles/i-want-to-hold-your-hand");
    client.execute(req, ctx);//ww  w  .java 2  s  .  c o m
    req.abort();

    List<String> urls = getSongUrls(
            "http://www.hooktheory.com/analysis/browseSearch?sQuery=&sOrderBy=views&nResultsPerPage=525&nPage=1",
            client, ctx);
    List<List<? extends NameValuePair>> paramsList = new ArrayList<>(urls.size());
    for (String songUrl : urls) {
        paramsList.addAll(getSongParams(songUrl, client, ctx));
    }
    int i = 0;
    for (List<? extends NameValuePair> params : paramsList) {

        HttpPost request = new HttpPost("http://www.hooktheory.com/songs/getXML");

        request.setHeader("User-Agent",
                "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:15.0) Gecko/20100101 Firefox/15.0.1");
        request.setHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
        request.setHeader("Accept-Encoding", "gzip, deflate");
        request.setHeader("Accept-Language", "en,en-us;q=0.7,bg;q=0.3");
        request.setHeader("Content-Type", "application/x-www-form-urlencoded");
        request.setHeader("Origin", "http://www.hooktheory.com");
        request.setHeader("Referer",
                URLEncoder.encode("http://www.hooktheory.com/swf/DNALive Version 1.0.131.swf", "utf-8"));

        HttpEntity entity = new UrlEncodedFormEntity(params);
        request.setEntity(entity);

        try {
            HttpResponse response = client.execute(request, ctx);
            if (response.getStatusLine().getStatusCode() == 200) {
                InputStream is = response.getEntity().getContent();
                String xml = CharStreams.toString(new InputStreamReader(is));
                is.close();
                Files.write(xml, new File("c:/tmp/musicdb/" + i + ".xml"), Charset.forName("utf-8"));
            } else {
                System.out.println(response.getStatusLine());
                System.out.println(params);
            }
            i++;
            request.abort();
        } catch (Exception ex) {
            System.out.println(params);
            ex.printStackTrace();
        }
    }
}

From source file:com.gypsai.ClientFormLogin.java

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

    DefaultHttpClient httpclient = new DefaultHttpClient();
    httppostclient = new DefaultHttpClient();
    httppostclient.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BEST_MATCH);

    try {/*from ww  w .  j  a  v a2s.co m*/

        String loginUrl = "http://www.cnsfk.com/member.php?mod=logging&action=login&loginsubmit=yes&infloat=yes&lssubmit=yes";
        //String loginUrl = "http://renren.com/PLogin.do";

        String testurl = "http://www.baidu.com";
        HttpGet httpget = new HttpGet(testurl);

        HttpResponse response = httpclient.execute(httpget);
        HttpEntity entity = response.getEntity();

        //System.out.println(istostring(entity.getContent()));

        System.out.println("Login form get: " + response.getStatusLine());
        EntityUtils.consume(entity);

        System.out.println("Initial set of cookies:");
        List<Cookie> cookies = httpclient.getCookieStore().getCookies();
        if (cookies.isEmpty()) {
            System.out.println("None");
        } else {
            for (int i = 0; i < cookies.size(); i++) {
                //     System.out.println("- " + cookies.get(i).toString());
            }
        }

        HttpPost httpost = new HttpPost(loginUrl);

        String password = MD5.MD5Encode("luom1ng");
        String redirectURL = "http://www.renren.com/home";
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        nvps.add(new BasicNameValuePair("username", "gypsai@foxmail.com"));
        nvps.add(new BasicNameValuePair("password", password));
        // nvps.add(new BasicNameValuePair("origURL", redirectURL));  
        // nvps.add(new BasicNameValuePair("domain", "renren.com"));  
        //  nvps.add(new BasicNameValuePair("autoLogin", "true"));  
        //  nvps.add(new BasicNameValuePair("formName", ""));  
        //  nvps.add(new BasicNameValuePair("method", ""));  
        //  nvps.add(new BasicNameValuePair("submit", ""));  

        httpost.setEntity(new UrlEncodedFormEntity(nvps, Consts.UTF_8));
        httpost.setHeader("User-Agent",
                "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_5) AppleWebKit/537.28 (KHTML, like Gecko) Chrome/26.0.1397.2 Safari/537.28");

        //posthttpclient
        //DefaultHttpClient httppostclient = new DefaultHttpClient();

        //postheader
        Header[] pm = httpost.getAllHeaders();
        for (Header header : pm) {
            System.out.println("%%%%->" + header.toString());
        }

        //
        response = httppostclient.execute(httpost);

        EntityUtils.consume(response.getEntity());

        doget();
        //
        //

        //httppostclient.getConnectionManager().shutdown();

        //cookie
        List<Cookie> cncookies = httppostclient.getCookieStore().getCookies();
        System.out.println("Post logon cookies:");

        if (cncookies.isEmpty()) {
            System.out.println("None");
        } else {
            for (int i = 0; i < cncookies.size(); i++) {
                System.out.println("- " + cncookies.get(i).getName().toString() + "   ---->"
                        + cncookies.get(i).getValue().toString());
            }
        }

        //
        submit();

        //httpheader
        entity = response.getEntity();
        Header[] m = response.getAllHeaders();
        for (Header header : m) {
            //System.out.println("+++->"+header.toString());
        }
        //System.out.println(response.getAllHeaders());
        System.out.println(entity.getContentEncoding());

        //statusline
        System.out.println("Login form get: " + response.getStatusLine());

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

From source file:com.mycompany.mavenpost.HttpTest.java

public static void main(String args[]) throws UnsupportedEncodingException, IOException {

    System.out.println("this is a test program");
    HttpPost httppost = new HttpPost("https://app.monsum.com/api/1.0/api.php");

    // Request parameters and other properties.
    String auth = DEFAULT_USER + ":" + DEFAULT_PASS;
    byte[] encodedAuth = Base64.encodeBase64(auth.getBytes());
    String authHeader = "Basic " + new String(encodedAuth);
    //String authHeader = "Basic " +"YW5kcmVhcy5zZWZpY2hhQG1hcmtldHBsYWNlLWFuYWx5dGljcy5kZTo5MGRkYjg3NjExMWRiNjNmZDQ1YzUyMjdlNTNmZGIyYlhtMUJQQm03OHhDS1FUVm1OR1oxMHY5TVVyZkhWV3Vh";

    httppost.setHeader(HttpHeaders.AUTHORIZATION, authHeader);

    httppost.setHeader(HttpHeaders.CONTENT_TYPE, "Content-Type: application/json");

    Map<String, Object> params = new LinkedHashMap<>();
    params.put("SERVICE", "customer.get");

    JSONObject json = new JSONObject();
    json.put("SERVICE", "customer.get");

    //Map<String, Object> params2 = new LinkedHashMap<>();

    //params2.put("CUSTOMER_NUMBER","5");
    JSONObject array = new JSONObject();
    array.put("CUSTOMER_NUMBER", "2");

    json.put("FILTER", array);

    StringEntity param = new StringEntity(json.toString());
    httppost.setEntity(param);

    HttpClient client = HttpClientBuilder.create().build();
    HttpResponse response = client.execute(httppost);

    int statusCode = response.getStatusLine().getStatusCode();
    System.out.println("The status code is  " + statusCode);

    //Execute and get the response.
    HttpEntity entity = response.getEntity();

    Header[] headers = response.getAllHeaders();
    for (Header header : headers) {
        System.out.println("Key : " + header.getName() + " ,Value : " + header.getValue());
    }// ww  w  . j  a v  a2 s  .co  m
    if (entity != null) {
        String retSrc = EntityUtils.toString(entity); //Discouraged better open a stream and read the data as per Apache manual                     
        // parsing JSON
        //JSONObject result = new JSONObject(retSrc);
        Gson gson = new GsonBuilder().setPrettyPrinting().create();
        JsonParser jp = new JsonParser();
        JsonElement je = jp.parse(retSrc);
        String prettyJsonString = gson.toJson(je);
        System.out.println(prettyJsonString);
    }
    //if (entity != null) {
    //    InputStream instream = entity.getContent();
    //    try {
    //  final BufferedReader reader = new BufferedReader(
    //                    new InputStreamReader(instream));
    //            String line = null;
    //            while ((line = reader.readLine()) != null) {
    //                System.out.println(line);
    //            }
    //            reader.close();
    //    } finally {
    //        instream.close();
    //    }
    //}
}

From source file:com.http.my.ClientFormLogin.java

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

    ResponseHandler<String> responseHandler = new ResponseHandler<String>() {

        public String handleResponse(final HttpResponse response) throws ClientProtocolException, IOException {
            int status = response.getStatusLine().getStatusCode();
            System.out.println(response.getStatusLine());
            if (status >= 200 && status < 303) {
                HttpEntity entity = response.getEntity();

                return entity != null ? EntityUtils.toString(entity) : null;
            } else {
                throw new ClientProtocolException("Unexpected response status: " + status);
            }//from  ww w  . j a  v a2 s .  co m
        }

    };

    BasicCookieStore cookieStore = new BasicCookieStore();
    //        
    //        BasicClientCookie cookieJSESSIONID = new BasicClientCookie("JSESSIONID", "3FD927DC6911B719E4492E7473897FBA");
    //        cookieJSESSIONID.setVersion(0);
    //        cookieJSESSIONID.setDomain("218.75.79.230");
    //        cookieJSESSIONID.setPath("/");
    //        System.out.println("Initial set of cookies:");
    //        cookieStore.addCookie(cookieJSESSIONID);

    CloseableHttpClient httpclient = HttpClients.custom().setDefaultCookieStore(cookieStore).build();
    // HttpProtocolParams.setUserAgent(httpclient.getParams(), "Mozilla/5.0 (Windows; U; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 2.0.50727)");

    try {

        // HttpPost httpost = new HttpPost("http://localhost:8081/cring/jsp/user/userLogin.do?method=login");
        HttpPost loginpost = new HttpPost("http://134.96.41.47/ecommunications_chs/start.swe");
        //HttpGet loginGet = new HttpGet("http://134.96.41.47/ecommunications_chs/start.swe");
        // HttpGet loginGet = new HttpGet("http://www.baidu.com");
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        nvps.add(new BasicNameValuePair("SWEUserName", "nili"));
        nvps.add(new BasicNameValuePair("SWEPassword", "nili7788"));
        nvps.add(new BasicNameValuePair("SWEFo", "SWEEntryForm"));
        nvps.add(new BasicNameValuePair("SWENeedContext", "false"));
        nvps.add(new BasicNameValuePair("SWECmd", "ExecuteLogin"));
        nvps.add(new BasicNameValuePair("W", "t"));
        nvps.add(new BasicNameValuePair("SWEC", "0"));
        nvps.add(new BasicNameValuePair("SWEBID", "-1"));
        nvps.add(new BasicNameValuePair("SWETS", "1385712482625"));

        /**
         *  SWEUserName:111111
        SWEPassword:222222
        SWEFo:SWEEntryForm
        SWENeedContext:false
        SWECmd:ExecuteLogin
        W:t
        SWESPNR:
        SWESPNH:
        SWEH:
        SWEC:0
        SWEW:
        SWEBID:-1
        SWETS:1385712482625
        SWEWN:
         */
        loginpost.setEntity(new UrlEncodedFormEntity(nvps, Consts.UTF_8));
        //            CloseableHttpResponse response =  httpclient.execute(loginpost);
        // HttpEntity httpEntity =  response.getEntity();
        CloseableHttpResponse responseGet = httpclient.execute(loginpost);
        HttpEntity httpEntityGet = responseGet.getEntity();
        System.out.println("statusLine: " + responseGet.getStatusLine());
        System.out.println("ContentType: " + httpEntityGet.getContentType());
        System.out.println("ContentLength: " + httpEntityGet.getContentLength());

        //  httpEntityGet.get
        System.out.println("loginGet: " + EntityUtils.toString(httpEntityGet));
        /* try {
                
        System.out.println("Post logon cookies:");
        List<Cookie> cookies = cookieStore.getCookies();
        if (cookies.isEmpty()) {
            System.out.println("None");
        } else {
            for (int i = 0; i < cookies.size(); i++) {
                System.out.println("- " + cookies.get(i).toString());
            }
        }
                
                
                
        HttpPost modifypost = new HttpPost("http://localhost:8081/cring/jsp/user/corpUserController.do?method=modifyPwd");
        List <NameValuePair> modifynvps = new ArrayList <NameValuePair>();
        modifynvps.add(new BasicNameValuePair("newPwd","111111"));
        modifypost.setEntity(new UrlEncodedFormEntity(modifynvps, Consts.UTF_8));
                    
        CloseableHttpResponse modifyresponse = httpclient.execute(modifypost);
            System.out.println("modifyresponse : "+modifyresponse.getStatusLine()); 
                
                
                
         } finally {
        //response2.close();
         }*/
    } finally {
        httpclient.close();
    }
}

From source file:httpclient.UploadAction.java

public static void main(String[] args) throws FileNotFoundException {
    File targetFile1 = new File("F:\\2.jpg");
    // File targetFile2 = new File("F:\\1.jpg");
    FileInputStream fis1 = new FileInputStream(targetFile1);
    // FileInputStream fis2 = new FileInputStream(targetFile2);
    // String targetURL =
    // "http://static.fangbiandian.com.cn/round_server/upload/uploadFile.do";
    String targetURL = "http://www.fangbiandian.com.cn/round_server/user/updateUserInfo.do";
    HttpPost filePost = new HttpPost(targetURL);
    try {//from www.j a  va 2  s .c  o  m
        // ?????
        HttpClient client = new DefaultHttpClient();
        // FormBodyPart fbp1 = new FormBodyPart("file1", new
        // FileBody(targetFile1));
        // FormBodyPart fbp2 = new FormBodyPart("file2", new
        // FileBody(targetFile2));
        // FormBodyPart fbp3 = new FormBodyPart("file3", new
        // FileBody(targetFile3));
        // List<FormBodyPart> picList = new ArrayList<FormBodyPart>();
        // picList.add(fbp1);
        // picList.add(fbp2);
        // picList.add(fbp3);
        Map<String, Object> paramMap = new HashMap<String, Object>();
        paramMap.put("userId", "65478A5CD8D20C3807EE16CF22AF8A17");
        Map<String, Object> map = new HashMap<String, Object>();
        String jsonStr = JSON.toJSONString(paramMap);
        map.put("cid", 321);
        map.put("request", jsonStr);
        String jsonString = JSON.toJSONString(map);
        MultipartEntity multiEntity = new MultipartEntity();
        Charset charset = Charset.forName("UTF-8");
        multiEntity.addPart("request", new StringBody(jsonString, charset));
        multiEntity.addPart("photo", new InputStreamBody(fis1, "2.jpg"));
        // multiEntity.addPart("licenseUrl", new InputStreamBody(fis2,
        // "1.jpg"));
        filePost.setEntity(multiEntity);
        HttpResponse response = client.execute(filePost);
        int code = response.getStatusLine().getStatusCode();
        System.out.println(code);
        if (HttpStatus.SC_OK == code) {
            System.out.println("?");
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                InputStream instream = entity.getContent();
                try {
                    // do something useful
                    BufferedReader reader = new BufferedReader(new InputStreamReader(instream));
                    String str = null;
                    while ((str = reader.readLine()) != null) {
                        System.out.println(str);
                    }
                } finally {
                    instream.close();
                }
            }
        } else {
            System.out.println("");
        }
    } catch (Exception ex) {
        ex.printStackTrace();
    } finally {
        filePost.releaseConnection();
    }
}

From source file:simauthenticator.SimAuthenticator.java

/**
 * @param args the command line arguments
 *//*from   www  .java2 s  . co  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:org.craftercms.social.UCGRestServicesTest.java

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

    ProfileClient profileRestClient = new ProfileRestClientImpl();

    String token = profileRestClient.getAppToken("craftersocial", "craftersocial");
    Tenant tenant = profileRestClient.getTenantByName(token, "testing");
    String ticket = profileRestClient.getTicket(token, "admin", "admin", tenant.getId());
    List<NameValuePair> qparams = new ArrayList<NameValuePair>();
    qparams.add(new BasicNameValuePair("ticket", ticket));
    qparams.add(new BasicNameValuePair("target", "testing"));

    qparams.add(new BasicNameValuePair("textContent", "Content"));

    URI uri = URIUtils.createURI("http", "localhost", 8080, "crafter-social/api/1/ugc/" + "create.json",
            URLEncodedUtils.format(qparams, HTTP.UTF_8), null);

    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost(uri);
    File file = new File(
            "/Users/alvarogonzalez/development/projects/crafter-social/rest/src/test/resources/test.txt");
    MultipartEntity me = new MultipartEntity();

    //The usual form parameters can be added this way
    //me.addPart("fileDescription", new StringBody(fileDescription != null ? fileDescription : "")) ;
    //multiPartEntity.addPart("fileName", new StringBody(fileName != null ? fileName : file.getName())) ;

    /*Need to construct a FileBody with the file that needs to be attached and specify the mime type of the file. Add the fileBody to the request as an another part.
    This part will be considered as file part and the rest of them as usual form-data parts*/
    FileBody fileBody = new FileBody(file, "application/octect-stream");
    //me.addPart("ticket", new StringBody(token)) ;
    //me.addPart("target", new StringBody("my-test")) ;
    me.addPart("attachments", fileBody);

    httppost.setEntity(me);
    httpclient.execute(httppost);//  www.j av a  2  s .  c  o m

}