Advertisement
jovenb

Java HTTP Post request

May 26th, 2015
247
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.63 KB | None | 0 0
  1.     public static String excutePost(String targetURL, String urlParameters) {
  2.         HttpURLConnection connection = null;
  3.         try {
  4.             //Create connection
  5.             URL url = new URL(targetURL);
  6.             connection = (HttpURLConnection) url.openConnection();
  7.             connection.setRequestMethod("POST");
  8.             connection.setRequestProperty("Content-Type",
  9.                     "application/x-www-form-urlencoded");
  10.  
  11.             connection.setRequestProperty("Content-Length", Integer.toString(urlParameters.getBytes().length));
  12.             connection.setRequestProperty("Content-Language", "en-US");
  13.  
  14.             connection.setUseCaches(false);
  15.             connection.setDoOutput(true);
  16.  
  17.             //Send request
  18.             DataOutputStream wr = new DataOutputStream(
  19.                     connection.getOutputStream());
  20.             wr.writeBytes(urlParameters);
  21.             wr.close();
  22.  
  23.             //Get Response  
  24.             InputStream is = connection.getInputStream();
  25.             BufferedReader rd = new BufferedReader(new InputStreamReader(is));
  26.             StringBuilder response = new StringBuilder(); // or StringBuffer if not Java 5+
  27.             String line;
  28.             while ((line = rd.readLine()) != null) {
  29.                 response.append(line);
  30.                 response.append('\r');
  31.             }
  32.             rd.close();
  33.             return response.toString();
  34.         } catch (Exception e) {
  35.             e.printStackTrace();
  36.             return null;
  37.         } finally {
  38.             if (connection != null) {
  39.                 connection.disconnect();
  40.             }
  41.         }
  42.     }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement