Advertisement
Guest User

WEBUTILS

a guest
Sep 14th, 2018
201
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.64 KB | None | 0 0
  1. public class WebUtils {
  2.  
  3. public static String get(String url) throws IOException {
  4.  
  5. HttpURLConnection con = (HttpURLConnection) new URL(url).openConnection();
  6.  
  7. con.setRequestMethod("GET");
  8. con.setRequestProperty("User-Agent", "Mozilla/5.0");
  9.  
  10. BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
  11. String inputLine;
  12. StringBuilder response = new StringBuilder();
  13.  
  14. while ((inputLine = in.readLine()) != null) {
  15. response.append(inputLine)
  16. .append("\n");
  17. }
  18.  
  19. in.close();
  20.  
  21. return response.toString();
  22. }
  23.  
  24. public static String post(String url, Map<String, String> requestMap, String body) throws IOException {
  25.  
  26. HttpURLConnection con = (HttpURLConnection) new URL(url).openConnection();
  27.  
  28. con.setRequestMethod("POST");
  29. con.setRequestProperty("User-Agent", "Mozilla/5.0");
  30.  
  31. if (requestMap != null)
  32. requestMap.forEach(con::setRequestProperty);
  33.  
  34. con.setDoOutput(true);
  35. con.setDoInput(true);
  36.  
  37. DataOutputStream wr = new DataOutputStream(con.getOutputStream());
  38. wr.writeBytes(body);
  39. wr.flush();
  40. wr.close();
  41.  
  42. BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
  43. String inputLine;
  44. StringBuilder response = new StringBuilder();
  45.  
  46. while ((inputLine = in.readLine()) != null) {
  47. response.append(inputLine)
  48. .append("\n");
  49. }
  50. in.close();
  51.  
  52. return response.toString();
  53. }
  54.  
  55.  
  56. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement