List of usage examples for org.apache.http.impl.client DefaultHttpClient DefaultHttpClient
public DefaultHttpClient()
From source file:com.mtea.macrotea_httpclient_study.ClientCustomContext.java
public final static void main(String[] args) throws Exception { HttpClient httpclient = new DefaultHttpClient(); try {//from w w w. j a v a2s .c om // CookieStore CookieStore cookieStore = new BasicCookieStore(); // HttpContext HttpContext localContext = new BasicHttpContext(); //HttpContextCookieStore localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore); HttpGet httpget = new HttpGet("http://www.google.com/"); System.out.println("executing request " + httpget.getURI()); // ? HttpResponse response = httpclient.execute(httpget, localContext); HttpEntity entity = response.getEntity(); System.out.println("----------------------------------------"); System.out.println(response.getStatusLine()); if (entity != null) { System.out.println("Response content length: " + entity.getContentLength()); } //???cookie List<Cookie> cookies = cookieStore.getCookies(); for (int i = 0; i < cookies.size(); i++) { System.out.println("Local cookie: " + cookies.get(i)); } // EntityUtils.consume(entity); System.out.println("----------------------------------------"); } finally { //??httpclient??? httpclient.getConnectionManager().shutdown(); } }
From source file:org.vuphone.vandyupon.test.ImagePostTester.java
public static void main(String[] args) { try {//from ww w . j a v a2 s. com File image = new File("2008-05-8 ChrisMikeNinaGrad.jpg"); byte[] bytes = new byte[(int) image.length()]; FileInputStream fis = new FileInputStream(image); int offset = 0; int numRead = 0; while (offset < bytes.length && (numRead = fis.read(bytes, offset, bytes.length - offset)) >= 0) { offset += numRead; } fis.close(); HttpClient c = new DefaultHttpClient(); HttpPost post = new HttpPost( "http://afrl-gift.dre.vanderbilt.edu:8080/vandyupon/events/?type=eventimagepost&eventid=2" + "&time=" + System.currentTimeMillis() + "&resp=xml"); post.addHeader("Content-Type", "image/jpeg"); ByteArrayEntity bae = new ByteArrayEntity(bytes); post.setEntity(bae); try { HttpResponse resp = c.execute(post); resp.getEntity().writeTo(System.out); } catch (IOException e) { e.printStackTrace(); } } catch (IOException e) { e.printStackTrace(); } }
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);/*from www . j a v a2s . c om*/ 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.quix.aia.cn.imo.mapper.UrlForUserData.java
public static void main(String[] args) { // TODO Auto-generated method stub UserAuthResponds userAuth = new UserAuthResponds(); try {/*from w ww . jav a 2 s .c om*/ GsonBuilder builder = new GsonBuilder(); DefaultHttpClient httpClient = new DefaultHttpClient(); String username = "", psw = "", co = ""; username = "NSNP306"; psw = "A111111A"; co = "0986"; HttpGet getRequest = new HttpGet("http://211.144.219.243/isp/rest/index.do?isAjax=true&account=" + username + "&co=" + co + "&password=" + psw + ""); getRequest.addHeader("accept", "application/json"); HttpResponse response = httpClient.execute(getRequest); if (response.getStatusLine().getStatusCode() != 200) { throw new RuntimeException( "Failed : HTTP error code : " + response.getStatusLine().getStatusCode()); } BufferedReader br = new BufferedReader(new InputStreamReader((response.getEntity().getContent()))); String output; System.out.println("Output from Server .... \n"); while ((output = br.readLine()) != null) { System.out.println(output); Gson googleJson = new Gson(); userAuth = googleJson.fromJson(output, UserAuthResponds.class); System.out.println("Success " + userAuth.getSuccess()); if (userAuth.getSuccess().equals("1")) { System.out.println("Login successfully Done"); } else { System.out.println("Login Failed "); } } httpClient.getConnectionManager().shutdown(); // googleJson = builder.create(); // Type listType = new TypeToken<List<UserAuthResponds>>() {}.getType(); } catch (ClientProtocolException e) { log.log(Level.SEVERE, e.getMessage()); e.printStackTrace(); } catch (IOException e) { log.log(Level.SEVERE, e.getMessage()); e.printStackTrace(); } }
From source file:com.dlmu.heipacker.crawler.client.ClientFormLogin.java
public static void main(String[] args) throws Exception { DefaultHttpClient httpclient = new DefaultHttpClient(); try {// www.j av a2 s.c o m HttpGet httpget = new HttpGet("https://portal.sun.com/portal/dt"); HttpResponse response = httpclient.execute(httpget); HttpEntity entity = response.getEntity(); 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("https://portal.sun.com/amserver/UI/Login?" + "org=self_registered_users&" + "goto=/portal/dt&" + "gotoOnFail=/portal/dt?error=true"); List<NameValuePair> nvps = new ArrayList<NameValuePair>(); nvps.add(new BasicNameValuePair("IDToken1", "username")); nvps.add(new BasicNameValuePair("IDToken2", "password")); 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()); } } } 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.dlmu.heipacker.crawler.client.ClientCustomContext.java
public final static void main(String[] args) throws Exception { HttpClient httpclient = new DefaultHttpClient(); try {/*from www . ja va 2 s .co m*/ // Create a local instance of cookie store CookieStore cookieStore = new BasicCookieStore(); // Create local HTTP context HttpContext localContext = new BasicHttpContext(); // Bind custom cookie store to the local context localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore); HttpGet httpget = new HttpGet("http://www.google.com/"); System.out.println("executing request " + httpget.getURI()); // Pass local context as a parameter HttpResponse response = httpclient.execute(httpget, localContext); HttpEntity entity = response.getEntity(); System.out.println("----------------------------------------"); System.out.println(response.getStatusLine()); if (entity != null) { System.out.println("Response content length: " + entity.getContentLength()); } List<Cookie> cookies = cookieStore.getCookies(); for (int i = 0; i < cookies.size(); i++) { System.out.println("Local cookie: " + cookies.get(i)); } // Consume response content EntityUtils.consume(entity); 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:ch.tatool.app.service.export.DataImportTest.java
public static void main(String[] args) { // get the httpentity containing the data HttpEntity httpEntity = getHttpEntity(); // Create a httpclient instance DefaultHttpClient httpclient = new DefaultHttpClient(); // setup a POST call HttpGet httpGet = new HttpGet(serverUrl); try {//from www. j av a 2s.c o m HttpResponse response = httpclient.execute(httpGet); if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) { System.out.println("Unable to download data: " + response.getStatusLine().getReasonPhrase()); System.out.println(response.getStatusLine().getStatusCode()); } else { // all ok HttpEntity enty = response.getEntity(); InputStream is = enty.getContent(); XmlBeanFactory beanFactory = null; try { beanFactory = new XmlBeanFactory(new InputStreamResource(is)); } catch (BeansException be) { // TODO: inform user that training configuration is broken throw new RuntimeException("Unable to load module configuration", be); } // check whether we have the mandatory beans (rootElement) if (!beanFactory.containsBean("rootElement")) { // TODO: inform user that training configuration is broken throw new RuntimeException("No rootElement bean found in the module configuration file"); } // fetch the rootElement Node rootElement = (Node) beanFactory.getBean("rootElement"); System.out.println(rootElement.getId()); } } catch (IOException ioe) { } // 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:fr.itinerennes.bundler.integration.onebusaway.GenerateStaticObaApiResults.java
public static void main(String[] args) throws IOException, GtfsException { final String url = args[0]; final String key = args[1]; final String gtfsFile = args[2]; final String out = args[3].replaceAll("/$", ""); final Map<String, String> agencyMapping = new HashMap<String, String>(); agencyMapping.put("1", "2"); final GtfsDao gtfs = GtfsUtils.load(new File(gtfsFile), agencyMapping); oba = new JsonOneBusAwayClient(new DefaultHttpClient(), url, key); gson = OneBusAwayGsonFactory.newInstance(true); final Calendar end = Calendar.getInstance(); end.set(2013, 11, 22, 0, 0);// w ww .jav a 2s . c o m final Calendar start = Calendar.getInstance(); start.set(2013, 10, 4, 0, 0); final Calendar current = Calendar.getInstance(); current.setTime(start.getTime()); while (current.before(end) || current.equals(end)) { System.out.println(current.getTime()); for (final Stop stop : gtfs.getAllStops()) { final String stopId = stop.getId().toString(); final String dateDir = String.format("%04d/%02d/%02d", current.get(Calendar.YEAR), current.get(Calendar.MONTH) + 1, current.get(Calendar.DAY_OF_MONTH)); final String methodDir = String.format("%s/schedule-for-stop", out); final File outDir = new File(String.format("%s/%s", methodDir, dateDir)); outDir.mkdirs(); final File f = new File(outDir, String.format("%s.json", stopId)); final StopSchedule ss = oba.getScheduleForStop(stopId, current.getTime()); final String json = gson.toJson(ss); final Writer w = new PrintWriter(f); w.write(json); w.close(); } current.add(Calendar.DAY_OF_MONTH, 1); } final File outDir = new File(String.format("%s/trip-details", out)); outDir.mkdirs(); for (final Trip trip : gtfs.getAllTrips()) { final String tripId = trip.getId().toString(); final File f = new File(outDir, String.format("%s.json", tripId)); final TripSchedule ts = oba.getTripDetails(tripId); final String json = gson.toJson(ts); final Writer w = new PrintWriter(f); w.write(json); w.close(); } }
From source file:httpclient.client.ClientInteractiveAuthentication.java
public static void main(String[] args) throws Exception { DefaultHttpClient httpclient = new DefaultHttpClient(); // Create local execution context HttpContext localContext = new BasicHttpContext(); HttpGet httpget = new HttpGet("http://localhost/test"); boolean trying = true; while (trying) { System.out.println("executing request " + httpget.getRequestLine()); HttpResponse response = httpclient.execute(httpget, localContext); System.out.println("----------------------------------------"); System.out.println(response.getStatusLine()); // Consume response content HttpEntity entity = response.getEntity(); if (entity != null) { entity.consumeContent();/*w ww . j av a 2 s . c o m*/ } int sc = response.getStatusLine().getStatusCode(); AuthState authState = null; if (sc == HttpStatus.SC_UNAUTHORIZED) { // Target host authentication required authState = (AuthState) localContext.getAttribute(ClientContext.TARGET_AUTH_STATE); } if (sc == HttpStatus.SC_PROXY_AUTHENTICATION_REQUIRED) { // Proxy authentication required authState = (AuthState) localContext.getAttribute(ClientContext.PROXY_AUTH_STATE); } if (authState != null) { System.out.println("----------------------------------------"); AuthScope authScope = authState.getAuthScope(); System.out.println("Please provide credentials"); System.out.println(" Host: " + authScope.getHost() + ":" + authScope.getPort()); System.out.println(" Realm: " + authScope.getRealm()); BufferedReader console = new BufferedReader(new InputStreamReader(System.in)); System.out.print("Enter username: "); String user = console.readLine(); System.out.print("Enter password: "); String password = console.readLine(); if (user != null && user.length() > 0) { Credentials creds = new UsernamePasswordCredentials(user, password); httpclient.getCredentialsProvider().setCredentials(authScope, creds); trying = true; } else { trying = false; } } else { trying = false; } } // 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.dlmu.heipacker.crawler.client.ClientExecuteSOCKS.java
public static void main(String[] args) throws Exception { DefaultHttpClient httpclient = new DefaultHttpClient(); try {/* w ww.j a va 2s.c o m*/ httpclient.getParams().setParameter("socks.host", "mysockshost"); httpclient.getParams().setParameter("socks.port", 1234); httpclient.getConnectionManager().getSchemeRegistry() .register(new Scheme("http", 80, new MySchemeSocketFactory())); HttpHost target = new HttpHost("www.apache.org", 80, "http"); HttpGet req = new HttpGet("/"); System.out.println("executing request to " + target + " via SOCKS proxy"); HttpResponse rsp = httpclient.execute(target, req); HttpEntity entity = rsp.getEntity(); System.out.println("----------------------------------------"); System.out.println(rsp.getStatusLine()); Header[] headers = rsp.getAllHeaders(); for (int i = 0; i < headers.length; i++) { System.out.println(headers[i]); } System.out.println("----------------------------------------"); if (entity != null) { System.out.println(EntityUtils.toString(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(); } }