Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- String res = null;
- HttpURLConnection conn;
- try {
- // Set this to a string to send post data.
- String postData = null;
- // Open the connection
- conn = (HttpURLConnection)(new URL("http://inspirontrance.com/app.php")).openConnection();
- // Optionally set a timeout for the request:
- // conn.setConnectTimeout(10000); // 10 seconds
- // Add headers:
- // conn.addRequestProperty("Cookie", "a=b");
- // Replace a header: (use this when you don't have multiple headers with the same key, eg. Cookie)
- // conn.setRequestProperty("Authorization", "AuthHeader Value");
- if(postData != null) { // If post data is set
- // Set the method to POST
- conn.setRequestMethod("POST");
- // Allow us to write to the connection
- conn.setDoOutput(true);
- // Write
- OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());
- writer.write(postData);
- writer.flush();
- // A little trick, using Scanner for converting the input stream to a string
- Scanner s = new Scanner(conn.getInputStream());
- s.useDelimiter("\\A");
- res = s.hasNext() ? s.next() : "";
- s.close();
- }
- else { // No post data, do simple GET.
- conn.setRequestMethod("GET");
- // Scanner trick
- Scanner s = new Scanner(conn.getInputStream());
- s.useDelimiter("\\A");
- res = s.hasNext() ? s.next() : "";
- s.close();
- }
- } catch (MalformedURLException e) {
- // The URL is not valid
- return;
- } catch (IOException e) {
- // Something went wrong with the connection
- try {
- // Trying to read the HTTP status code, 404 for example
- int statusCode = conn.getResponseCode();
- // Do something with the status code here. Or don't.
- } catch (IOException e1) {}
- return;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement