code_junkie

How do I login and download a file from a https web page from Java?

Nov 13th, 2011
97
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.80 KB | None | 0 0
  1. baseURL = // a https URL;
  2. urlMap = new HashMap<String, URL>();
  3. urlMap.put("login", new URL(baseURL, "exec.asp?login=username&pass=XPTO"));
  4. urlMap.put("logout", new URL(baseURL, "exec.asp?exec.asp?page=999"));
  5. urlMap.put("file", new URL(baseURL, "exec.asp?file=111"));
  6.  
  7. urlConnection = urlMap.get("login").openConnection();
  8. urlConnection.connect();
  9. BufferedReader in = new BufferedReader(
  10. new InputStreamReader(urlConnection.getInputStream()));
  11. String inputLine;
  12. while ((inputLine = in.readLine()) != null)
  13. System.out.println(inputLine);
  14. in.close();
  15.  
  16. class MyCookieHandler extends CookieHandler {
  17.  
  18. private Map<String, List<String>> cookies = new HashMap<String, List<String>>();
  19.  
  20. @Override
  21. public Map<String, List<String>> get(URI uri,
  22. Map<String, List<String>> requestHeaders) throws IOException {
  23. String host = uri.getHost();
  24. Map<String, List<String>> ret = new HashMap<String, List<String>>();
  25. synchronized (cookies) {
  26. List<String> store = cookies.get(host);
  27. if (store != null) {
  28. store = Collections.unmodifiableList(store);
  29. ret.put("Cookie", store);
  30. }
  31. }
  32.  
  33. return Collections.unmodifiableMap(ret);
  34. }
  35.  
  36. @Override
  37. public void put(URI uri, Map<String, List<String>> responseHeaders)
  38. throws IOException {
  39. List<String> newCookies = responseHeaders.get("Set-Cookie");
  40. if (newCookies != null) {
  41. String host = uri.getHost();
  42. synchronized (cookies) {
  43. List<String> store = cookies.get(host);
  44. if (store == null) {
  45. store = new ArrayList<String>();
  46. cookies.put(host, store);
  47. }
  48. store.addAll(newCookies);
  49. }
  50. }
  51. }
  52.  
  53. }
Add Comment
Please, Sign In to add comment