Advertisement
_Tobias

HTTP Request in Java

Sep 3rd, 2013
103
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.67 KB | None | 0 0
  1. String res = null;
  2. HttpURLConnection conn;
  3.  
  4. try {
  5.     // Set this to a string to send post data.
  6.     String postData = null;
  7.  
  8.     // Open the connection
  9.     conn = (HttpURLConnection)(new URL("http://inspirontrance.com/app.php")).openConnection();
  10.  
  11.     // Optionally set a timeout for the request:
  12. //  conn.setConnectTimeout(10000); // 10 seconds
  13.  
  14.     // Add headers:
  15. //  conn.addRequestProperty("Cookie", "a=b");
  16.  
  17.     // Replace a header: (use this when you don't have multiple headers with the same key, eg. Cookie)
  18. //  conn.setRequestProperty("Authorization", "AuthHeader Value");
  19.  
  20.     if(postData != null) { // If post data is set
  21.         // Set the method to POST
  22.         conn.setRequestMethod("POST");
  23.  
  24.         // Allow us to write to the connection
  25.         conn.setDoOutput(true);
  26.        
  27.         // Write
  28.         OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());
  29.         writer.write(postData);
  30.         writer.flush();
  31.        
  32.         // A little trick, using Scanner for converting the input stream to a string
  33.         Scanner s = new Scanner(conn.getInputStream());
  34.         s.useDelimiter("\\A");
  35.         res = s.hasNext() ? s.next() : "";
  36.         s.close();
  37.     }
  38.     else { // No post data, do simple GET.
  39.         conn.setRequestMethod("GET");
  40.  
  41.         // Scanner trick
  42.         Scanner s = new Scanner(conn.getInputStream());
  43.         s.useDelimiter("\\A");
  44.         res = s.hasNext() ? s.next() : "";
  45.         s.close();
  46.     }
  47. } catch (MalformedURLException e) {
  48.     // The URL is not valid
  49.     return;
  50. } catch (IOException e) {
  51.     // Something went wrong with the connection
  52.     try {
  53.         // Trying to read the HTTP status code, 404 for example
  54.         int statusCode = conn.getResponseCode();
  55.  
  56.         // Do something with the status code here. Or don't.
  57.     } catch (IOException e1) {}
  58.     return;
  59. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement