Java HTTP Request getDataFromRequestViaPost(String request, String urlParameters)

Here you can find the source of getDataFromRequestViaPost(String request, String urlParameters)

Description

Gets data using HTTP POST method.

License

Open Source License

Parameter

Parameter Description
request Base URL
urlParameters Parameters

Exception

Parameter Description
MalformedURLException an exception
IOException an exception

Return

Data from the request

Declaration

public static String getDataFromRequestViaPost(String request, String urlParameters)
        throws MalformedURLException, IOException 

Method Source Code

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

import java.io.DataOutputStream;

import java.io.IOException;

import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import java.util.Scanner;

public class Main {
    /**/*w ww  . j a v  a  2 s . c  o  m*/
     * Gets data using HTTP POST method.
     * 
     * @param request Base URL
     * @param urlParameters Parameters
     * @return Data from the request
     * @throws MalformedURLException
     * @throws IOException 
     */
    public static String getDataFromRequestViaPost(String request, String urlParameters)
            throws MalformedURLException, IOException {

        HttpURLConnection con = (HttpURLConnection) new URL(request).openConnection();
        con.setDoOutput(true);
        con.setDoInput(true);
        con.setInstanceFollowRedirects(false);
        con.setRequestMethod("POST");
        con.setRequestProperty("charset", "utf-8");
        con.setRequestProperty("Content-Length", Integer.toString(urlParameters.getBytes().length));
        con.setUseCaches(false);

        try (DataOutputStream wr = new DataOutputStream(con.getOutputStream())) {
            wr.writeBytes(urlParameters);
            wr.flush();
        }

        StringBuilder data = new StringBuilder();

        try (Scanner scan = new Scanner(con.getInputStream())) {
            while (scan.hasNextLine()) {
                data.append(scan.nextLine()).append("\n");
            }
        }

        con.disconnect();

        return data.toString();

    }
}

Related

  1. addRequestProperties(final Map requestProperties, final HttpURLConnection connection)
  2. doHttpRequest(String action, URL url, String body, String... args)
  3. getContent(String requestUrl)
  4. getOutputFromUrlConnection(String stringUrl, String requestProperty)
  5. getRequest(String urlString)
  6. getRequest(URL url, int timeout)
  7. getRequestContent(String urlText)