ashutiwari4

Untitled

Aug 8th, 2016
64
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.98 KB | None | 0 0
  1. public static ServerResponse getServerStream(String url, HashMap<String, String> parameter, String reqtype) {
  2. HttpURLConnection connection;
  3.  
  4. ServerResponse streamBean = new ServerResponse();
  5. try {
  6. connection = (HttpURLConnection) (new URL(url)).openConnection();
  7. connection.setInstanceFollowRedirects(true);
  8.  
  9. connection.setUseCaches(true);
  10. // connection.setDefaultUseCaches(true);
  11.  
  12. connection.setReadTimeout(10000);
  13. connection.setConnectTimeout(15000);
  14. connection.setRequestMethod(reqtype);
  15. // connection.addRequestProperty("Cache-Control", "only-if-cached");
  16. connection.addRequestProperty("Cache-Control", "max-age=" + 30 * 60);
  17. int maxStale = 60 * 60 * 24 * 28; // tolerate 1 day stale
  18. connection.addRequestProperty("Cache-Control", "max-stale=" + maxStale);
  19.  
  20.  
  21. if (reqtype == NetworkLoader.POST) {
  22. connection.setDoInput(true);
  23. connection.setDoOutput(true);
  24. if (parameter != null) {
  25. OutputStream os = connection.getOutputStream();
  26. BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
  27. writer.write(getPostDataString(parameter));
  28. writer.flush();
  29. writer.close();
  30. os.close();
  31.  
  32. }
  33. }
  34.  
  35. connection.connect();
  36. System.out.println("Response Cache is installed : " + HttpResponseCache.getInstalled().getHitCount()+" Size: "+ HttpResponseCache.getInstalled().maxSize());
  37. System.out.println("Cached response is : " + HttpResponseCache.getInstalled().get(new URI(url.toString()), reqtype, connection.getHeaderFields()));
  38.  
  39. //System.out.println("Connection Error: " + connection.getResponseCode());
  40. if (connection.getResponseCode() == 200 && connection.getInputStream() != null) {
  41. streamBean.setResponseCode(connection.getResponseCode());
  42. streamBean.setServerResponse(convertStreamToString(connection.getInputStream()));
  43. return streamBean;
  44. } else {
  45. streamBean.setResponseCode(connection.getResponseCode());
  46. streamBean.setServerResponse(convertStreamToString(connection.getErrorStream()));
  47. return streamBean;
  48. }
  49. } catch (EOFException eof) {
  50. streamBean.setException(eof);
  51. eof.printStackTrace();
  52. } catch (SocketException se) {
  53. streamBean.setException(se);
  54. se.printStackTrace();
  55. } catch (IOException exception) {
  56. streamBean.setException(exception);
  57. exception.printStackTrace();
  58. } catch (Exception exception) {
  59. streamBean.setException(exception);
  60. exception.printStackTrace();
  61. }
  62. return streamBean;
  63. }
Add Comment
Please, Sign In to add comment