Java HTTP Post postRaw(URL url, String params)

Here you can find the source of postRaw(URL url, String params)

Description

Posts the given string to the URL

License

Open Source License

Parameter

Parameter Description
url the URL to post to
params the data to post

Exception

Parameter Description
IOException if there was a problem posting to the URL

Return

the response retrieved from the URL

Declaration

public static String postRaw(URL url, String params) throws IOException 

Method Source Code


//package com.java2s;
//License from project: Open Source License 

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

public class Main {
    /**/*from  w w  w.  j  a  va  2 s .  com*/
     * Posts the given string to the URL
     * 
     * @param url
     *            the URL to post to
     * @param params
     *            the data to post
     * @return the response retrieved from the URL
     * @throws IOException
     *             if there was a problem posting to the URL
     */
    public static String postRaw(URL url, String params) throws IOException {
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("POST");
        connection.setRequestProperty("User-Agent", "Mozilla/5.0");
        connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

        connection.setRequestProperty("Content-Length", "" + Integer.toString(params.getBytes().length));

        connection.setUseCaches(false);
        connection.setDoInput(true);
        connection.setDoOutput(true);

        //Send Post
        DataOutputStream wr = new DataOutputStream(connection.getOutputStream());
        wr.writeBytes(params);
        wr.flush();
        wr.close();

        //Get Response
        BufferedReader rd = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        StringBuilder response = new StringBuilder();
        String line;
        while ((line = rd.readLine()) != null) {
            response.append(line);
            response.append('\r');
        }
        rd.close();
        return response.toString();
    }
}

Related

  1. postCall(JsonObject json, String url)
  2. postData(Reader data, URL endpoint, Writer output)
  3. postForm(String url, Map params)
  4. postHTTPQuery(String url, String urlParameters)
  5. postJSON(JSONObject job, HttpURLConnection conn)
  6. postURL(final URL url, final String request)
  7. put(String url, String content)
  8. put(URL host, String endpoint, String customer, String name, String version, InputStream in)
  9. putPOST(HttpURLConnection h, String query)