Here you can find the source of getDataFromRequestViaPost(String request, String urlParameters)
Parameter | Description |
---|---|
request | Base URL |
urlParameters | Parameters |
Parameter | Description |
---|---|
MalformedURLException | an exception |
IOException | an exception |
public static String getDataFromRequestViaPost(String request, String urlParameters) throws MalformedURLException, IOException
//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(); } }