Advertisement
tommasov

HTTP POST

Nov 10th, 2020 (edited)
1,199
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.79 KB | None | 0 0
  1. public class httpPost {
  2.  
  3.     private String response = null;
  4.     private String URL      = "https://mio url";
  5.  
  6.     public String invio() {
  7.  
  8.         StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
  9.         StrictMode.setThreadPolicy(policy);
  10.  
  11.         try {
  12.             URL url = new URL(URL);
  13.  
  14.             HttpURLConnection conn = (HttpURLConnection) url.openConnection();
  15.             conn.setRequestMethod("POST");
  16.             conn.setDoInput(true);
  17.             conn.setDoOutput(true);
  18.  
  19.             Uri.Builder builder = new Uri.Builder();
  20.  
  21.         //Parametri da passare 
  22.             builder.appendQueryParameter("chiave1", "valore1");
  23.             builder.appendQueryParameter("chiave2", "valore2");
  24.             builder.appendQueryParameter("chiave3", "valore3");
  25.             builder.appendQueryParameter("chiave4", "valore4");
  26.  
  27.             String query = builder.build().getEncodedQuery();
  28.  
  29.             OutputStream os = conn.getOutputStream();
  30.             BufferedWriter writer = new BufferedWriter(
  31.                     new OutputStreamWriter(os, StandardCharsets.UTF_8));
  32.             writer.write(query);
  33.             writer.flush();
  34.             writer.close();
  35.  
  36.             InputStream in = new BufferedInputStream(conn.getInputStream());
  37.             response = http.InputStreamToString(in);
  38.  
  39.         } catch (MalformedURLException e) {
  40.             Log.e("HTTP", "MalformedURLException: " + e.getMessage());
  41.         } catch (ProtocolException e) {
  42.             Log.e("HTTP", "ProtocolException: " + e.getMessage());
  43.         } catch (IOException e) {
  44.             Log.e("HTTP", "IOException: " + e.getMessage());
  45.         } catch (Exception e) {
  46.             Log.e("HTTP", "Exception: " + e.getMessage());
  47.         }
  48.  
  49.         return response;
  50.     }
  51. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement