List of usage examples for org.apache.http.client.methods HttpPost HttpPost
public HttpPost(final String uri)
From source file:es.tsb.ltba.nomhad.example.ClientWithResponseHandler.java
public final static void main(String[] args) throws Exception { DefaultHttpClient httpclient = new DefaultHttpClient(); httpclient = wrapClient(httpclient); httpclient.getCredentialsProvider().setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT), new UsernamePasswordCredentials("A100", "123456")); try {/*from ww w . ja v a2 s .co m*/ HttpGet httpget = new HttpGet(NOMHAD_URL_HEADER + "A100" + OBSERVATIONS_REQUEST); HttpPost httppost = new HttpPost(NOMHAD_URL_HEADER + "A100" + OBSERVATIONS_REQUEST); httppost.setEntity(new StringEntity(BODY_TEST)); System.out.println("executing request " + httpget.getURI()); // Create a response handler ResponseHandler<String> responseHandler = new BasicResponseHandler(); String responseBody = httpclient.execute(httppost, responseHandler); System.out.println("----------------------------------------"); System.out.println(responseBody); System.out.println("----------------------------------------"); } 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:com.cloudhopper.sxmp.Post.java
static public void main(String[] args) throws Exception { String message = "Test With @ Character"; //String message = "Tell Twitter what you're doing!\nStd msg charges apply. Send 'stop' to quit.\nVisit twitter.com or email help@twitter.com for help."; StringBuilder string0 = new StringBuilder(200).append("<?xml version=\"1.0\"?>\n") .append("<operation type=\"submit\">\n") .append(" <account username=\"customer1\" password=\"password1\"/>\n") .append(" <submitRequest referenceId=\"MYREF102020022\">\n") .append(" <operatorId>75</operatorId>\n").append(" <deliveryReport>true</deliveryReport>\n") .append(" <sourceAddress type=\"network\">40404</sourceAddress>\n") .append(" <destinationAddress type=\"international\">+13135551234</destinationAddress>\n") .append(" <text encoding=\"ISO-8859-1\">" + HexUtil.toHexString(message.getBytes("ISO-8859-1")) + "</text>\n") .append(" </submitRequest>\n").append("</operation>\n").append(""); /**/*from w w w .j a v a 2 s . com*/ //.append("<!DOCTYPE chapter PUBLIC \"-//OASIS//DTD DocBook XML//EN\" \"../dtds/docbookx.dtd\">") //.append("<!DOCTYPE chapter PUBLIC \"-//OASIS//DTD DocBook XML//EN\">") .append("<submitRequest sequenceId=\"1000\">\n") .append(" <!-- this is a comment -->\n") .append(" <account username=\"testaccount\" password=\"testpassword\"/>\n") .append(" <option />\n") .append(" <messageRequest referenceId=\"MYMESSREF\">\n") //.append(" <sourceAddress>+13135551212</sourceAddress>\n") .append(" <destinationAddress>+13135551200</destinationAddress>\n") .append(" <text><![CDATA[Hello World]]></text>\n") .append(" </messageRequest>\n") .append("</submitRequest>") .append(""); */ // Get target URL String strURL = "http://localhost:9080/api/sxmp/1.0"; // Get file to be posted //String strXMLFilename = args[1]; //File input = new File(strXMLFilename); HttpClient client = new DefaultHttpClient(); long totalStart = System.currentTimeMillis(); for (int i = 0; i < 1; i++) { long start = System.currentTimeMillis(); // execute request try { HttpPost post = new HttpPost(strURL); StringEntity entity = new StringEntity(string0.toString(), "ISO-8859-1"); entity.setContentType("text/xml; charset=\"ISO-8859-1\""); post.setEntity(entity); ResponseHandler<String> responseHandler = new BasicResponseHandler(); String responseBody = client.execute(post, responseHandler); long stop = System.currentTimeMillis(); logger.debug("----------------------------------------"); logger.debug("Response took " + (stop - start) + " ms"); logger.debug(responseBody); logger.debug("----------------------------------------"); } finally { // do nothing } } long totalEnd = System.currentTimeMillis(); logger.debug("Response took " + (totalEnd - totalStart) + " ms"); }
From source file:edu.harvard.hul.ois.fits.clients.FormFileUploaderClientApplication.java
/** * Run the program.//from w ww .ja v a2s. c om * * @param args First argument is path to the file to analyze; second (optional) is path to server for overriding default value. */ public static void main(String[] args) { // takes file path from first program's argument if (args.length < 1) { logger.error("****** Path to input file must be first argument to program! *******"); logger.error("===== Exiting Program ====="); System.exit(1); } String filePath = args[0]; File uploadFile = new File(filePath); if (!uploadFile.exists()) { logger.error("****** File does not exist at expected locations! *******"); logger.error("===== Exiting Program ====="); System.exit(1); } if (args.length > 1) { serverUrl = args[1]; } logger.info("File to upload: " + filePath); CloseableHttpClient httpclient = HttpClients.createDefault(); try { HttpPost httppost = new HttpPost(serverUrl + "false"); FileBody bin = new FileBody(uploadFile); MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.addPart(FITS_FORM_FIELD_DATAFILE, bin); HttpEntity reqEntity = builder.build(); httppost.setEntity(reqEntity); logger.info("executing request " + httppost.getRequestLine()); CloseableHttpResponse response = httpclient.execute(httppost); try { logger.info("HTTP Response Status Line: " + response.getStatusLine()); // Expecting a 200 Status Code if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) { String reason = response.getStatusLine().getReasonPhrase(); logger.warn("Unexpected HTTP response status code:[" + response.getStatusLine().getStatusCode() + "] -- Reason (if available): " + reason); } else { HttpEntity resEntity = response.getEntity(); InputStream is = resEntity.getContent(); BufferedReader in = new BufferedReader(new InputStreamReader(is)); String output; StringBuilder sb = new StringBuilder(); while ((output = in.readLine()) != null) { sb.append(output); sb.append(System.getProperty("line.separator")); } logger.info(sb.toString()); in.close(); EntityUtils.consume(resEntity); } } finally { response.close(); } } catch (Exception e) { logger.error("Caught exception: " + e.getMessage(), e); } finally { try { httpclient.close(); } catch (IOException e) { logger.warn("Exception closing HTTP client: " + e.getMessage(), e); } logger.info("DONE"); } }
From source file:edu.harvard.hul.ois.drs.pdfaconvert.clients.FormFileUploaderClientApplication.java
/** * Run the program.//from w ww . j a va 2 s . c o m * * @param args First argument is path to the file to analyze; second (optional) is path to server for overriding default value. */ public static void main(String[] args) { // takes file path from first program's argument if (args.length < 1) { logger.error("****** Path to input file must be first argument to program! *******"); logger.error("===== Exiting Program ====="); System.exit(1); } String filePath = args[0]; File uploadFile = new File(filePath); if (!uploadFile.exists()) { logger.error("****** File does not exist at expected locations! *******"); logger.error("===== Exiting Program ====="); System.exit(1); } if (args.length > 1) { serverUrl = args[1]; } logger.info("File to upload: " + filePath); CloseableHttpClient httpclient = HttpClients.createDefault(); try { HttpPost httppost = new HttpPost(serverUrl); FileBody bin = new FileBody(uploadFile); HttpEntity reqEntity = MultipartEntityBuilder.create().addPart(FORM_FIELD_DATAFILE, bin).build(); httppost.setEntity(reqEntity); logger.info("executing request " + httppost.getRequestLine()); CloseableHttpResponse response = httpclient.execute(httppost); try { logger.info("HTTP Response Status Line: " + response.getStatusLine()); // Expecting a 200 Status Code if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) { String reason = response.getStatusLine().getReasonPhrase(); logger.warn("Unexpected HTTP response status code:[" + response.getStatusLine().getStatusCode() + "] -- Reason (if available): " + reason); } else { HttpEntity resEntity = response.getEntity(); InputStream is = resEntity.getContent(); BufferedReader in = new BufferedReader(new InputStreamReader(is)); String output; StringBuilder sb = new StringBuilder("Response data received:"); while ((output = in.readLine()) != null) { sb.append(System.getProperty("line.separator")); sb.append(output); } logger.info(sb.toString()); in.close(); EntityUtils.consume(resEntity); } } finally { response.close(); } } catch (Exception e) { logger.error("Caught exception: " + e.getMessage(), e); } finally { try { httpclient.close(); } catch (IOException e) { logger.warn("Exception closing HTTP client: " + e.getMessage(), e); } logger.info("DONE"); } }
From source file:com.ds.test.ClientFormLogin.java
public static void main(String[] args) throws Exception { DefaultHttpClient httpclient = new DefaultHttpClient(); try {/*from w ww.j a va 2s. c o m*/ HttpGet httpget = new HttpGet("http://www.iteye.com/login"); HttpResponse response = httpclient.execute(httpget); HttpEntity entity = response.getEntity(); System.out.println("Login form get: " + response.getStatusLine()); System.out.println("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()); } } /* HeaderIterator hi = response.headerIterator(); while(hi.hasNext()){ System.out.println(hi.next()); } EntityUtils.consume(entity); */ String token = parseHtml(EntityUtils.toString(entity)); httpget.releaseConnection(); System.out.println("********************************************************"); HttpPost httpost = new HttpPost("http://www.iteye.com/login"); List<NameValuePair> nvps = new ArrayList<NameValuePair>(); nvps.add(new BasicNameValuePair("name", "")); nvps.add(new BasicNameValuePair("password", "")); nvps.add(new BasicNameValuePair("authenticity_token", token)); httpost.setEntity(new UrlEncodedFormEntity(nvps, Consts.UTF_8)); response = httpclient.execute(httpost); entity = response.getEntity(); System.out.println("Login form get: " + response.getStatusLine()); EntityUtils.consume(entity); System.out.println("Post logon cookies:"); 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()); } } System.out.println("********************************************************"); HttpGet httpget2 = new HttpGet("http://www.iteye.com/login"); HttpResponse response2 = httpclient.execute(httpget2); HttpEntity entity2 = response2.getEntity(); System.out.println("Login form get: " + response2.getStatusLine()); print(response2); } 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: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 www . j a v a 2s. 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:com.renren.ntc.sg.util.wxpay.https.ClientCustomSSL.java
public final static void main(String[] args) throws Exception { KeyStore keyStore = KeyStore.getInstance("PKCS12"); FileInputStream instream = new FileInputStream( new File("/Users/allenz/Downloads/wx_cert/apiclient_cert.p12")); try {/*from w w w . ja v a 2 s .co m*/ keyStore.load(instream, Constants.mch_id.toCharArray()); } finally { instream.close(); } // Trust own CA and all self-signed certs SSLContext sslcontext = SSLContexts.custom().loadKeyMaterial(keyStore, Constants.mch_id.toCharArray()) .build(); // Allow TLSv1 protocol only SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext, new String[] { "TLSv1" }, null, SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER); CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build(); try { HttpPost post = new HttpPost("https://api.mch.weixin.qq.com/mmpaymkttransfers/promotion/transfers"); System.out.println("executing request" + post.getRequestLine()); String openid = "oQfDLjmZD7Lgynv6vuoBlWXUY_ic"; String nonce_str = Sha1Util.getNonceStr(); String orderId = SUtils.getOrderId(); String re_user_name = "?"; String amount = "1"; String desc = ""; String spbill_create_ip = "123.56.102.224"; String txt = TXT.replace("{mch_appid}", Constants.mch_appid); txt = txt.replace("{mchid}", Constants.mch_id); txt = txt.replace("{openid}", openid); txt = txt.replace("{nonce_str}", nonce_str); txt = txt.replace("{partner_trade_no}", orderId); txt = txt.replace("{check_name}", "FORCE_CHECK"); txt = txt.replace("{re_user_name}", re_user_name); txt = txt.replace("{amount}", amount); txt = txt.replace("{desc}", desc); txt = txt.replace("{spbill_create_ip}", spbill_create_ip); SortedMap<String, String> map = new TreeMap<String, String>(); map.put("mch_appid", Constants.mch_appid); map.put("mchid", Constants.mch_id); map.put("openid", openid); map.put("nonce_str", nonce_str); map.put("partner_trade_no", orderId); //FORCE_CHECK| OPTION_CHECK | NO_CHECK map.put("check_name", "OPTION_CHECK"); map.put("re_user_name", re_user_name); map.put("amount", amount); map.put("desc", desc); map.put("spbill_create_ip", spbill_create_ip); String sign = SUtils.createSign(map).toUpperCase(); txt = txt.replace("{sign}", sign); post.setEntity(new StringEntity(txt, "utf-8")); CloseableHttpResponse response = httpclient.execute(post); try { HttpEntity entity = response.getEntity(); System.out.println(response.getStatusLine()); if (entity != null) { System.out.println("Response content length: " + entity.getContentLength()); BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(entity.getContent())); String text; StringBuffer sb = new StringBuffer(); while ((text = bufferedReader.readLine()) != null) { sb.append(text); } String resp = sb.toString(); LoggerUtils.getInstance().log(String.format("req %s rec %s", txt, resp)); if (isOk(resp)) { String payment_no = getValue(resp, "payment_no"); LoggerUtils.getInstance() .log(String.format("order %s pay OK payment_no %s", orderId, payment_no)); } } EntityUtils.consume(entity); } finally { response.close(); } } finally { httpclient.close(); } }
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 w w w . ja v a 2s . com 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:test.TestJavaService.java
/** * Main. The cmdline arguments either do or don't contain the flag -remote: that's the only supported flag. If it is specified, * we test code on the AWS instance. If it is not, we test code running locally. * The first non-flag argument is the "verb", which (currently) should be one of the verbs set at the top of source file * org.qcert.javasrc.Main. Remaining non-flag arguments are file names. There must be at least one. The number of such * arguments and what they should contain depends on the verb. * @throws Exception/* ww w .j a v a2 s .c om*/ */ public static void main(String[] args) throws Exception { /* Parse command line */ List<String> files = new ArrayList<>(); String loc = "localhost", verb = null; for (String arg : args) { if (arg.equals("-remote")) loc = REMOTE_LOC; else if (arg.startsWith("-")) illegal(); else if (verb == null) verb = arg; else files.add(arg); } /* Simple consistency checks and verb-specific parsing */ if (files.size() == 0) illegal(); String file = files.remove(0); String schema = null; switch (verb) { case "parseSQL": case "serialRule2CAMP": case "sqlSchema2JSON": if (files.size() != 0) illegal(); break; case "techRule2CAMP": if (files.size() != 1) illegal(); schema = files.get(0); break; case "csv2JSON": if (files.size() < 1) illegal(); break; default: illegal(); } /* Assemble information from arguments */ String url = String.format("http://%s:9879?verb=%s", loc, verb); byte[] contents = Files.readAllBytes(Paths.get(file)); String toSend; if ("serialRule2CAMP".equals(verb)) toSend = Base64.getEncoder().encodeToString(contents); else toSend = new String(contents); if ("techRule2CAMP".equals(verb)) toSend = makeSpecialJson(toSend, schema); else if ("csv2JSON".equals(verb)) toSend = makeSpecialJson(toSend, files); HttpClient client = HttpClients.createDefault(); HttpPost post = new HttpPost(url); StringEntity entity = new StringEntity(toSend); entity.setContentType("text/plain"); post.setEntity(entity); HttpResponse resp = client.execute(post); int code = resp.getStatusLine().getStatusCode(); if (code == HttpStatus.SC_OK) { HttpEntity answer = resp.getEntity(); InputStream s = answer.getContent(); BufferedReader rdr = new BufferedReader(new InputStreamReader(s)); String line = rdr.readLine(); while (line != null) { System.out.println(line); line = rdr.readLine(); } rdr.close(); s.close(); } else System.out.println(resp.getStatusLine()); }
From source file:com.da.img.ClientFormLogin.java
public static void main(String[] args) throws Exception { DefaultHttpClient httpclient = new DefaultHttpClient(); try {/*from w w w.j a v a 2s . c o m*/ HttpGet httpget = new HttpGet("http://www.soraven.info/index.php"); HttpResponse response = httpclient.execute(httpget); HttpEntity entity = response.getEntity(); //System.out.println( EntityUtils.toString(entity)); 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("-1 " + cookies.get(i).toString()); } } HttpPost httpost = new HttpPost("http://www.soraven.info/common/include/login.php"); Header header1 = new BasicHeader("Accept", "image/gif, image/x-xbitmap, image/jpeg, image/pjpeg,application/msword, */*"); Header header2 = new BasicHeader("Referer", "http://www.soraven.info/index.php"); List<NameValuePair> nvps = new ArrayList<NameValuePair>(); nvps.add(new BasicNameValuePair("p_userid", "bimohani")); nvps.add(new BasicNameValuePair("p_passwd", "cw8904")); nvps.add(new BasicNameValuePair("x", "12")); nvps.add(new BasicNameValuePair("y", "20")); httpost.setHeader(header1); httpost.setHeader(header2); httpost.setEntity(new UrlEncodedFormEntity(nvps, Consts.UTF_8)); //Thread.sleep(2000); response = httpclient.execute(httpost); entity = response.getEntity(); System.out.println("Login form get: " + response.getStatusLine()); System.out.println(EntityUtils.toString(entity)); EntityUtils.consume(entity); System.out.println("Post logon cookies:"); cookies = httpclient.getCookieStore().getCookies(); if (cookies.isEmpty()) { System.out.println("None"); } else { for (int i = 0; i < cookies.size(); i++) { System.out.println("-2 " + cookies.get(i).toString()); } } } finally { // When HttpClient instance is no longer needed, // shut down the connection manager to ensure // immediate deallocation of all system resources httpclient.getConnectionManager().shutdown(); } }