List of usage examples for org.apache.http.client.methods HttpPost setEntity
public void setEntity(final HttpEntity entity)
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 w w w . j a v a 2s .co 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: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 {// ww w. ja va 2 s . c o 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:net.cloudkit.relaxation.HttpClientTest.java
public static void main(String[] args) throws Exception { InetAddress[] addresss = InetAddress.getAllByName("google.com"); for (InetAddress address : addresss) { System.out.println(address); }/* w w w. j a va2 s .co m*/ CloseableHttpClient httpclient = HttpClients.createDefault(); String __VIEWSTATE = ""; String __EVENTVALIDATION = ""; HttpGet httpGet = new HttpGet("http://query.customs.gov.cn/MNFTQ/MRoadQuery.aspx?" + Math.random() * 1000); httpGet.setHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8"); httpGet.setHeader("Accept-Encoding", "gzip, deflate, sdch"); httpGet.setHeader("Accept-Language", "zh-CN,zh;q=0.8,en;q=0.6"); httpGet.setHeader("Cache-Control", "no-cache"); // httpGet.setHeader("Connection", "keep-alive"); httpGet.setHeader("Host", "query.customs.gov.cn"); httpGet.setHeader("Pragma", "no-cache"); httpGet.setHeader("Upgrade-Insecure-Requests", "1"); httpGet.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.101 Safari/537.36"); HttpClientContext context = HttpClientContext.create(); // CloseableHttpResponse response1 = httpclient.execute(httpGet, context); CloseableHttpResponse response1 = httpclient.execute(httpGet); // Header[] headers = response1.getHeaders(HttpHeaders.CONTENT_TYPE); // System.out.println("context cookies:" + context.getCookieStore().getCookies()); // String setCookie = response1.getFirstHeader("Set-Cookie").getValue(); // System.out.println("context cookies:" + setCookie); try { System.out.println(response1.getStatusLine()); HttpEntity entity1 = response1.getEntity(); // do something useful with the response body and ensure it is fully consumed String result = IOUtils.toString(entity1.getContent(), "GBK"); // System.out.println(result); Matcher m1 = Pattern.compile( "<input type=\\\"hidden\\\" name=\\\"__VIEWSTATE\\\" id=\\\"__VIEWSTATE\\\" value=\\\"(.*)\\\" />") .matcher(result); __VIEWSTATE = m1.find() ? m1.group(1) : ""; Matcher m2 = Pattern.compile( "<input type=\\\"hidden\\\" name=\\\"__EVENTVALIDATION\\\" id=\\\"__EVENTVALIDATION\\\" value=\\\"(.*)\\\" />") .matcher(result); __EVENTVALIDATION = m2.find() ? m2.group(1) : ""; System.out.println(__VIEWSTATE); System.out.println(__EVENTVALIDATION); /* File storeFile = new File("D:\\customs\\customs"+ i +".jpg"); FileOutputStream output = new FileOutputStream(storeFile); IOUtils.copy(input, output); output.close(); */ EntityUtils.consume(entity1); } finally { response1.close(); } HttpPost httpPost = new HttpPost( "http://query.customs.gov.cn/MNFTQ/MRoadQuery.aspx?" + Math.random() * 1000); httpPost.setHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8"); httpPost.setHeader("Accept-Encoding", "gzip, deflate"); httpPost.setHeader("Accept-Language", "zh-CN,zh;q=0.8,en;q=0.6"); httpPost.setHeader("Cache-Control", "no-cache"); // httpPost.setHeader("Connection", "keep-alive"); httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded"); httpPost.setHeader("Cookie", "ASP.NET_SessionId=t1td453hcuy4oqiplekkqe55"); httpPost.setHeader("Host", "query.customs.gov.cn"); httpPost.setHeader("Origin", "http://query.customs.gov.cn"); httpPost.setHeader("Pragma", "no-cache"); httpPost.setHeader("Referer", "http://query.customs.gov.cn/MNFTQ/MRoadQuery.aspx"); httpPost.setHeader("Upgrade-Insecure-Requests", "1"); httpPost.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.101 Safari/537.36"); List<NameValuePair> nvps = new ArrayList<NameValuePair>(); nvps.add(new BasicNameValuePair("__VIEWSTATE", __VIEWSTATE)); nvps.add(new BasicNameValuePair("__EVENTVALIDATION", __EVENTVALIDATION)); nvps.add(new BasicNameValuePair("ScrollTop", "")); nvps.add(new BasicNameValuePair("__essVariable", "")); nvps.add(new BasicNameValuePair("MRoadQueryCtrl1$txtManifestID", "5100312462240")); nvps.add(new BasicNameValuePair("MRoadQueryCtrl1$txtBillNo", "7PH650021105")); nvps.add(new BasicNameValuePair("MRoadQueryCtrl1$txtCode", "a778")); nvps.add(new BasicNameValuePair("MRoadQueryCtrl1$btQuery", " ")); nvps.add(new BasicNameValuePair("select", "")); nvps.add(new BasicNameValuePair("select1", "")); nvps.add(new BasicNameValuePair("select2", "")); nvps.add(new BasicNameValuePair("select3", "")); nvps.add(new BasicNameValuePair("select4", "")); nvps.add(new BasicNameValuePair("select5", "??")); nvps.add(new BasicNameValuePair("select6", "")); nvps.add(new BasicNameValuePair("select7", "")); nvps.add(new BasicNameValuePair("select8", "")); httpPost.setEntity(new UrlEncodedFormEntity(nvps, "GBK")); 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 // System.out.println(entity2.getContent()); System.out.println(IOUtils.toString(response2.getEntity().getContent(), "GBK")); EntityUtils.consume(entity2); } finally { response2.close(); } }
From source file:org.wso2.carbon.sample.pizzadelivery.client.PizzaDeliveryClient.java
public static void main(String[] args) { KeyStoreUtil.setTrustStoreParams();//from w ww . j a va2 s.c o m String url = args[0]; String username = args[1]; String password = args[2]; HttpClient httpClient = new SystemDefaultHttpClient(); try { HttpPost method = new HttpPost(url); if (httpClient != null) { String[] xmlElements = new String[] { "<mypizza:PizzaDeliveryStream xmlns:mypizza=\"http://samples.wso2.org/\">\n" + " <mypizza:PizzaDelivery>\n" + " <mypizza:OrderNo>0023</mypizza:OrderNo>\n" + " <mypizza:PaymentType>Card</mypizza:PaymentType>\n" + " <mypizza:Address>29BX Finchwood Ave, Clovis, CA 93611</mypizza:Address>\n" + " </mypizza:PizzaDelivery>\n" + "</mypizza:PizzaDeliveryStream>", "<mypizza:PizzaDeliveryStream xmlns:mypizza=\"http://samples.wso2.org/\">\n" + " <mypizza:PizzaDelivery>\n" + " <mypizza:OrderNo>0024</mypizza:OrderNo>\n" + " <mypizza:PaymentType>Card</mypizza:PaymentType>\n" + " <mypizza:Address>2CYL Morris Ave, Clovis, CA 93611</mypizza:Address>\n" + " </mypizza:PizzaDelivery>\n" + "</mypizza:PizzaDeliveryStream>", "<mypizza:PizzaDeliveryStream xmlns:mypizza=\"http://samples.wso2.org/\">\n" + " <mypizza:PizzaDelivery>\n" + " <mypizza:OrderNo>0025</mypizza:OrderNo>\n" + " <mypizza:PaymentType>Cash</mypizza:PaymentType>\n" + " <mypizza:Address>22RE Robinwood Ave, Clovis, CA 93611</mypizza:Address>\n" + " </mypizza:PizzaDelivery>\n" + "</mypizza:PizzaDeliveryStream>", "<mypizza:PizzaDeliveryStream xmlns:mypizza=\"http://samples.wso2.org/\">\n" + " <mypizza:PizzaDelivery>\n" + " <mypizza:OrderNo>0026</mypizza:OrderNo>\n" + " <mypizza:PaymentType>Card</mypizza:PaymentType>\n" + " <mypizza:Address>29BX Finchwood Ave, Clovis, CA 93611</mypizza:Address>\n" + " </mypizza:PizzaDelivery>\n" + "</mypizza:PizzaDeliveryStream>" }; try { for (String xmlElement : xmlElements) { StringEntity entity = new StringEntity(xmlElement); method.setEntity(entity); if (url.startsWith("https")) { processAuthentication(method, username, password); } httpClient.execute(method).getEntity().getContent().close(); } } catch (Exception e) { e.printStackTrace(); } Thread.sleep(500); // We need to wait some time for the message to be sent } } catch (Throwable t) { t.printStackTrace(); } }
From source file:org.wso2.carbon.sample.pizzadelivery.client.PizzaOrderClient.java
public static void main(String[] args) { KeyStoreUtil.setTrustStoreParams();/*www . j a v a 2 s . c o m*/ String url = args[0]; boolean batchedElements = Boolean.valueOf(args[1]); HttpClient httpClient = new SystemDefaultHttpClient(); try { HttpPost method = new HttpPost(url); if (httpClient != null) { String[] xmlElements = new String[] { "<mypizza:PizzaOrderStream xmlns:mypizza=\"http://samples.wso2.org/\">\n" + " <mypizza:PizzaOrder>\n" + " <mypizza:OrderNo>0023</mypizza:OrderNo>\n" + " <mypizza:Type>PEPPERONI</mypizza:Type>\n" + " <mypizza:Size>L</mypizza:Size>\n" + " <mypizza:Quantity>2</mypizza:Quantity>\n" + " <mypizza:Contact>James Mark</mypizza:Contact>\n" + " <mypizza:Address>29BX Finchwood Ave, Clovis, CA 93611</mypizza:Address>\n" + " </mypizza:PizzaOrder>\n" + "</mypizza:PizzaOrderStream>", "<mypizza:PizzaOrderStream xmlns:mypizza=\"http://samples.wso2.org/\">\n" + " <mypizza:PizzaOrder>\n" + " <mypizza:OrderNo>0024</mypizza:OrderNo>\n" + " <mypizza:Type>CHEESE</mypizza:Type>\n" + " <mypizza:Size>M</mypizza:Size>\n" + " <mypizza:Quantity>1</mypizza:Quantity>\n" + " <mypizza:Contact>Henry Clock</mypizza:Contact>\n" + " <mypizza:Address>2CYL Morris Ave, Clovis, CA 93611</mypizza:Address>\n" + " </mypizza:PizzaOrder>\n" + "</mypizza:PizzaOrderStream>", "<mypizza:PizzaOrderStream xmlns:mypizza=\"http://samples.wso2.org/\">\n" + " <mypizza:PizzaOrder>\n" + " <mypizza:OrderNo>0025</mypizza:OrderNo>\n" + " <mypizza:Type>SEAFOOD</mypizza:Type>\n" + " <mypizza:Size>S</mypizza:Size>\n" + " <mypizza:Quantity>4</mypizza:Quantity>\n" + " <mypizza:Contact>James Mark</mypizza:Contact>\n" + " <mypizza:Address>22RE Robinwood Ave, Clovis, CA 93611</mypizza:Address>\n" + " </mypizza:PizzaOrder>\n" + "</mypizza:PizzaOrderStream>", "<mypizza:PizzaOrderStream xmlns:mypizza=\"http://samples.wso2.org/\">\n" + " <mypizza:PizzaOrder>\n" + " <mypizza:OrderNo>0026</mypizza:OrderNo>\n" + " <mypizza:Type>CHICKEN</mypizza:Type>\n" + " <mypizza:Size>L</mypizza:Size>\n" + " <mypizza:Contact>Alis Miranda</mypizza:Contact>\n" + " <mypizza:Address>779 Burl Ave, Clovis, CA 93611</mypizza:Address>\n" + " </mypizza:PizzaOrder>\n" + "</mypizza:PizzaOrderStream>", "<mypizza:PizzaOrderStream xmlns:mypizza=\"http://samples.wso2.org/\">\n" + " <mypizza:PizzaOrder>\n" + " <mypizza:OrderNo>0026</mypizza:OrderNo>\n" + " <mypizza:Type>VEGGIE</mypizza:Type>\n" + " <mypizza:Size>L</mypizza:Size>\n" + " <mypizza:Quantity>1</mypizza:Quantity>\n" + " <mypizza:Contact>James Mark</mypizza:Contact>\n" + " <mypizza:Address>29BX Finchwood Ave, Clovis, CA 93611</mypizza:Address>\n" + " </mypizza:PizzaOrder>\n" + "</mypizza:PizzaOrderStream>" }; String[] batchedXmlElements = new String[] { "<mypizza:PizzaOrderStream xmlns:mypizza=\"http://samples.wso2.org/\">\n" + " <mypizza:PizzaOrder>\n" + " <mypizza:OrderNo>0023</mypizza:OrderNo>\n" + " <mypizza:Type>PEPPERONI</mypizza:Type>\n" + " <mypizza:Size>L</mypizza:Size>\n" + " <mypizza:Quantity>2</mypizza:Quantity>\n" + " <mypizza:Contact>James Mark</mypizza:Contact>\n" + " <mypizza:Address>29BX Finchwood Ave, Clovis, CA 93611</mypizza:Address>\n" + " </mypizza:PizzaOrder>\n" + " <mypizza:PizzaOrder>\n" + " <mypizza:OrderNo>0024</mypizza:OrderNo>\n" + " <mypizza:Type>CHEESE</mypizza:Type>\n" + " <mypizza:Size>M</mypizza:Size>\n" + " <mypizza:Quantity>1</mypizza:Quantity>\n" + " <mypizza:Contact>Henry Clock</mypizza:Contact>\n" + " <mypizza:Address>2CYL Morris Ave, Clovis, CA 93611</mypizza:Address>\n" + " </mypizza:PizzaOrder>\n" + " <mypizza:PizzaOrder>\n" + " <mypizza:OrderNo>0025</mypizza:OrderNo>\n" + " <mypizza:Type>SEAFOOD</mypizza:Type>\n" + " <mypizza:Size>S</mypizza:Size>\n" + " <mypizza:Quantity>4</mypizza:Quantity>\n" + " <mypizza:Contact>James Mark</mypizza:Contact>\n" + " <mypizza:Address>22RE Robinwood Ave, Clovis, CA 93611</mypizza:Address>\n" + " </mypizza:PizzaOrder>\n" + "</mypizza:PizzaOrderStream>", "<mypizza:PizzaOrderStream xmlns:mypizza=\"http://samples.wso2.org/\">\n" + " <mypizza:PizzaOrder>\n" + " <mypizza:OrderNo>0026</mypizza:OrderNo>\n" + " <mypizza:Type>CHICKEN</mypizza:Type>\n" + " <mypizza:Size>L</mypizza:Size>\n" + " <mypizza:Quantity>1</mypizza:Quantity>\n" + " <mypizza:Contact>Alis Miranda</mypizza:Contact>\n" + " <mypizza:Address>779 Burl Ave, Clovis, CA 93611</mypizza:Address>\n" + " </mypizza:PizzaOrder>\n" + " <mypizza:PizzaOrder>\n" + " <mypizza:OrderNo>0026</mypizza:OrderNo>\n" + " <mypizza:Type>VEGGIE</mypizza:Type>\n" + " <mypizza:Size>L</mypizza:Size>\n" + " <mypizza:Quantity>1</mypizza:Quantity>\n" + " <mypizza:Contact>James Mark</mypizza:Contact>\n" + " <mypizza:Address>29BX Finchwood Ave, Clovis, CA 93611</mypizza:Address>\n" + " </mypizza:PizzaOrder>\n" + "</mypizza:PizzaOrderStream>" }; int i = 0; if (batchedElements) { for (String xmlElement : batchedXmlElements) { StringEntity entity = new StringEntity(xmlElement); method.setEntity(entity); httpClient.execute(method).getEntity().getContent().close(); System.out.println("Sent event no :" + i++); } } else { for (String xmlElement : xmlElements) { StringEntity entity = new StringEntity(xmlElement); method.setEntity(entity); httpClient.execute(method).getEntity().getContent().close(); System.out.println("Sent event no :" + i++); } } Thread.sleep(500); // We need to wait some time for the message to be sent } } catch (Throwable t) { t.printStackTrace(); } }
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:io.kamax.mxisd.util.RestClientUtils.java
public static HttpPost post(String url, String body) { StringEntity entity = new StringEntity(body, StandardCharsets.UTF_8); entity.setContentType(ContentType.APPLICATION_JSON.toString()); HttpPost req = new HttpPost(url); req.setEntity(entity); return req;//from w w w . java2 s . c om }
From source file:Main.java
public static String getStringFromUrl(List<NameValuePair> nameValuePairs) throws ClientProtocolException, IOException { String url = "http://www.fsurugby.org/serve/request.php"; DefaultHttpClient client = new DefaultHttpClient(); HttpPost httppost = new HttpPost(url); httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); HttpResponse response = client.execute(httppost); HttpEntity entity = response.getEntity(); BufferedHttpEntity buffer = new BufferedHttpEntity(entity); InputStream is = buffer.getContent(); BufferedReader reader = new BufferedReader(new InputStreamReader(is)); StringBuilder sb = new StringBuilder(); String line;/*from www .j a va 2 s.c om*/ while ((line = reader.readLine()) != null) { sb.append(line); } return sb.toString(); }
From source file:Main.java
public static String getJSONFromUrlWithPostRequest(String url, List<NameValuePair> params) { try {/*from ww w . jav a 2 s . c o 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 ""; }
From source file:nayan.netty.client.FileUploadClient.java
private static void uploadFile() throws Exception { File file = new File("small.jpg"); HttpEntity httpEntity = MultipartEntityBuilder.create() .addBinaryBody("file", file, ContentType.create("image/jpeg"), file.getName()).build(); CloseableHttpClient httpclient = HttpClients.createDefault(); HttpPost httppost = new HttpPost("http://localhost:8080"); httppost.setEntity(httpEntity); System.out.println("executing request " + httppost.getRequestLine()); CloseableHttpResponse response = httpclient.execute(httppost); System.out.println("----------------------------------------"); System.out.println(response.getStatusLine()); HttpEntity resEntity = response.getEntity(); if (resEntity != null) { System.out.println("Response content length: " + resEntity.getContentLength()); }//from ww w .j a v a2 s.com EntityUtils.consume(resEntity); response.close(); }