Advertisement
Guest User

httputil.java

a guest
Apr 24th, 2015
206
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.51 KB | None | 0 0
  1. package util;
  2.  
  3. import java.io.BufferedReader;
  4. import java.io.DataOutputStream;
  5. import java.io.InputStreamReader;
  6. import java.net.HttpURLConnection;
  7. import java.net.URL;
  8. import java.util.logging.Logger;
  9.  
  10. /**
  11. *
  12. * @author Alex
  13. * references :http://stackoverflow.com/questions/1051004/how-to-send-put-delete-http-request-in-httpurlconnection
  14. * initial author:http://stackoverflow.com/users/4023/matthew-murdoch
  15. */
  16. public class HttpUtil {
  17.  
  18. private int codestatus;
  19.  
  20. public int getCodestatus() {
  21. return codestatus;
  22. }
  23.  
  24. public String httpMetodo(String url, String type, String reqbody) {
  25.  
  26. HttpURLConnection con = null;
  27. String jsonresultado = null;
  28.  
  29. try {
  30. con = getHttpConnection(url, type);
  31.  
  32. if (reqbody != null) {
  33. con.setDoInput(true);
  34. con.setDoOutput(true);
  35. try (DataOutputStream out = new DataOutputStream(con.getOutputStream())) {
  36. out.writeBytes(reqbody);
  37. out.flush();
  38. }
  39.  
  40. }
  41. con.connect();
  42. this.codestatus = con.getResponseCode();
  43.  
  44. try (BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()))) {
  45. String temp = null;
  46. StringBuilder sb = new StringBuilder();
  47. while ((temp = in.readLine()) != null) {
  48. sb.append(temp).append(" ");
  49. }
  50. jsonresultado = sb.toString();
  51. in.close();
  52. }
  53. } catch (Exception e) {
  54. Logger.getLogger(e.getMessage());
  55.  
  56. }
  57. return jsonresultado;
  58. }
  59.  
  60. private HttpURLConnection getHttpConnection(String url, String type) {
  61. URL uri = null;
  62. HttpURLConnection conexao = null;
  63. try {
  64. uri = new URL(url);
  65. conexao = (HttpURLConnection) uri.openConnection();
  66. conexao.setRequestMethod(type); //type: POST, PUT, DELETE, GET
  67. conexao.setDoOutput(true);
  68. conexao.setDoInput(true);
  69. conexao.setConnectTimeout(60000); //60 secs
  70. conexao.setReadTimeout(60000); //60 secs
  71. conexao.setRequestProperty("Accept-Encoding", "UTF-8");
  72. conexao.setRequestProperty("Content-Type", "application/json");
  73. } catch (Exception e) {
  74. Logger.getLogger("erro"+e.getMessage());
  75. }
  76. return conexao;
  77. }
  78.  
  79. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement