Advertisement
NikitaKurtin

HttpRequest

Jul 30th, 2015
7,109
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 7.38 KB | None | 0 0
  1. //HttpRequest v1.4 Updated: 2017-04-28
  2. //needed imports:
  3. import java.io.BufferedReader;
  4. import java.io.BufferedWriter;
  5. import java.io.ByteArrayOutputStream;
  6. import java.io.IOException;
  7. import java.io.InputStream;
  8. import java.io.InputStreamReader;
  9. import java.io.OutputStream;
  10. import java.io.OutputStreamWriter;
  11. import java.net.HttpURLConnection;
  12. import java.net.MalformedURLException;
  13. import java.net.URL;
  14. import java.util.HashMap;
  15. import java.util.Map;
  16.  
  17. import org.json.JSONException;
  18. import org.json.JSONObject;
  19.  
  20. /**
  21.  * Since HttpClient,BasicNameValuePairs, etc...  are deprecated.
  22.  * I've searched for a good alternative, and couldn't find any. Eventually ended up writing my own solution, so I decided to share to those who needs it.
  23.  * Main goals: to make it intuitive, short, clean and reasonable.
  24.  * NOTE methods: .prepare(), preparePost(), withData(map) & withData(string) are build to allow caller to chain in different variations, examples:
  25.  *HttpRequest req=new HttpRequest("http://host:port/path");
  26.  *
  27.  *Example 1: //prepare Http Post request and send to "http://host:port/path" with data params name=Bubu and age=29, return true - if worked
  28.  *req.preparePost().withData("name=Bubu&age=29").send();
  29.  *
  30.  *Example 2: //prepare http get request,  send to "http://host:port/path" and read server's response as String
  31.  *req.prepare().sendAndReadString();
  32.  *
  33.  *Example 3: //prepare Http Post request and send to "http://host:port/path" with name=Bubu and age=29 and read server's response as JSONObject
  34.  *HashMap<String, String>params=new HashMap<>();
  35.  params.put("name", "Groot");
  36.  params.put("age", "29");
  37.  *req.preparePost().withData(params).sendAndReadJSON();
  38.  */
  39. public class HttpRequest {
  40.     //Supported HttpRequest methods
  41.     public static enum Method{
  42.         POST,PUT,DELETE,GET;
  43.     }
  44.     private URL url;
  45.     private HttpURLConnection con;
  46.     private OutputStream os;
  47.     //After instantiation, when opening connection - IOException can occur
  48.     public HttpRequest(URL url)throws IOException{
  49.         this.url=url;
  50.         con = (HttpURLConnection)this.url.openConnection();
  51.     }
  52.     //Can be instantiated with String representation of url, force caller to check for IOException which can be thrown
  53.     public HttpRequest(String url)throws IOException{ this(new URL(url)); }
  54.    
  55.     /**
  56.      * Sending connection and opening an output stream to server by pre-defined instance variable url
  57.      *
  58.      * @param method Method - indicates HTTP Method should be set
  59.      * @throws IOException - should be checked by caller
  60.      * */
  61.     private void prepareAll(Method method)throws IOException{
  62.         con.setDoInput(true);
  63.         con.setRequestMethod(method.name());
  64.         if(method==Method.POST||method==Method.PUT){
  65.             con.setDoOutput(true);
  66.             os = con.getOutputStream();
  67.         }
  68.     }
  69.     //prepare request in GET method
  70.     //@return HttpRequest this instance -> for chaining method @see line 22
  71.     public HttpRequest prepare() throws IOException{
  72.         prepareAll(Method.GET);
  73.         return this;
  74.     }
  75.     /**
  76.      * Prepares HttpRequest method with for given method, possible values: HttpRequest.Method.POST,
  77.      * HttpRequest.Method.PUT, HttpRequest.Method.GET & HttpRequest.Method.DELETE
  78.      *
  79.      * @param method HttpRequest.Method - nested enum HttpRequest.Method constant
  80.      * @return HttpRequest this instance -> for chaining method @see line 22
  81.      * @throws IOException - should be checked by caller
  82.      * */
  83.     public HttpRequest prepare(Method method)throws IOException{
  84.         prepareAll(method);
  85.         return this;
  86.     }
  87.     /**
  88.      * Adding request headers (standard format "Key":"Value")
  89.      *
  90.      * @param headers String variadic params in standard format "Key":"Value"
  91.      * @return HttpRequest this instance -> for chaining method @see line 22
  92.      * */
  93.     public HttpRequest withHeaders(String... headers){
  94.         for(int i=0,last=headers.length;i<last;i++) {
  95.             String[]h=headers[i].split("[:]");
  96.             con.setRequestProperty(h[0],h[1]);
  97.         }
  98.         return this;
  99.     }
  100.  
  101.     /**
  102.      * Writes query to open stream to server
  103.      *
  104.      * @param query String params in format of key1=v1&key2=v2 to open stream to server
  105.      * @return HttpRequest this instance -> for chaining method @see line 22
  106.      * @throws IOException - should be checked by caller
  107.      * */
  108.     public HttpRequest withData(String query) throws IOException{
  109.         BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
  110.         writer.write(query);
  111.         writer.close();
  112.         return this;
  113.     }
  114.     /**
  115.      * Builds query on format of key1=v1&key2=v2 from given hashMap structure
  116.      * for map: {name=Bubu, age=29} -> builds "name=Bubu&age=29"
  117.      * for map: {Iam=Groot} -> builds "Iam=Groot"
  118.      *
  119.      * @param params HashMap consists of key-> value pairs to build query from
  120.      * @return HttpRequest this instance -> for chaining method @see line 22
  121.      * @throws IOException - should be checked by caller
  122.      * */
  123.     public HttpRequest withData(HashMap<String,String> params) throws IOException{
  124.         StringBuilder result=new StringBuilder();
  125.         for(Map.Entry<String,String>entry : params.entrySet()){
  126.             result.append((result.length()>0?"&":"")+entry.getKey()+"="+entry.getValue());//appends: key=value (for first param) OR &key=value(second and more)
  127.         }
  128.         withData(result.toString());
  129.         return this;
  130.     }
  131.     /**
  132.      * Writes raw data byte [] to open stream
  133.      * @param data  byte[] raw Array of bytes
  134.      * @return HttpRequest this instance -> for chaining method @see line 22
  135.      * @throws IOException - should be checked by caller
  136.      * */
  137.     public HttpRequest withData(byte [] data)throws IOException{
  138.         os.write(data);
  139.         return this;
  140.     }
  141.     //When caller only need to send, and don't need String response from server
  142.     public int send() throws IOException{
  143.         return con.getResponseCode(); //return HTTP status code to indicate whether it successfully sent
  144.     }
  145.     /**
  146.      * Sending request to the server and pass to caller String as it received in response from server
  147.      *
  148.      * @return String printed from server's response
  149.      * @throws IOException - should be checked by caller
  150.      * */
  151.     public String sendAndReadString() throws IOException{
  152.         BufferedReader br=new BufferedReader(new InputStreamReader(con.getInputStream()));
  153.         StringBuilder response=new StringBuilder();
  154.         for(String line;(line=br.readLine())!=null;)response.append(line+"\n");
  155.         return response.toString();
  156.     }
  157.     /**
  158.      * Sending request to the server and pass to caller its raw contents in bytes as it received from server.
  159.      *
  160.      * @return byte[] from server's response
  161.      * @throws IOException - should be checked by caller
  162.      * */
  163.     public byte[] sendAndReadBytes() throws IOException{
  164.         byte[] buffer = new byte[8192];
  165.         InputStream is = con.getInputStream();
  166.         ByteArrayOutputStream output = new ByteArrayOutputStream();
  167.         for (int bytesRead;(bytesRead=is.read(buffer))>=0;)output.write(buffer, 0, bytesRead);
  168.         return output.toByteArray();
  169.     }
  170.     //JSONObject representation of String response from server
  171.     public JSONObject sendAndReadJSON() throws JSONException, IOException{
  172.         return new JSONObject(sendAndReadString());
  173.     }
  174. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement