Advertisement
frostblooded

Fixed Java POST request

Dec 29th, 2015
336
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.12 KB | None | 0 0
  1. package <package>;
  2.  
  3. import android.util.Log;
  4.  
  5. import org.json.JSONObject;
  6.  
  7. import java.io.BufferedReader;
  8. import java.io.DataOutputStream;
  9. import java.io.InputStream;
  10. import java.io.InputStreamReader;
  11. import java.net.HttpURLConnection;
  12. import java.net.URL;
  13. import java.net.URLEncoder;
  14.  
  15. public class HttpClient {
  16.     public static String sendToken(String token){
  17.         URL url;
  18.         HttpURLConnection connection = null;
  19.         try {
  20.             JSONObject json = new JSONObject();
  21.             json.put("token", token);
  22.             byte[] sent_info = json.toString().getBytes();
  23.  
  24.             //Create connection
  25.             url = new URL("<url>/register_token");
  26.             connection = (HttpURLConnection)url.openConnection();
  27.             connection.setRequestMethod("POST");
  28.             connection.setRequestProperty("Content-Type", "application/json");
  29.  
  30.             connection.setRequestProperty("Content-Length", "" +
  31.                     Integer.toString(sent_info.length));
  32.             connection.setRequestProperty("Content-Language", "en-US");
  33.  
  34.             connection.setUseCaches (false);
  35.             connection.setDoInput(true);
  36.             connection.setDoOutput(true);
  37.  
  38.             // Send POST output.
  39.             DataOutputStream printout = new DataOutputStream(connection.getOutputStream());
  40.             printout.write(sent_info);
  41.             printout.flush();
  42.             printout.close();
  43.  
  44.             //Get Response
  45.             InputStream is = connection.getInputStream();
  46.             BufferedReader rd = new BufferedReader(new InputStreamReader(is));
  47.             String line;
  48.             StringBuffer response = new StringBuffer();
  49.  
  50.             while((line = rd.readLine()) != null) {
  51.                 response.append(line);
  52.                 response.append('\r');
  53.             }
  54.  
  55.             rd.close();
  56.             return response.toString();
  57.  
  58.         } catch (Exception e) {
  59.             Log.i(MainActivity.TAG, e.getMessage());
  60.             return null;
  61.         } finally {
  62.             if(connection != null) {
  63.                 connection.disconnect();
  64.             }
  65.         }
  66.     }
  67. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement