Java - sending HTTP parameters via POST method easily










287















I am successfully using this code to send HTTP requests with some parameters via GET method



void sendRequest(String request)

// i.e.: request = "http://example.com/index.php?param1=a&param2=b&param3=c";
URL url = new URL(request);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setInstanceFollowRedirects(false);
connection.setRequestMethod("GET");
connection.setRequestProperty("Content-Type", "text/plain");
connection.setRequestProperty("charset", "utf-8");
connection.connect();



Now I may need to send the parameters (i.e. param1, param2, param3) via POST method because they are very long.
I was thinking to add an extra parameter to that method (i.e. String httpMethod).



How can I change the code above as little as possible to be able to send paramters either via GET or POST?



I was hoping that changing



connection.setRequestMethod("GET");


to



connection.setRequestMethod("POST");


would have done the trick, but the parameters are still sent via GET method.



Has HttpURLConnection got any method that would help?
Is there any helpful Java construct?



Any help would be very much appreciated.










share|improve this question
























  • Post parameters are sent inside the http header section not in the URL. (your post url would be http://example.com/index.php)

    – dacwe
    Nov 17 '10 at 15:34







  • 2





    there is no method setRequestMethod in Java 1.6 defined: docs.oracle.com/javase/6/docs/api/java/net/URLConnection.html

    – ante.sabo
    Jul 5 '12 at 11:24






  • 2





    Cast it to Http(s)UrlConnection ....

    – Peter Kriens
    Jul 9 '12 at 14:52











  • extending the question! Does anyone has any clue how to send an attachment as post parameter ...

    – therealprashant
    Mar 23 '16 at 7:35






  • 1





    Why does the first code snippet start with the keyword "function"?

    – Llew Vallis
    Mar 29 '18 at 8:26















287















I am successfully using this code to send HTTP requests with some parameters via GET method



void sendRequest(String request)

// i.e.: request = "http://example.com/index.php?param1=a&param2=b&param3=c";
URL url = new URL(request);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setInstanceFollowRedirects(false);
connection.setRequestMethod("GET");
connection.setRequestProperty("Content-Type", "text/plain");
connection.setRequestProperty("charset", "utf-8");
connection.connect();



Now I may need to send the parameters (i.e. param1, param2, param3) via POST method because they are very long.
I was thinking to add an extra parameter to that method (i.e. String httpMethod).



How can I change the code above as little as possible to be able to send paramters either via GET or POST?



I was hoping that changing



connection.setRequestMethod("GET");


to



connection.setRequestMethod("POST");


would have done the trick, but the parameters are still sent via GET method.



Has HttpURLConnection got any method that would help?
Is there any helpful Java construct?



Any help would be very much appreciated.










share|improve this question
























  • Post parameters are sent inside the http header section not in the URL. (your post url would be http://example.com/index.php)

    – dacwe
    Nov 17 '10 at 15:34







  • 2





    there is no method setRequestMethod in Java 1.6 defined: docs.oracle.com/javase/6/docs/api/java/net/URLConnection.html

    – ante.sabo
    Jul 5 '12 at 11:24






  • 2





    Cast it to Http(s)UrlConnection ....

    – Peter Kriens
    Jul 9 '12 at 14:52











  • extending the question! Does anyone has any clue how to send an attachment as post parameter ...

    – therealprashant
    Mar 23 '16 at 7:35






  • 1





    Why does the first code snippet start with the keyword "function"?

    – Llew Vallis
    Mar 29 '18 at 8:26













287












287








287


159






I am successfully using this code to send HTTP requests with some parameters via GET method



void sendRequest(String request)

// i.e.: request = "http://example.com/index.php?param1=a&param2=b&param3=c";
URL url = new URL(request);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setInstanceFollowRedirects(false);
connection.setRequestMethod("GET");
connection.setRequestProperty("Content-Type", "text/plain");
connection.setRequestProperty("charset", "utf-8");
connection.connect();



Now I may need to send the parameters (i.e. param1, param2, param3) via POST method because they are very long.
I was thinking to add an extra parameter to that method (i.e. String httpMethod).



How can I change the code above as little as possible to be able to send paramters either via GET or POST?



I was hoping that changing



connection.setRequestMethod("GET");


to



connection.setRequestMethod("POST");


would have done the trick, but the parameters are still sent via GET method.



Has HttpURLConnection got any method that would help?
Is there any helpful Java construct?



Any help would be very much appreciated.










share|improve this question
















I am successfully using this code to send HTTP requests with some parameters via GET method



void sendRequest(String request)

// i.e.: request = "http://example.com/index.php?param1=a&param2=b&param3=c";
URL url = new URL(request);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setInstanceFollowRedirects(false);
connection.setRequestMethod("GET");
connection.setRequestProperty("Content-Type", "text/plain");
connection.setRequestProperty("charset", "utf-8");
connection.connect();



Now I may need to send the parameters (i.e. param1, param2, param3) via POST method because they are very long.
I was thinking to add an extra parameter to that method (i.e. String httpMethod).



How can I change the code above as little as possible to be able to send paramters either via GET or POST?



I was hoping that changing



connection.setRequestMethod("GET");


to



connection.setRequestMethod("POST");


would have done the trick, but the parameters are still sent via GET method.



Has HttpURLConnection got any method that would help?
Is there any helpful Java construct?



Any help would be very much appreciated.







java http post httpurlconnection






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited May 4 '18 at 16:19









Imaskar

1,3541425




1,3541425










asked Nov 17 '10 at 15:29









dandan

5,773185283




5,773185283












  • Post parameters are sent inside the http header section not in the URL. (your post url would be http://example.com/index.php)

    – dacwe
    Nov 17 '10 at 15:34







  • 2





    there is no method setRequestMethod in Java 1.6 defined: docs.oracle.com/javase/6/docs/api/java/net/URLConnection.html

    – ante.sabo
    Jul 5 '12 at 11:24






  • 2





    Cast it to Http(s)UrlConnection ....

    – Peter Kriens
    Jul 9 '12 at 14:52











  • extending the question! Does anyone has any clue how to send an attachment as post parameter ...

    – therealprashant
    Mar 23 '16 at 7:35






  • 1





    Why does the first code snippet start with the keyword "function"?

    – Llew Vallis
    Mar 29 '18 at 8:26

















  • Post parameters are sent inside the http header section not in the URL. (your post url would be http://example.com/index.php)

    – dacwe
    Nov 17 '10 at 15:34







  • 2





    there is no method setRequestMethod in Java 1.6 defined: docs.oracle.com/javase/6/docs/api/java/net/URLConnection.html

    – ante.sabo
    Jul 5 '12 at 11:24






  • 2





    Cast it to Http(s)UrlConnection ....

    – Peter Kriens
    Jul 9 '12 at 14:52











  • extending the question! Does anyone has any clue how to send an attachment as post parameter ...

    – therealprashant
    Mar 23 '16 at 7:35






  • 1





    Why does the first code snippet start with the keyword "function"?

    – Llew Vallis
    Mar 29 '18 at 8:26
















Post parameters are sent inside the http header section not in the URL. (your post url would be http://example.com/index.php)

– dacwe
Nov 17 '10 at 15:34






Post parameters are sent inside the http header section not in the URL. (your post url would be http://example.com/index.php)

– dacwe
Nov 17 '10 at 15:34





2




2





there is no method setRequestMethod in Java 1.6 defined: docs.oracle.com/javase/6/docs/api/java/net/URLConnection.html

– ante.sabo
Jul 5 '12 at 11:24





there is no method setRequestMethod in Java 1.6 defined: docs.oracle.com/javase/6/docs/api/java/net/URLConnection.html

– ante.sabo
Jul 5 '12 at 11:24




2




2





Cast it to Http(s)UrlConnection ....

– Peter Kriens
Jul 9 '12 at 14:52





Cast it to Http(s)UrlConnection ....

– Peter Kriens
Jul 9 '12 at 14:52













extending the question! Does anyone has any clue how to send an attachment as post parameter ...

– therealprashant
Mar 23 '16 at 7:35





extending the question! Does anyone has any clue how to send an attachment as post parameter ...

– therealprashant
Mar 23 '16 at 7:35




1




1





Why does the first code snippet start with the keyword "function"?

– Llew Vallis
Mar 29 '18 at 8:26





Why does the first code snippet start with the keyword "function"?

– Llew Vallis
Mar 29 '18 at 8:26












16 Answers
16






active

oldest

votes


















437














In a GET request, the parameters are sent as part of the URL.



In a POST request, the parameters are sent as a body of the request, after the headers.



To do a POST with HttpURLConnection, you need to write the parameters to the connection after you have opened the connection.



This code should get you started:



String urlParameters = "param1=a&param2=b&param3=c";
byte postData = urlParameters.getBytes( StandardCharsets.UTF_8 );
int postDataLength = postData.length;
String request = "http://example.com/index.php";
URL url = new URL( request );
HttpURLConnection conn= (HttpURLConnection) url.openConnection();
conn.setDoOutput( true );
conn.setInstanceFollowRedirects( false );
conn.setRequestMethod( "POST" );
conn.setRequestProperty( "Content-Type", "application/x-www-form-urlencoded");
conn.setRequestProperty( "charset", "utf-8");
conn.setRequestProperty( "Content-Length", Integer.toString( postDataLength ));
conn.setUseCaches( false );
try( DataOutputStream wr = new DataOutputStream( conn.getOutputStream()))
wr.write( postData );






share|improve this answer




















  • 37





    @Alan Geleynse : 'url.openconnection()' does not open connection. In case you do not specify a connect() statement the connection is opened when you write to to the http request body /heared and send it. I have tried this with certificates. The ssl handshake takes place only after you call connect or when you send a data to the server.

    – Ashwin
    Mar 23 '12 at 10:20






  • 12





    getBytes() uses default charaset of environment, NOT UTF-8 charset=utf-8 must follw the content type: application/x-www-form-urlencoded;charset=utf-8 You do byte conversion twice in the example. Should do: byte data = urlParameters.getData("UTF-8"); connection.getOutputStream().write(data); no use to close AND flush AND disconnect

    – Peter Kriens
    Jul 9 '12 at 15:00







  • 7





    @PeterKriens Thanks for your addition -- I believe you meant byte data = urlParameters.getBytes(Charset.forName("UTF-8")) :).

    – gerrytan
    Apr 15 '13 at 23:52







  • 5





    @AlanGeleynse Don't you miss wr.flush(); and wr.close(); at the end?

    – confile
    Apr 3 '15 at 22:13






  • 6





    How come this has so many upvotes, if it is not working? You need to call either conn.getResponseCode() or conn.getInputStream() otherwise it will not send any data.

    – Imaskar
    May 4 '18 at 13:02


















210














Here is a simple example that submits a form then dumps the result page to System.out. Change the URL and the POST params as appropriate, of course:



import java.io.*;
import java.net.*;
import java.util.*;

class Test
public static void main(String args) throws Exception
URL url = new URL("http://example.net/new-message.php");
Map<String,Object> params = new LinkedHashMap<>();
params.put("name", "Freddie the Fish");
params.put("email", "fishie@seamail.example.com");
params.put("reply_to_thread", 10394);
params.put("message", "Shark attacks in Botany Bay have gotten out of control. We need more defensive dolphins to protect the schools here, but Mayor Porpoise is too busy stuffing his snout with lobsters. He's so shellfish.");

StringBuilder postData = new StringBuilder();
for (Map.Entry<String,Object> param : params.entrySet())
if (postData.length() != 0) postData.append('&');
postData.append(URLEncoder.encode(param.getKey(), "UTF-8"));
postData.append('=');
postData.append(URLEncoder.encode(String.valueOf(param.getValue()), "UTF-8"));

byte postDataBytes = postData.toString().getBytes("UTF-8");

HttpURLConnection conn = (HttpURLConnection)url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setRequestProperty("Content-Length", String.valueOf(postDataBytes.length));
conn.setDoOutput(true);
conn.getOutputStream().write(postDataBytes);

Reader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));

for (int c; (c = in.read()) >= 0;)
System.out.print((char)c);





If you want the result as a String instead of directly printed out do:



 StringBuilder sb = new StringBuilder();
for (int c; (c = in.read()) >= 0;)
sb.append((char)c);
String response = sb.toString();





share|improve this answer




















  • 34





    +1 for being the only one to care about parameter encoding.

    – Giulio Piancastelli
    Mar 24 '14 at 16:40






  • 13





    +1 for a generic routine that uses Map.

    – Nathaniel Johnson
    Mar 28 '14 at 18:27






  • 3





    this is what i call code :)

    – Fareed Alnamrouti
    Aug 15 '14 at 19:33






  • 3





    Unfortunately this code assumes that the encoding of the content is UTF-8, which is not always the case. To retrieve the charset, one should get the header Content-Type and parse the charset of that. When that header is not available, use the standard http one: ISO-8859-1.

    – engineercoding
    Jan 4 '15 at 15:39






  • 1





    @Nepster Don't do that. response += line; is phenomenally slow, and it eats line breaks. I've added to the answer an example of getting a string response.

    – Boann
    Feb 28 '16 at 17:35



















60














I couldn't get Alan's example to actually do the post, so I ended up with this:



String urlParameters = "param1=a&param2=b&param3=c";
URL url = new URL("http://example.com/index.php");
URLConnection conn = url.openConnection();

conn.setDoOutput(true);

OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());

writer.write(urlParameters);
writer.flush();

String line;
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));

while ((line = reader.readLine()) != null)
System.out.println(line);

writer.close();
reader.close();





share|improve this answer




















  • 1





    Unfortunately, this code doesn't read the response. It reads the empty form html.

    – Kovács Imre
    Dec 26 '13 at 14:01











  • what i had to add to alan's example was opening response stream. before i had done it, no bytes were actually sent.

    – beefeather
    Mar 3 '14 at 0:46






  • 1





    Removing the writer.close() call did it for me.

    – Maxime T
    May 22 '15 at 10:42



















22














I find HttpURLConnection really cumbersome to use. And you have to write a lot of boilerplate, error prone code. I needed a lightweight wrapper for my Android projects and came out with a library which you can use as well: DavidWebb.



The above example could be written like this:



Webb webb = Webb.create();
webb.post("http://example.com/index.php")
.param("param1", "a")
.param("param2", "b")
.param("param3", "c")
.ensureSuccess()
.asVoid();


You can find a list of alternative libraries on the link provided.






share|improve this answer


















  • 1





    I'm not going to upvote because your post was less of an answer and more of an advert... but, I played with your library and I like it. Very succinct; lots of syntactical sugar; if you use Java as a bit of a scripting language as I do then it's a great library for very quickly and efficiently adding some http interactions. Zero boilerplate is valuable at times and it may have been useful to the OP.

    – Dean
    Jan 14 '14 at 9:01







  • 2





    I'll upvote. I've succesfully used DavidWebb in one of my apps, and will do so for two more I'll be developing soon. Very easy to use.

    – William T. Mallard
    Apr 29 '14 at 17:31











  • Thank you, using DefaultHttpClient with https on Android fails with SSLPeerUnverifiedException: No peer certificate (even on correctly signed https certificates), using URL is cumbersome (encoding parameters, checking for result). Using DavidWebb worked for me, thanks.

    – Martin Vysny
    Jan 28 '15 at 13:06











  • no AsyncTask support? So locking the UI thread by default...that's bad

    – slinden77
    Jun 26 '16 at 16:04











  • It's a very basic library. The programmer has to call it from background-thread, in AsyncTask, in IntentService, in Synchronization Handler and the like. And it doesn't depend on Android -> can be used in Java SE and EE as well.

    – hgoebl
    Jun 26 '16 at 16:49


















10














I see some other answers have given the alternative, I personally think that intuitively you're doing the right thing ;). Sorry, at devoxx where several speakers have been ranting about this sort of thing.



That's why I personally use Apache's HTTPClient/HttpCore libraries to do this sort of work, I find their API to be easier to use than Java's native HTTP support. YMMV of course!






share|improve this answer




















  • 1





    how to use ....

    – user1735921
    Nov 21 '18 at 7:38


















9














import java.net.*;

public class Demo

public static void main()

String data = "data=Hello+World!";
URL url = new URL("http://localhost:8084/WebListenerServer/webListener");
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("POST");
con.setDoOutput(true);
con.getOutputStream().write(data.getBytes("UTF-8"));
con.getInputStream();









share|improve this answer




















  • 4





    WTH import java.net.*;!

    – Yousha Aleayoub
    May 12 '16 at 11:14


















8














i have read above answers and have created a utility class to simplify HTTP request. i hope it will help you.



Method Call



 // send params with Hash Map
HashMap<String, String> params = new HashMap<String, String>();
params.put("email","me@example.com");
params.put("password","12345");

//server url
String url = "http://www.example.com";

// static class "HttpUtility" with static method "newRequest(url,method,callback)"
HttpUtility.newRequest(url,HttpUtility.METHOD_POST,params, new HttpUtility.Callback()
@Override
public void OnSuccess(String response)
// on success
System.out.println("Server OnSuccess response="+response);

@Override
public void OnError(int status_code, String message)
// on error
System.out.println("Server OnError status_code="+status_code+" message="+message);

);


Utility Class



import java.io.*;
import java.net.*;
import java.util.HashMap;
import java.util.Map;
import static java.net.HttpURLConnection.HTTP_OK;

public class HttpUtility

public static final int METHOD_GET = 0; // METHOD GET
public static final int METHOD_POST = 1; // METHOD POST

// Callback interface
public interface Callback
// abstract methods
public void OnSuccess(String response);
public void OnError(int status_code, String message);

// static method
public static void newRequest(String web_url, int method, HashMap < String, String > params, Callback callback)

// thread for handling async task
new Thread(new Runnable()
@Override
public void run()
try
String url = web_url;
// write GET params,append with url
if (method == METHOD_GET && params != null)
for (Map.Entry < String, String > item: params.entrySet())
String key = URLEncoder.encode(item.getKey(), "UTF-8");
String value = URLEncoder.encode(item.getValue(), "UTF-8");
if (!url.contains("?"))
url += "?" + key + "=" + value;
else
url += "&" + key + "=" + value;




HttpURLConnection urlConnection = (HttpURLConnection) new URL(url).openConnection();
urlConnection.setUseCaches(false);
urlConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); // handle url encoded form data
urlConnection.setRequestProperty("charset", "utf-8");
if (method == METHOD_GET)
urlConnection.setRequestMethod("GET");
else if (method == METHOD_POST)
urlConnection.setDoOutput(true); // write POST params
urlConnection.setRequestMethod("POST");


//write POST data
if (method == METHOD_POST && params != null)
StringBuilder postData = new StringBuilder();
for (Map.Entry < String, String > item: params.entrySet())
if (postData.length() != 0) postData.append('&');
postData.append(URLEncoder.encode(item.getKey(), "UTF-8"));
postData.append('=');
postData.append(URLEncoder.encode(String.valueOf(item.getValue()), "UTF-8"));

byte postDataBytes = postData.toString().getBytes("UTF-8");
urlConnection.setRequestProperty("Content-Length", String.valueOf(postDataBytes.length));
urlConnection.getOutputStream().write(postDataBytes);


// server response code
int responseCode = urlConnection.getResponseCode();
if (responseCode == HTTP_OK && callback != null)
BufferedReader reader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
StringBuilder response = new StringBuilder();
String line;
while ((line = reader.readLine()) != null)
response.append(line);

// callback success
callback.OnSuccess(response.toString());
reader.close(); // close BufferReader
else if (callback != null)
// callback error
callback.OnError(responseCode, urlConnection.getResponseMessage());


urlConnection.disconnect(); // disconnect connection
catch (IOException e)
e.printStackTrace();
if (callback != null)
// callback error
callback.OnError(500, e.getLocalizedMessage());



).start(); // start thread







share|improve this answer
































    5














    GET and POST method set like this... Two types for api calling 1)get() and 2) post() . get() method to get value from api json array to get value & post() method use in our data post in url and get response.



     public class HttpClientForExample 

    private final String USER_AGENT = "Mozilla/5.0";

    public static void main(String args) throws Exception

    HttpClientExample http = new HttpClientExample();

    System.out.println("Testing 1 - Send Http GET request");
    http.sendGet();

    System.out.println("nTesting 2 - Send Http POST request");
    http.sendPost();



    // HTTP GET request
    private void sendGet() throws Exception

    String url = "http://www.google.com/search?q=developer";

    HttpClient client = new DefaultHttpClient();
    HttpGet request = new HttpGet(url);

    // add request header
    request.addHeader("User-Agent", USER_AGENT);

    HttpResponse response = client.execute(request);

    System.out.println("nSending 'GET' request to URL : " + url);
    System.out.println("Response Code : " +
    response.getStatusLine().getStatusCode());

    BufferedReader rd = new BufferedReader(
    new InputStreamReader(response.getEntity().getContent()));

    StringBuffer result = new StringBuffer();
    String line = "";
    while ((line = rd.readLine()) != null)
    result.append(line);


    System.out.println(result.toString());



    // HTTP POST request
    private void sendPost() throws Exception

    String url = "https://selfsolve.apple.com/wcResults.do";

    HttpClient client = new DefaultHttpClient();
    HttpPost post = new HttpPost(url);

    // add header
    post.setHeader("User-Agent", USER_AGENT);

    List<NameValuePair> urlParameters = new ArrayList<NameValuePair>();
    urlParameters.add(new BasicNameValuePair("sn", "C02G8416DRJM"));
    urlParameters.add(new BasicNameValuePair("cn", ""));
    urlParameters.add(new BasicNameValuePair("locale", ""));
    urlParameters.add(new BasicNameValuePair("caller", ""));
    urlParameters.add(new BasicNameValuePair("num", "12345"));

    post.setEntity(new UrlEncodedFormEntity(urlParameters));

    HttpResponse response = client.execute(post);
    System.out.println("nSending 'POST' request to URL : " + url);
    System.out.println("Post parameters : " + post.getEntity());
    System.out.println("Response Code : " +
    response.getStatusLine().getStatusCode());

    BufferedReader rd = new BufferedReader(
    new InputStreamReader(response.getEntity().getContent()));

    StringBuffer result = new StringBuffer();
    String line = "";
    while ((line = rd.readLine()) != null)
    result.append(line);


    System.out.println(result.toString());









    share|improve this answer
































      3














      I had the same issue. I wanted to send data via POST.
      I used the following code:



       URL url = new URL("http://example.com/getval.php");
      Map<String,Object> params = new LinkedHashMap<>();
      params.put("param1", param1);
      params.put("param2", param2);

      StringBuilder postData = new StringBuilder();
      for (Map.Entry<String,Object> param : params.entrySet())
      if (postData.length() != 0) postData.append('&');
      postData.append(URLEncoder.encode(param.getKey(), "UTF-8"));
      postData.append('=');
      postData.append(URLEncoder.encode(String.valueOf(param.getValue()), "UTF-8"));

      String urlParameters = postData.toString();
      URLConnection conn = url.openConnection();

      conn.setDoOutput(true);

      OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());

      writer.write(urlParameters);
      writer.flush();

      String result = "";
      String line;
      BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));

      while ((line = reader.readLine()) != null)
      result += line;

      writer.close();
      reader.close()
      System.out.println(result);


      I used Jsoup for parse:



       Document doc = Jsoup.parseBodyFragment(value);
      Iterator<Element> opts = doc.select("option").iterator();
      for (;opts.hasNext();)
      Element item = opts.next();
      if (item.hasAttr("value"))
      System.out.println(item.attr("value"));







      share|improve this answer






























        3














        Try this pattern:



        public static PricesResponse getResponse(EventRequestRaw request) 

        // String urlParameters = "param1=a&param2=b&param3=c";
        String urlParameters = Piping.serialize(request);

        HttpURLConnection conn = RestClient.getPOSTConnection(endPoint, urlParameters);

        PricesResponse response = null;

        try
        // POST
        OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());
        writer.write(urlParameters);
        writer.flush();

        // RESPONSE
        BufferedReader reader = new BufferedReader(new InputStreamReader((conn.getInputStream()), StandardCharsets.UTF_8));
        String json = Buffering.getString(reader);
        response = (PricesResponse) Piping.deserialize(json, PricesResponse.class);

        writer.close();
        reader.close();

        catch (Exception e)
        e.printStackTrace();


        conn.disconnect();

        System.out.println("PricesClient: " + response.toString());

        return response;


        public static HttpURLConnection getPOSTConnection(String endPoint, String urlParameters)

        return RestClient.getConnection(endPoint, "POST", urlParameters);




        public static HttpURLConnection getConnection(String endPoint, String method, String urlParameters)

        System.out.println("ENDPOINT " + endPoint + " METHOD " + method);
        HttpURLConnection conn = null;

        try
        URL url = new URL(endPoint);
        conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod(method);
        conn.setDoOutput(true);
        conn.setRequestProperty("Content-Type", "text/plain");

        catch (IOException e)
        e.printStackTrace();


        return conn;






        share|improve this answer






























          2














          here i sent jsonobject as parameter //jsonobject="name":"lucifer","pass":"abc"//serverUrl = "http://192.168.100.12/testing" //host=192.168.100.12



           public static String getJson(String serverUrl,String host,String jsonobject)

          StringBuilder sb = new StringBuilder();

          String http = serverUrl;

          HttpURLConnection urlConnection = null;
          try
          URL url = new URL(http);
          urlConnection = (HttpURLConnection) url.openConnection();
          urlConnection.setDoOutput(true);
          urlConnection.setRequestMethod("POST");
          urlConnection.setUseCaches(false);
          urlConnection.setConnectTimeout(50000);
          urlConnection.setReadTimeout(50000);
          urlConnection.setRequestProperty("Content-Type", "application/json");
          urlConnection.setRequestProperty("Host", host);
          urlConnection.connect();
          //You Can also Create JSONObject here
          OutputStreamWriter out = new OutputStreamWriter(urlConnection.getOutputStream());
          out.write(jsonobject);// here i sent the parameter
          out.close();
          int HttpResult = urlConnection.getResponseCode();
          if (HttpResult == HttpURLConnection.HTTP_OK)
          BufferedReader br = new BufferedReader(new InputStreamReader(
          urlConnection.getInputStream(), "utf-8"));
          String line = null;
          while ((line = br.readLine()) != null)
          sb.append(line + "n");

          br.close();
          Log.e("new Test", "" + sb.toString());
          return sb.toString();
          else
          Log.e(" ", "" + urlConnection.getResponseMessage());

          catch (MalformedURLException e)
          e.printStackTrace();
          catch (IOException e)
          e.printStackTrace();
          catch (JSONException e)
          e.printStackTrace();
          finally
          if (urlConnection != null)
          urlConnection.disconnect();

          return null;






          share|improve this answer
































            2














            I higly recomend http-request built on apache http api.



            For your case you can see example:



            private static final HttpRequest<String.class> HTTP_REQUEST = 
            HttpRequestBuilder.createPost("http://example.com/index.php", String.class)
            .responseDeserializer(ResponseDeserializer.ignorableDeserializer())
            .build();

            public void sendRequest(String request)
            String parameters = request.split("\?")[1];
            ResponseHandler<String> responseHandler =
            HTTP_REQUEST.executeWithQuery(parameters);

            System.out.println(responseHandler.getStatusCode());
            System.out.println(responseHandler.get()); //prints response body



            If you are not interested in the response body



            private static final HttpRequest<?> HTTP_REQUEST = 
            HttpRequestBuilder.createPost("http://example.com/index.php").build();

            public void sendRequest(String request)
            ResponseHandler<String> responseHandler =
            HTTP_REQUEST.executeWithQuery(parameters);



            For general sending post request with http-request: Read the documentation and see my answers HTTP POST request with JSON String in JAVA, Sending HTTP POST Request In Java, HTTP POST using JSON in Java






            share|improve this answer






























              1














              Hello pls use this class to improve your post method



              public static JSONObject doPostRequest(HashMap<String, String> data, String url) UnsupportedEncodingException e) 

              JSONObject jsonObject=new JSONObject();

              try
              jsonObject.put("status","false");
              jsonObject.put("message",e.getLocalizedMessage());
              catch (JSONException e1)
              e1.printStackTrace();

              Log.e(TAG, "Error: " + e.getLocalizedMessage());
              catch (Exception e)
              e.printStackTrace();
              JSONObject jsonObject=new JSONObject();

              try
              jsonObject.put("status","false");
              jsonObject.put("message",e.getLocalizedMessage());
              catch (JSONException e1)
              e1.printStackTrace();

              Log.e(TAG, "Other Error: " + e.getLocalizedMessage());

              return null;






              share|improve this answer
































                1














                This answer covers the specific case of the POST Call using a Custom Java POJO.



                Using maven dependency for Gson to serialize our Java Object to JSON.



                Install Gson using the dependency below.



                <dependency>
                <groupId>com.google.code.gson</groupId>
                <artifactId>gson</artifactId>
                <version>2.8.5</version>
                <scope>compile</scope>
                </dependency>


                For those using gradle can use the below



                dependencies 
                implementation 'com.google.code.gson:gson:2.8.5'



                Other imports used:



                import org.apache.http.HttpResponse;
                import org.apache.http.client.methods.HttpPost;
                import org.apache.http.client.methods.CloseableHttpResponse;
                import org.apache.http.client.methods.HttpGet;
                import org.apache.http.client.methods.HttpPost;
                import org.apache.http.entity.*;
                import org.apache.http.impl.client.CloseableHttpClient;
                import com.google.gson.Gson;


                Now, we can go ahead and use the HttpPost provided by Apache



                private CloseableHttpClient httpclient = HttpClients.createDefault();
                HttpPost httppost = new HttpPost("https://example.com");

                Product product = new Product(); //custom java object to be posted as Request Body
                Gson gson = new Gson();
                String client = gson.toJson(product);

                httppost.setEntity(new StringEntity(client, ContentType.APPLICATION_JSON));
                httppost.setHeader("RANDOM-HEADER", "headervalue");
                //Execute and get the response.
                HttpResponse response = null;
                try
                response = httpclient.execute(httppost);
                catch (IOException e)
                throw new InternalServerErrorException("Post fails");

                Response.Status responseStatus = Response.Status.fromStatusCode(response.getStatusLine().getStatusCode());
                return Response.status(responseStatus).build();


                The above code will return with the response code received from the POST Call






                share|improve this answer






























                  0














                  I took Boann's answer and used it to create a more flexible query string builder that supports lists and arrays, just like php's http_build_query method:



                  public static byte httpBuildQueryString(Map<String, Object> postsData) throws UnsupportedEncodingException 
                  StringBuilder postData = new StringBuilder();
                  for (Map.Entry<String,Object> param : postsData.entrySet())
                  if (postData.length() != 0) postData.append('&');

                  Object value = param.getValue();
                  String key = param.getKey();

                  if(value instanceof Object
                  return postData.toString().getBytes("UTF-8");






                  share|improve this answer






























                    -3














                    Appears that you also have to callconnection.getOutputStream() "at least once" (as well as setDoOutput(true)) for it to treat it as a POST.



                    So the minimum required code is:



                     URL url = new URL(urlString);
                    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                    //connection.setRequestMethod("POST"); this doesn't seem to do anything at all..so not useful
                    connection.setDoOutput(true); // set it to POST...not enough by itself however, also need the getOutputStream call...
                    connection.connect();
                    connection.getOutputStream().close();


                    You can even use "GET" style parameters in the urlString, surprisingly. Though that might confuse things.



                    You can also use NameValuePair apparently.






                    share|improve this answer

























                    • Where are POST parameters... ?

                      – Yousha Aleayoub
                      Apr 18 '16 at 18:58











                    • Why are people downvoting this? It's a note for how to do POST's at all, though without parameters...(i.e. no payload0...

                      – rogerdpack
                      May 23 '18 at 23:15










                    protected by Community Nov 21 '18 at 11:58



                    Thank you for your interest in this question.
                    Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).



                    Would you like to answer one of these unanswered questions instead?














                    16 Answers
                    16






                    active

                    oldest

                    votes








                    16 Answers
                    16






                    active

                    oldest

                    votes









                    active

                    oldest

                    votes






                    active

                    oldest

                    votes









                    437














                    In a GET request, the parameters are sent as part of the URL.



                    In a POST request, the parameters are sent as a body of the request, after the headers.



                    To do a POST with HttpURLConnection, you need to write the parameters to the connection after you have opened the connection.



                    This code should get you started:



                    String urlParameters = "param1=a&param2=b&param3=c";
                    byte postData = urlParameters.getBytes( StandardCharsets.UTF_8 );
                    int postDataLength = postData.length;
                    String request = "http://example.com/index.php";
                    URL url = new URL( request );
                    HttpURLConnection conn= (HttpURLConnection) url.openConnection();
                    conn.setDoOutput( true );
                    conn.setInstanceFollowRedirects( false );
                    conn.setRequestMethod( "POST" );
                    conn.setRequestProperty( "Content-Type", "application/x-www-form-urlencoded");
                    conn.setRequestProperty( "charset", "utf-8");
                    conn.setRequestProperty( "Content-Length", Integer.toString( postDataLength ));
                    conn.setUseCaches( false );
                    try( DataOutputStream wr = new DataOutputStream( conn.getOutputStream()))
                    wr.write( postData );






                    share|improve this answer




















                    • 37





                      @Alan Geleynse : 'url.openconnection()' does not open connection. In case you do not specify a connect() statement the connection is opened when you write to to the http request body /heared and send it. I have tried this with certificates. The ssl handshake takes place only after you call connect or when you send a data to the server.

                      – Ashwin
                      Mar 23 '12 at 10:20






                    • 12





                      getBytes() uses default charaset of environment, NOT UTF-8 charset=utf-8 must follw the content type: application/x-www-form-urlencoded;charset=utf-8 You do byte conversion twice in the example. Should do: byte data = urlParameters.getData("UTF-8"); connection.getOutputStream().write(data); no use to close AND flush AND disconnect

                      – Peter Kriens
                      Jul 9 '12 at 15:00







                    • 7





                      @PeterKriens Thanks for your addition -- I believe you meant byte data = urlParameters.getBytes(Charset.forName("UTF-8")) :).

                      – gerrytan
                      Apr 15 '13 at 23:52







                    • 5





                      @AlanGeleynse Don't you miss wr.flush(); and wr.close(); at the end?

                      – confile
                      Apr 3 '15 at 22:13






                    • 6





                      How come this has so many upvotes, if it is not working? You need to call either conn.getResponseCode() or conn.getInputStream() otherwise it will not send any data.

                      – Imaskar
                      May 4 '18 at 13:02















                    437














                    In a GET request, the parameters are sent as part of the URL.



                    In a POST request, the parameters are sent as a body of the request, after the headers.



                    To do a POST with HttpURLConnection, you need to write the parameters to the connection after you have opened the connection.



                    This code should get you started:



                    String urlParameters = "param1=a&param2=b&param3=c";
                    byte postData = urlParameters.getBytes( StandardCharsets.UTF_8 );
                    int postDataLength = postData.length;
                    String request = "http://example.com/index.php";
                    URL url = new URL( request );
                    HttpURLConnection conn= (HttpURLConnection) url.openConnection();
                    conn.setDoOutput( true );
                    conn.setInstanceFollowRedirects( false );
                    conn.setRequestMethod( "POST" );
                    conn.setRequestProperty( "Content-Type", "application/x-www-form-urlencoded");
                    conn.setRequestProperty( "charset", "utf-8");
                    conn.setRequestProperty( "Content-Length", Integer.toString( postDataLength ));
                    conn.setUseCaches( false );
                    try( DataOutputStream wr = new DataOutputStream( conn.getOutputStream()))
                    wr.write( postData );






                    share|improve this answer




















                    • 37





                      @Alan Geleynse : 'url.openconnection()' does not open connection. In case you do not specify a connect() statement the connection is opened when you write to to the http request body /heared and send it. I have tried this with certificates. The ssl handshake takes place only after you call connect or when you send a data to the server.

                      – Ashwin
                      Mar 23 '12 at 10:20






                    • 12





                      getBytes() uses default charaset of environment, NOT UTF-8 charset=utf-8 must follw the content type: application/x-www-form-urlencoded;charset=utf-8 You do byte conversion twice in the example. Should do: byte data = urlParameters.getData("UTF-8"); connection.getOutputStream().write(data); no use to close AND flush AND disconnect

                      – Peter Kriens
                      Jul 9 '12 at 15:00







                    • 7





                      @PeterKriens Thanks for your addition -- I believe you meant byte data = urlParameters.getBytes(Charset.forName("UTF-8")) :).

                      – gerrytan
                      Apr 15 '13 at 23:52







                    • 5





                      @AlanGeleynse Don't you miss wr.flush(); and wr.close(); at the end?

                      – confile
                      Apr 3 '15 at 22:13






                    • 6





                      How come this has so many upvotes, if it is not working? You need to call either conn.getResponseCode() or conn.getInputStream() otherwise it will not send any data.

                      – Imaskar
                      May 4 '18 at 13:02













                    437












                    437








                    437







                    In a GET request, the parameters are sent as part of the URL.



                    In a POST request, the parameters are sent as a body of the request, after the headers.



                    To do a POST with HttpURLConnection, you need to write the parameters to the connection after you have opened the connection.



                    This code should get you started:



                    String urlParameters = "param1=a&param2=b&param3=c";
                    byte postData = urlParameters.getBytes( StandardCharsets.UTF_8 );
                    int postDataLength = postData.length;
                    String request = "http://example.com/index.php";
                    URL url = new URL( request );
                    HttpURLConnection conn= (HttpURLConnection) url.openConnection();
                    conn.setDoOutput( true );
                    conn.setInstanceFollowRedirects( false );
                    conn.setRequestMethod( "POST" );
                    conn.setRequestProperty( "Content-Type", "application/x-www-form-urlencoded");
                    conn.setRequestProperty( "charset", "utf-8");
                    conn.setRequestProperty( "Content-Length", Integer.toString( postDataLength ));
                    conn.setUseCaches( false );
                    try( DataOutputStream wr = new DataOutputStream( conn.getOutputStream()))
                    wr.write( postData );






                    share|improve this answer















                    In a GET request, the parameters are sent as part of the URL.



                    In a POST request, the parameters are sent as a body of the request, after the headers.



                    To do a POST with HttpURLConnection, you need to write the parameters to the connection after you have opened the connection.



                    This code should get you started:



                    String urlParameters = "param1=a&param2=b&param3=c";
                    byte postData = urlParameters.getBytes( StandardCharsets.UTF_8 );
                    int postDataLength = postData.length;
                    String request = "http://example.com/index.php";
                    URL url = new URL( request );
                    HttpURLConnection conn= (HttpURLConnection) url.openConnection();
                    conn.setDoOutput( true );
                    conn.setInstanceFollowRedirects( false );
                    conn.setRequestMethod( "POST" );
                    conn.setRequestProperty( "Content-Type", "application/x-www-form-urlencoded");
                    conn.setRequestProperty( "charset", "utf-8");
                    conn.setRequestProperty( "Content-Length", Integer.toString( postDataLength ));
                    conn.setUseCaches( false );
                    try( DataOutputStream wr = new DataOutputStream( conn.getOutputStream()))
                    wr.write( postData );







                    share|improve this answer














                    share|improve this answer



                    share|improve this answer








                    edited May 26 '15 at 3:37









                    Tim Biegeleisen

                    235k13100159




                    235k13100159










                    answered Nov 17 '10 at 15:40









                    Alan GeleynseAlan Geleynse

                    20.8k43854




                    20.8k43854







                    • 37





                      @Alan Geleynse : 'url.openconnection()' does not open connection. In case you do not specify a connect() statement the connection is opened when you write to to the http request body /heared and send it. I have tried this with certificates. The ssl handshake takes place only after you call connect or when you send a data to the server.

                      – Ashwin
                      Mar 23 '12 at 10:20






                    • 12





                      getBytes() uses default charaset of environment, NOT UTF-8 charset=utf-8 must follw the content type: application/x-www-form-urlencoded;charset=utf-8 You do byte conversion twice in the example. Should do: byte data = urlParameters.getData("UTF-8"); connection.getOutputStream().write(data); no use to close AND flush AND disconnect

                      – Peter Kriens
                      Jul 9 '12 at 15:00







                    • 7





                      @PeterKriens Thanks for your addition -- I believe you meant byte data = urlParameters.getBytes(Charset.forName("UTF-8")) :).

                      – gerrytan
                      Apr 15 '13 at 23:52







                    • 5





                      @AlanGeleynse Don't you miss wr.flush(); and wr.close(); at the end?

                      – confile
                      Apr 3 '15 at 22:13






                    • 6





                      How come this has so many upvotes, if it is not working? You need to call either conn.getResponseCode() or conn.getInputStream() otherwise it will not send any data.

                      – Imaskar
                      May 4 '18 at 13:02












                    • 37





                      @Alan Geleynse : 'url.openconnection()' does not open connection. In case you do not specify a connect() statement the connection is opened when you write to to the http request body /heared and send it. I have tried this with certificates. The ssl handshake takes place only after you call connect or when you send a data to the server.

                      – Ashwin
                      Mar 23 '12 at 10:20






                    • 12





                      getBytes() uses default charaset of environment, NOT UTF-8 charset=utf-8 must follw the content type: application/x-www-form-urlencoded;charset=utf-8 You do byte conversion twice in the example. Should do: byte data = urlParameters.getData("UTF-8"); connection.getOutputStream().write(data); no use to close AND flush AND disconnect

                      – Peter Kriens
                      Jul 9 '12 at 15:00







                    • 7





                      @PeterKriens Thanks for your addition -- I believe you meant byte data = urlParameters.getBytes(Charset.forName("UTF-8")) :).

                      – gerrytan
                      Apr 15 '13 at 23:52







                    • 5





                      @AlanGeleynse Don't you miss wr.flush(); and wr.close(); at the end?

                      – confile
                      Apr 3 '15 at 22:13






                    • 6





                      How come this has so many upvotes, if it is not working? You need to call either conn.getResponseCode() or conn.getInputStream() otherwise it will not send any data.

                      – Imaskar
                      May 4 '18 at 13:02







                    37




                    37





                    @Alan Geleynse : 'url.openconnection()' does not open connection. In case you do not specify a connect() statement the connection is opened when you write to to the http request body /heared and send it. I have tried this with certificates. The ssl handshake takes place only after you call connect or when you send a data to the server.

                    – Ashwin
                    Mar 23 '12 at 10:20





                    @Alan Geleynse : 'url.openconnection()' does not open connection. In case you do not specify a connect() statement the connection is opened when you write to to the http request body /heared and send it. I have tried this with certificates. The ssl handshake takes place only after you call connect or when you send a data to the server.

                    – Ashwin
                    Mar 23 '12 at 10:20




                    12




                    12





                    getBytes() uses default charaset of environment, NOT UTF-8 charset=utf-8 must follw the content type: application/x-www-form-urlencoded;charset=utf-8 You do byte conversion twice in the example. Should do: byte data = urlParameters.getData("UTF-8"); connection.getOutputStream().write(data); no use to close AND flush AND disconnect

                    – Peter Kriens
                    Jul 9 '12 at 15:00






                    getBytes() uses default charaset of environment, NOT UTF-8 charset=utf-8 must follw the content type: application/x-www-form-urlencoded;charset=utf-8 You do byte conversion twice in the example. Should do: byte data = urlParameters.getData("UTF-8"); connection.getOutputStream().write(data); no use to close AND flush AND disconnect

                    – Peter Kriens
                    Jul 9 '12 at 15:00





                    7




                    7





                    @PeterKriens Thanks for your addition -- I believe you meant byte data = urlParameters.getBytes(Charset.forName("UTF-8")) :).

                    – gerrytan
                    Apr 15 '13 at 23:52






                    @PeterKriens Thanks for your addition -- I believe you meant byte data = urlParameters.getBytes(Charset.forName("UTF-8")) :).

                    – gerrytan
                    Apr 15 '13 at 23:52





                    5




                    5





                    @AlanGeleynse Don't you miss wr.flush(); and wr.close(); at the end?

                    – confile
                    Apr 3 '15 at 22:13





                    @AlanGeleynse Don't you miss wr.flush(); and wr.close(); at the end?

                    – confile
                    Apr 3 '15 at 22:13




                    6




                    6





                    How come this has so many upvotes, if it is not working? You need to call either conn.getResponseCode() or conn.getInputStream() otherwise it will not send any data.

                    – Imaskar
                    May 4 '18 at 13:02





                    How come this has so many upvotes, if it is not working? You need to call either conn.getResponseCode() or conn.getInputStream() otherwise it will not send any data.

                    – Imaskar
                    May 4 '18 at 13:02













                    210














                    Here is a simple example that submits a form then dumps the result page to System.out. Change the URL and the POST params as appropriate, of course:



                    import java.io.*;
                    import java.net.*;
                    import java.util.*;

                    class Test
                    public static void main(String args) throws Exception
                    URL url = new URL("http://example.net/new-message.php");
                    Map<String,Object> params = new LinkedHashMap<>();
                    params.put("name", "Freddie the Fish");
                    params.put("email", "fishie@seamail.example.com");
                    params.put("reply_to_thread", 10394);
                    params.put("message", "Shark attacks in Botany Bay have gotten out of control. We need more defensive dolphins to protect the schools here, but Mayor Porpoise is too busy stuffing his snout with lobsters. He's so shellfish.");

                    StringBuilder postData = new StringBuilder();
                    for (Map.Entry<String,Object> param : params.entrySet())
                    if (postData.length() != 0) postData.append('&');
                    postData.append(URLEncoder.encode(param.getKey(), "UTF-8"));
                    postData.append('=');
                    postData.append(URLEncoder.encode(String.valueOf(param.getValue()), "UTF-8"));

                    byte postDataBytes = postData.toString().getBytes("UTF-8");

                    HttpURLConnection conn = (HttpURLConnection)url.openConnection();
                    conn.setRequestMethod("POST");
                    conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
                    conn.setRequestProperty("Content-Length", String.valueOf(postDataBytes.length));
                    conn.setDoOutput(true);
                    conn.getOutputStream().write(postDataBytes);

                    Reader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));

                    for (int c; (c = in.read()) >= 0;)
                    System.out.print((char)c);





                    If you want the result as a String instead of directly printed out do:



                     StringBuilder sb = new StringBuilder();
                    for (int c; (c = in.read()) >= 0;)
                    sb.append((char)c);
                    String response = sb.toString();





                    share|improve this answer




















                    • 34





                      +1 for being the only one to care about parameter encoding.

                      – Giulio Piancastelli
                      Mar 24 '14 at 16:40






                    • 13





                      +1 for a generic routine that uses Map.

                      – Nathaniel Johnson
                      Mar 28 '14 at 18:27






                    • 3





                      this is what i call code :)

                      – Fareed Alnamrouti
                      Aug 15 '14 at 19:33






                    • 3





                      Unfortunately this code assumes that the encoding of the content is UTF-8, which is not always the case. To retrieve the charset, one should get the header Content-Type and parse the charset of that. When that header is not available, use the standard http one: ISO-8859-1.

                      – engineercoding
                      Jan 4 '15 at 15:39






                    • 1





                      @Nepster Don't do that. response += line; is phenomenally slow, and it eats line breaks. I've added to the answer an example of getting a string response.

                      – Boann
                      Feb 28 '16 at 17:35
















                    210














                    Here is a simple example that submits a form then dumps the result page to System.out. Change the URL and the POST params as appropriate, of course:



                    import java.io.*;
                    import java.net.*;
                    import java.util.*;

                    class Test
                    public static void main(String args) throws Exception
                    URL url = new URL("http://example.net/new-message.php");
                    Map<String,Object> params = new LinkedHashMap<>();
                    params.put("name", "Freddie the Fish");
                    params.put("email", "fishie@seamail.example.com");
                    params.put("reply_to_thread", 10394);
                    params.put("message", "Shark attacks in Botany Bay have gotten out of control. We need more defensive dolphins to protect the schools here, but Mayor Porpoise is too busy stuffing his snout with lobsters. He's so shellfish.");

                    StringBuilder postData = new StringBuilder();
                    for (Map.Entry<String,Object> param : params.entrySet())
                    if (postData.length() != 0) postData.append('&');
                    postData.append(URLEncoder.encode(param.getKey(), "UTF-8"));
                    postData.append('=');
                    postData.append(URLEncoder.encode(String.valueOf(param.getValue()), "UTF-8"));

                    byte postDataBytes = postData.toString().getBytes("UTF-8");

                    HttpURLConnection conn = (HttpURLConnection)url.openConnection();
                    conn.setRequestMethod("POST");
                    conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
                    conn.setRequestProperty("Content-Length", String.valueOf(postDataBytes.length));
                    conn.setDoOutput(true);
                    conn.getOutputStream().write(postDataBytes);

                    Reader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));

                    for (int c; (c = in.read()) >= 0;)
                    System.out.print((char)c);





                    If you want the result as a String instead of directly printed out do:



                     StringBuilder sb = new StringBuilder();
                    for (int c; (c = in.read()) >= 0;)
                    sb.append((char)c);
                    String response = sb.toString();





                    share|improve this answer




















                    • 34





                      +1 for being the only one to care about parameter encoding.

                      – Giulio Piancastelli
                      Mar 24 '14 at 16:40






                    • 13





                      +1 for a generic routine that uses Map.

                      – Nathaniel Johnson
                      Mar 28 '14 at 18:27






                    • 3





                      this is what i call code :)

                      – Fareed Alnamrouti
                      Aug 15 '14 at 19:33






                    • 3





                      Unfortunately this code assumes that the encoding of the content is UTF-8, which is not always the case. To retrieve the charset, one should get the header Content-Type and parse the charset of that. When that header is not available, use the standard http one: ISO-8859-1.

                      – engineercoding
                      Jan 4 '15 at 15:39






                    • 1





                      @Nepster Don't do that. response += line; is phenomenally slow, and it eats line breaks. I've added to the answer an example of getting a string response.

                      – Boann
                      Feb 28 '16 at 17:35














                    210












                    210








                    210







                    Here is a simple example that submits a form then dumps the result page to System.out. Change the URL and the POST params as appropriate, of course:



                    import java.io.*;
                    import java.net.*;
                    import java.util.*;

                    class Test
                    public static void main(String args) throws Exception
                    URL url = new URL("http://example.net/new-message.php");
                    Map<String,Object> params = new LinkedHashMap<>();
                    params.put("name", "Freddie the Fish");
                    params.put("email", "fishie@seamail.example.com");
                    params.put("reply_to_thread", 10394);
                    params.put("message", "Shark attacks in Botany Bay have gotten out of control. We need more defensive dolphins to protect the schools here, but Mayor Porpoise is too busy stuffing his snout with lobsters. He's so shellfish.");

                    StringBuilder postData = new StringBuilder();
                    for (Map.Entry<String,Object> param : params.entrySet())
                    if (postData.length() != 0) postData.append('&');
                    postData.append(URLEncoder.encode(param.getKey(), "UTF-8"));
                    postData.append('=');
                    postData.append(URLEncoder.encode(String.valueOf(param.getValue()), "UTF-8"));

                    byte postDataBytes = postData.toString().getBytes("UTF-8");

                    HttpURLConnection conn = (HttpURLConnection)url.openConnection();
                    conn.setRequestMethod("POST");
                    conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
                    conn.setRequestProperty("Content-Length", String.valueOf(postDataBytes.length));
                    conn.setDoOutput(true);
                    conn.getOutputStream().write(postDataBytes);

                    Reader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));

                    for (int c; (c = in.read()) >= 0;)
                    System.out.print((char)c);





                    If you want the result as a String instead of directly printed out do:



                     StringBuilder sb = new StringBuilder();
                    for (int c; (c = in.read()) >= 0;)
                    sb.append((char)c);
                    String response = sb.toString();





                    share|improve this answer















                    Here is a simple example that submits a form then dumps the result page to System.out. Change the URL and the POST params as appropriate, of course:



                    import java.io.*;
                    import java.net.*;
                    import java.util.*;

                    class Test
                    public static void main(String args) throws Exception
                    URL url = new URL("http://example.net/new-message.php");
                    Map<String,Object> params = new LinkedHashMap<>();
                    params.put("name", "Freddie the Fish");
                    params.put("email", "fishie@seamail.example.com");
                    params.put("reply_to_thread", 10394);
                    params.put("message", "Shark attacks in Botany Bay have gotten out of control. We need more defensive dolphins to protect the schools here, but Mayor Porpoise is too busy stuffing his snout with lobsters. He's so shellfish.");

                    StringBuilder postData = new StringBuilder();
                    for (Map.Entry<String,Object> param : params.entrySet())
                    if (postData.length() != 0) postData.append('&');
                    postData.append(URLEncoder.encode(param.getKey(), "UTF-8"));
                    postData.append('=');
                    postData.append(URLEncoder.encode(String.valueOf(param.getValue()), "UTF-8"));

                    byte postDataBytes = postData.toString().getBytes("UTF-8");

                    HttpURLConnection conn = (HttpURLConnection)url.openConnection();
                    conn.setRequestMethod("POST");
                    conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
                    conn.setRequestProperty("Content-Length", String.valueOf(postDataBytes.length));
                    conn.setDoOutput(true);
                    conn.getOutputStream().write(postDataBytes);

                    Reader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));

                    for (int c; (c = in.read()) >= 0;)
                    System.out.print((char)c);





                    If you want the result as a String instead of directly printed out do:



                     StringBuilder sb = new StringBuilder();
                    for (int c; (c = in.read()) >= 0;)
                    sb.append((char)c);
                    String response = sb.toString();






                    share|improve this answer














                    share|improve this answer



                    share|improve this answer








                    edited Feb 28 '16 at 17:31

























                    answered Feb 9 '14 at 9:41









                    BoannBoann

                    37.4k1290121




                    37.4k1290121







                    • 34





                      +1 for being the only one to care about parameter encoding.

                      – Giulio Piancastelli
                      Mar 24 '14 at 16:40






                    • 13





                      +1 for a generic routine that uses Map.

                      – Nathaniel Johnson
                      Mar 28 '14 at 18:27






                    • 3





                      this is what i call code :)

                      – Fareed Alnamrouti
                      Aug 15 '14 at 19:33






                    • 3





                      Unfortunately this code assumes that the encoding of the content is UTF-8, which is not always the case. To retrieve the charset, one should get the header Content-Type and parse the charset of that. When that header is not available, use the standard http one: ISO-8859-1.

                      – engineercoding
                      Jan 4 '15 at 15:39






                    • 1





                      @Nepster Don't do that. response += line; is phenomenally slow, and it eats line breaks. I've added to the answer an example of getting a string response.

                      – Boann
                      Feb 28 '16 at 17:35













                    • 34





                      +1 for being the only one to care about parameter encoding.

                      – Giulio Piancastelli
                      Mar 24 '14 at 16:40






                    • 13





                      +1 for a generic routine that uses Map.

                      – Nathaniel Johnson
                      Mar 28 '14 at 18:27






                    • 3





                      this is what i call code :)

                      – Fareed Alnamrouti
                      Aug 15 '14 at 19:33






                    • 3





                      Unfortunately this code assumes that the encoding of the content is UTF-8, which is not always the case. To retrieve the charset, one should get the header Content-Type and parse the charset of that. When that header is not available, use the standard http one: ISO-8859-1.

                      – engineercoding
                      Jan 4 '15 at 15:39






                    • 1





                      @Nepster Don't do that. response += line; is phenomenally slow, and it eats line breaks. I've added to the answer an example of getting a string response.

                      – Boann
                      Feb 28 '16 at 17:35








                    34




                    34





                    +1 for being the only one to care about parameter encoding.

                    – Giulio Piancastelli
                    Mar 24 '14 at 16:40





                    +1 for being the only one to care about parameter encoding.

                    – Giulio Piancastelli
                    Mar 24 '14 at 16:40




                    13




                    13





                    +1 for a generic routine that uses Map.

                    – Nathaniel Johnson
                    Mar 28 '14 at 18:27





                    +1 for a generic routine that uses Map.

                    – Nathaniel Johnson
                    Mar 28 '14 at 18:27




                    3




                    3





                    this is what i call code :)

                    – Fareed Alnamrouti
                    Aug 15 '14 at 19:33





                    this is what i call code :)

                    – Fareed Alnamrouti
                    Aug 15 '14 at 19:33




                    3




                    3





                    Unfortunately this code assumes that the encoding of the content is UTF-8, which is not always the case. To retrieve the charset, one should get the header Content-Type and parse the charset of that. When that header is not available, use the standard http one: ISO-8859-1.

                    – engineercoding
                    Jan 4 '15 at 15:39





                    Unfortunately this code assumes that the encoding of the content is UTF-8, which is not always the case. To retrieve the charset, one should get the header Content-Type and parse the charset of that. When that header is not available, use the standard http one: ISO-8859-1.

                    – engineercoding
                    Jan 4 '15 at 15:39




                    1




                    1





                    @Nepster Don't do that. response += line; is phenomenally slow, and it eats line breaks. I've added to the answer an example of getting a string response.

                    – Boann
                    Feb 28 '16 at 17:35






                    @Nepster Don't do that. response += line; is phenomenally slow, and it eats line breaks. I've added to the answer an example of getting a string response.

                    – Boann
                    Feb 28 '16 at 17:35












                    60














                    I couldn't get Alan's example to actually do the post, so I ended up with this:



                    String urlParameters = "param1=a&param2=b&param3=c";
                    URL url = new URL("http://example.com/index.php");
                    URLConnection conn = url.openConnection();

                    conn.setDoOutput(true);

                    OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());

                    writer.write(urlParameters);
                    writer.flush();

                    String line;
                    BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));

                    while ((line = reader.readLine()) != null)
                    System.out.println(line);

                    writer.close();
                    reader.close();





                    share|improve this answer




















                    • 1





                      Unfortunately, this code doesn't read the response. It reads the empty form html.

                      – Kovács Imre
                      Dec 26 '13 at 14:01











                    • what i had to add to alan's example was opening response stream. before i had done it, no bytes were actually sent.

                      – beefeather
                      Mar 3 '14 at 0:46






                    • 1





                      Removing the writer.close() call did it for me.

                      – Maxime T
                      May 22 '15 at 10:42
















                    60














                    I couldn't get Alan's example to actually do the post, so I ended up with this:



                    String urlParameters = "param1=a&param2=b&param3=c";
                    URL url = new URL("http://example.com/index.php");
                    URLConnection conn = url.openConnection();

                    conn.setDoOutput(true);

                    OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());

                    writer.write(urlParameters);
                    writer.flush();

                    String line;
                    BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));

                    while ((line = reader.readLine()) != null)
                    System.out.println(line);

                    writer.close();
                    reader.close();





                    share|improve this answer




















                    • 1





                      Unfortunately, this code doesn't read the response. It reads the empty form html.

                      – Kovács Imre
                      Dec 26 '13 at 14:01











                    • what i had to add to alan's example was opening response stream. before i had done it, no bytes were actually sent.

                      – beefeather
                      Mar 3 '14 at 0:46






                    • 1





                      Removing the writer.close() call did it for me.

                      – Maxime T
                      May 22 '15 at 10:42














                    60












                    60








                    60







                    I couldn't get Alan's example to actually do the post, so I ended up with this:



                    String urlParameters = "param1=a&param2=b&param3=c";
                    URL url = new URL("http://example.com/index.php");
                    URLConnection conn = url.openConnection();

                    conn.setDoOutput(true);

                    OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());

                    writer.write(urlParameters);
                    writer.flush();

                    String line;
                    BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));

                    while ((line = reader.readLine()) != null)
                    System.out.println(line);

                    writer.close();
                    reader.close();





                    share|improve this answer















                    I couldn't get Alan's example to actually do the post, so I ended up with this:



                    String urlParameters = "param1=a&param2=b&param3=c";
                    URL url = new URL("http://example.com/index.php");
                    URLConnection conn = url.openConnection();

                    conn.setDoOutput(true);

                    OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());

                    writer.write(urlParameters);
                    writer.flush();

                    String line;
                    BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));

                    while ((line = reader.readLine()) != null)
                    System.out.println(line);

                    writer.close();
                    reader.close();






                    share|improve this answer














                    share|improve this answer



                    share|improve this answer








                    edited May 23 '17 at 12:26









                    Community

                    11




                    11










                    answered Nov 20 '12 at 7:41









                    CraigoCraigo

                    2,0611714




                    2,0611714







                    • 1





                      Unfortunately, this code doesn't read the response. It reads the empty form html.

                      – Kovács Imre
                      Dec 26 '13 at 14:01











                    • what i had to add to alan's example was opening response stream. before i had done it, no bytes were actually sent.

                      – beefeather
                      Mar 3 '14 at 0:46






                    • 1





                      Removing the writer.close() call did it for me.

                      – Maxime T
                      May 22 '15 at 10:42













                    • 1





                      Unfortunately, this code doesn't read the response. It reads the empty form html.

                      – Kovács Imre
                      Dec 26 '13 at 14:01











                    • what i had to add to alan's example was opening response stream. before i had done it, no bytes were actually sent.

                      – beefeather
                      Mar 3 '14 at 0:46






                    • 1





                      Removing the writer.close() call did it for me.

                      – Maxime T
                      May 22 '15 at 10:42








                    1




                    1





                    Unfortunately, this code doesn't read the response. It reads the empty form html.

                    – Kovács Imre
                    Dec 26 '13 at 14:01





                    Unfortunately, this code doesn't read the response. It reads the empty form html.

                    – Kovács Imre
                    Dec 26 '13 at 14:01













                    what i had to add to alan's example was opening response stream. before i had done it, no bytes were actually sent.

                    – beefeather
                    Mar 3 '14 at 0:46





                    what i had to add to alan's example was opening response stream. before i had done it, no bytes were actually sent.

                    – beefeather
                    Mar 3 '14 at 0:46




                    1




                    1





                    Removing the writer.close() call did it for me.

                    – Maxime T
                    May 22 '15 at 10:42






                    Removing the writer.close() call did it for me.

                    – Maxime T
                    May 22 '15 at 10:42












                    22














                    I find HttpURLConnection really cumbersome to use. And you have to write a lot of boilerplate, error prone code. I needed a lightweight wrapper for my Android projects and came out with a library which you can use as well: DavidWebb.



                    The above example could be written like this:



                    Webb webb = Webb.create();
                    webb.post("http://example.com/index.php")
                    .param("param1", "a")
                    .param("param2", "b")
                    .param("param3", "c")
                    .ensureSuccess()
                    .asVoid();


                    You can find a list of alternative libraries on the link provided.






                    share|improve this answer


















                    • 1





                      I'm not going to upvote because your post was less of an answer and more of an advert... but, I played with your library and I like it. Very succinct; lots of syntactical sugar; if you use Java as a bit of a scripting language as I do then it's a great library for very quickly and efficiently adding some http interactions. Zero boilerplate is valuable at times and it may have been useful to the OP.

                      – Dean
                      Jan 14 '14 at 9:01







                    • 2





                      I'll upvote. I've succesfully used DavidWebb in one of my apps, and will do so for two more I'll be developing soon. Very easy to use.

                      – William T. Mallard
                      Apr 29 '14 at 17:31











                    • Thank you, using DefaultHttpClient with https on Android fails with SSLPeerUnverifiedException: No peer certificate (even on correctly signed https certificates), using URL is cumbersome (encoding parameters, checking for result). Using DavidWebb worked for me, thanks.

                      – Martin Vysny
                      Jan 28 '15 at 13:06











                    • no AsyncTask support? So locking the UI thread by default...that's bad

                      – slinden77
                      Jun 26 '16 at 16:04











                    • It's a very basic library. The programmer has to call it from background-thread, in AsyncTask, in IntentService, in Synchronization Handler and the like. And it doesn't depend on Android -> can be used in Java SE and EE as well.

                      – hgoebl
                      Jun 26 '16 at 16:49















                    22














                    I find HttpURLConnection really cumbersome to use. And you have to write a lot of boilerplate, error prone code. I needed a lightweight wrapper for my Android projects and came out with a library which you can use as well: DavidWebb.



                    The above example could be written like this:



                    Webb webb = Webb.create();
                    webb.post("http://example.com/index.php")
                    .param("param1", "a")
                    .param("param2", "b")
                    .param("param3", "c")
                    .ensureSuccess()
                    .asVoid();


                    You can find a list of alternative libraries on the link provided.






                    share|improve this answer


















                    • 1





                      I'm not going to upvote because your post was less of an answer and more of an advert... but, I played with your library and I like it. Very succinct; lots of syntactical sugar; if you use Java as a bit of a scripting language as I do then it's a great library for very quickly and efficiently adding some http interactions. Zero boilerplate is valuable at times and it may have been useful to the OP.

                      – Dean
                      Jan 14 '14 at 9:01







                    • 2





                      I'll upvote. I've succesfully used DavidWebb in one of my apps, and will do so for two more I'll be developing soon. Very easy to use.

                      – William T. Mallard
                      Apr 29 '14 at 17:31











                    • Thank you, using DefaultHttpClient with https on Android fails with SSLPeerUnverifiedException: No peer certificate (even on correctly signed https certificates), using URL is cumbersome (encoding parameters, checking for result). Using DavidWebb worked for me, thanks.

                      – Martin Vysny
                      Jan 28 '15 at 13:06











                    • no AsyncTask support? So locking the UI thread by default...that's bad

                      – slinden77
                      Jun 26 '16 at 16:04











                    • It's a very basic library. The programmer has to call it from background-thread, in AsyncTask, in IntentService, in Synchronization Handler and the like. And it doesn't depend on Android -> can be used in Java SE and EE as well.

                      – hgoebl
                      Jun 26 '16 at 16:49













                    22












                    22








                    22







                    I find HttpURLConnection really cumbersome to use. And you have to write a lot of boilerplate, error prone code. I needed a lightweight wrapper for my Android projects and came out with a library which you can use as well: DavidWebb.



                    The above example could be written like this:



                    Webb webb = Webb.create();
                    webb.post("http://example.com/index.php")
                    .param("param1", "a")
                    .param("param2", "b")
                    .param("param3", "c")
                    .ensureSuccess()
                    .asVoid();


                    You can find a list of alternative libraries on the link provided.






                    share|improve this answer













                    I find HttpURLConnection really cumbersome to use. And you have to write a lot of boilerplate, error prone code. I needed a lightweight wrapper for my Android projects and came out with a library which you can use as well: DavidWebb.



                    The above example could be written like this:



                    Webb webb = Webb.create();
                    webb.post("http://example.com/index.php")
                    .param("param1", "a")
                    .param("param2", "b")
                    .param("param3", "c")
                    .ensureSuccess()
                    .asVoid();


                    You can find a list of alternative libraries on the link provided.







                    share|improve this answer












                    share|improve this answer



                    share|improve this answer










                    answered Jan 8 '14 at 9:13









                    hgoeblhgoebl

                    8,32553560




                    8,32553560







                    • 1





                      I'm not going to upvote because your post was less of an answer and more of an advert... but, I played with your library and I like it. Very succinct; lots of syntactical sugar; if you use Java as a bit of a scripting language as I do then it's a great library for very quickly and efficiently adding some http interactions. Zero boilerplate is valuable at times and it may have been useful to the OP.

                      – Dean
                      Jan 14 '14 at 9:01







                    • 2





                      I'll upvote. I've succesfully used DavidWebb in one of my apps, and will do so for two more I'll be developing soon. Very easy to use.

                      – William T. Mallard
                      Apr 29 '14 at 17:31











                    • Thank you, using DefaultHttpClient with https on Android fails with SSLPeerUnverifiedException: No peer certificate (even on correctly signed https certificates), using URL is cumbersome (encoding parameters, checking for result). Using DavidWebb worked for me, thanks.

                      – Martin Vysny
                      Jan 28 '15 at 13:06











                    • no AsyncTask support? So locking the UI thread by default...that's bad

                      – slinden77
                      Jun 26 '16 at 16:04











                    • It's a very basic library. The programmer has to call it from background-thread, in AsyncTask, in IntentService, in Synchronization Handler and the like. And it doesn't depend on Android -> can be used in Java SE and EE as well.

                      – hgoebl
                      Jun 26 '16 at 16:49












                    • 1





                      I'm not going to upvote because your post was less of an answer and more of an advert... but, I played with your library and I like it. Very succinct; lots of syntactical sugar; if you use Java as a bit of a scripting language as I do then it's a great library for very quickly and efficiently adding some http interactions. Zero boilerplate is valuable at times and it may have been useful to the OP.

                      – Dean
                      Jan 14 '14 at 9:01







                    • 2





                      I'll upvote. I've succesfully used DavidWebb in one of my apps, and will do so for two more I'll be developing soon. Very easy to use.

                      – William T. Mallard
                      Apr 29 '14 at 17:31











                    • Thank you, using DefaultHttpClient with https on Android fails with SSLPeerUnverifiedException: No peer certificate (even on correctly signed https certificates), using URL is cumbersome (encoding parameters, checking for result). Using DavidWebb worked for me, thanks.

                      – Martin Vysny
                      Jan 28 '15 at 13:06











                    • no AsyncTask support? So locking the UI thread by default...that's bad

                      – slinden77
                      Jun 26 '16 at 16:04











                    • It's a very basic library. The programmer has to call it from background-thread, in AsyncTask, in IntentService, in Synchronization Handler and the like. And it doesn't depend on Android -> can be used in Java SE and EE as well.

                      – hgoebl
                      Jun 26 '16 at 16:49







                    1




                    1





                    I'm not going to upvote because your post was less of an answer and more of an advert... but, I played with your library and I like it. Very succinct; lots of syntactical sugar; if you use Java as a bit of a scripting language as I do then it's a great library for very quickly and efficiently adding some http interactions. Zero boilerplate is valuable at times and it may have been useful to the OP.

                    – Dean
                    Jan 14 '14 at 9:01






                    I'm not going to upvote because your post was less of an answer and more of an advert... but, I played with your library and I like it. Very succinct; lots of syntactical sugar; if you use Java as a bit of a scripting language as I do then it's a great library for very quickly and efficiently adding some http interactions. Zero boilerplate is valuable at times and it may have been useful to the OP.

                    – Dean
                    Jan 14 '14 at 9:01





                    2




                    2





                    I'll upvote. I've succesfully used DavidWebb in one of my apps, and will do so for two more I'll be developing soon. Very easy to use.

                    – William T. Mallard
                    Apr 29 '14 at 17:31





                    I'll upvote. I've succesfully used DavidWebb in one of my apps, and will do so for two more I'll be developing soon. Very easy to use.

                    – William T. Mallard
                    Apr 29 '14 at 17:31













                    Thank you, using DefaultHttpClient with https on Android fails with SSLPeerUnverifiedException: No peer certificate (even on correctly signed https certificates), using URL is cumbersome (encoding parameters, checking for result). Using DavidWebb worked for me, thanks.

                    – Martin Vysny
                    Jan 28 '15 at 13:06





                    Thank you, using DefaultHttpClient with https on Android fails with SSLPeerUnverifiedException: No peer certificate (even on correctly signed https certificates), using URL is cumbersome (encoding parameters, checking for result). Using DavidWebb worked for me, thanks.

                    – Martin Vysny
                    Jan 28 '15 at 13:06













                    no AsyncTask support? So locking the UI thread by default...that's bad

                    – slinden77
                    Jun 26 '16 at 16:04





                    no AsyncTask support? So locking the UI thread by default...that's bad

                    – slinden77
                    Jun 26 '16 at 16:04













                    It's a very basic library. The programmer has to call it from background-thread, in AsyncTask, in IntentService, in Synchronization Handler and the like. And it doesn't depend on Android -> can be used in Java SE and EE as well.

                    – hgoebl
                    Jun 26 '16 at 16:49





                    It's a very basic library. The programmer has to call it from background-thread, in AsyncTask, in IntentService, in Synchronization Handler and the like. And it doesn't depend on Android -> can be used in Java SE and EE as well.

                    – hgoebl
                    Jun 26 '16 at 16:49











                    10














                    I see some other answers have given the alternative, I personally think that intuitively you're doing the right thing ;). Sorry, at devoxx where several speakers have been ranting about this sort of thing.



                    That's why I personally use Apache's HTTPClient/HttpCore libraries to do this sort of work, I find their API to be easier to use than Java's native HTTP support. YMMV of course!






                    share|improve this answer




















                    • 1





                      how to use ....

                      – user1735921
                      Nov 21 '18 at 7:38















                    10














                    I see some other answers have given the alternative, I personally think that intuitively you're doing the right thing ;). Sorry, at devoxx where several speakers have been ranting about this sort of thing.



                    That's why I personally use Apache's HTTPClient/HttpCore libraries to do this sort of work, I find their API to be easier to use than Java's native HTTP support. YMMV of course!






                    share|improve this answer




















                    • 1





                      how to use ....

                      – user1735921
                      Nov 21 '18 at 7:38













                    10












                    10








                    10







                    I see some other answers have given the alternative, I personally think that intuitively you're doing the right thing ;). Sorry, at devoxx where several speakers have been ranting about this sort of thing.



                    That's why I personally use Apache's HTTPClient/HttpCore libraries to do this sort of work, I find their API to be easier to use than Java's native HTTP support. YMMV of course!






                    share|improve this answer















                    I see some other answers have given the alternative, I personally think that intuitively you're doing the right thing ;). Sorry, at devoxx where several speakers have been ranting about this sort of thing.



                    That's why I personally use Apache's HTTPClient/HttpCore libraries to do this sort of work, I find their API to be easier to use than Java's native HTTP support. YMMV of course!







                    share|improve this answer














                    share|improve this answer



                    share|improve this answer








                    edited Nov 17 '10 at 15:57

























                    answered Nov 17 '10 at 15:40









                    Martijn VerburgMartijn Verburg

                    2,9611524




                    2,9611524







                    • 1





                      how to use ....

                      – user1735921
                      Nov 21 '18 at 7:38












                    • 1





                      how to use ....

                      – user1735921
                      Nov 21 '18 at 7:38







                    1




                    1





                    how to use ....

                    – user1735921
                    Nov 21 '18 at 7:38





                    how to use ....

                    – user1735921
                    Nov 21 '18 at 7:38











                    9














                    import java.net.*;

                    public class Demo

                    public static void main()

                    String data = "data=Hello+World!";
                    URL url = new URL("http://localhost:8084/WebListenerServer/webListener");
                    HttpURLConnection con = (HttpURLConnection) url.openConnection();
                    con.setRequestMethod("POST");
                    con.setDoOutput(true);
                    con.getOutputStream().write(data.getBytes("UTF-8"));
                    con.getInputStream();









                    share|improve this answer




















                    • 4





                      WTH import java.net.*;!

                      – Yousha Aleayoub
                      May 12 '16 at 11:14















                    9














                    import java.net.*;

                    public class Demo

                    public static void main()

                    String data = "data=Hello+World!";
                    URL url = new URL("http://localhost:8084/WebListenerServer/webListener");
                    HttpURLConnection con = (HttpURLConnection) url.openConnection();
                    con.setRequestMethod("POST");
                    con.setDoOutput(true);
                    con.getOutputStream().write(data.getBytes("UTF-8"));
                    con.getInputStream();









                    share|improve this answer




















                    • 4





                      WTH import java.net.*;!

                      – Yousha Aleayoub
                      May 12 '16 at 11:14













                    9












                    9








                    9







                    import java.net.*;

                    public class Demo

                    public static void main()

                    String data = "data=Hello+World!";
                    URL url = new URL("http://localhost:8084/WebListenerServer/webListener");
                    HttpURLConnection con = (HttpURLConnection) url.openConnection();
                    con.setRequestMethod("POST");
                    con.setDoOutput(true);
                    con.getOutputStream().write(data.getBytes("UTF-8"));
                    con.getInputStream();









                    share|improve this answer















                    import java.net.*;

                    public class Demo

                    public static void main()

                    String data = "data=Hello+World!";
                    URL url = new URL("http://localhost:8084/WebListenerServer/webListener");
                    HttpURLConnection con = (HttpURLConnection) url.openConnection();
                    con.setRequestMethod("POST");
                    con.setDoOutput(true);
                    con.getOutputStream().write(data.getBytes("UTF-8"));
                    con.getInputStream();










                    share|improve this answer














                    share|improve this answer



                    share|improve this answer








                    edited May 4 '18 at 18:14









                    Imaskar

                    1,3541425




                    1,3541425










                    answered May 2 '15 at 8:35









                    Manish MistryManish Mistry

                    11711




                    11711







                    • 4





                      WTH import java.net.*;!

                      – Yousha Aleayoub
                      May 12 '16 at 11:14












                    • 4





                      WTH import java.net.*;!

                      – Yousha Aleayoub
                      May 12 '16 at 11:14







                    4




                    4





                    WTH import java.net.*;!

                    – Yousha Aleayoub
                    May 12 '16 at 11:14





                    WTH import java.net.*;!

                    – Yousha Aleayoub
                    May 12 '16 at 11:14











                    8














                    i have read above answers and have created a utility class to simplify HTTP request. i hope it will help you.



                    Method Call



                     // send params with Hash Map
                    HashMap<String, String> params = new HashMap<String, String>();
                    params.put("email","me@example.com");
                    params.put("password","12345");

                    //server url
                    String url = "http://www.example.com";

                    // static class "HttpUtility" with static method "newRequest(url,method,callback)"
                    HttpUtility.newRequest(url,HttpUtility.METHOD_POST,params, new HttpUtility.Callback()
                    @Override
                    public void OnSuccess(String response)
                    // on success
                    System.out.println("Server OnSuccess response="+response);

                    @Override
                    public void OnError(int status_code, String message)
                    // on error
                    System.out.println("Server OnError status_code="+status_code+" message="+message);

                    );


                    Utility Class



                    import java.io.*;
                    import java.net.*;
                    import java.util.HashMap;
                    import java.util.Map;
                    import static java.net.HttpURLConnection.HTTP_OK;

                    public class HttpUtility

                    public static final int METHOD_GET = 0; // METHOD GET
                    public static final int METHOD_POST = 1; // METHOD POST

                    // Callback interface
                    public interface Callback
                    // abstract methods
                    public void OnSuccess(String response);
                    public void OnError(int status_code, String message);

                    // static method
                    public static void newRequest(String web_url, int method, HashMap < String, String > params, Callback callback)

                    // thread for handling async task
                    new Thread(new Runnable()
                    @Override
                    public void run()
                    try
                    String url = web_url;
                    // write GET params,append with url
                    if (method == METHOD_GET && params != null)
                    for (Map.Entry < String, String > item: params.entrySet())
                    String key = URLEncoder.encode(item.getKey(), "UTF-8");
                    String value = URLEncoder.encode(item.getValue(), "UTF-8");
                    if (!url.contains("?"))
                    url += "?" + key + "=" + value;
                    else
                    url += "&" + key + "=" + value;




                    HttpURLConnection urlConnection = (HttpURLConnection) new URL(url).openConnection();
                    urlConnection.setUseCaches(false);
                    urlConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); // handle url encoded form data
                    urlConnection.setRequestProperty("charset", "utf-8");
                    if (method == METHOD_GET)
                    urlConnection.setRequestMethod("GET");
                    else if (method == METHOD_POST)
                    urlConnection.setDoOutput(true); // write POST params
                    urlConnection.setRequestMethod("POST");


                    //write POST data
                    if (method == METHOD_POST && params != null)
                    StringBuilder postData = new StringBuilder();
                    for (Map.Entry < String, String > item: params.entrySet())
                    if (postData.length() != 0) postData.append('&');
                    postData.append(URLEncoder.encode(item.getKey(), "UTF-8"));
                    postData.append('=');
                    postData.append(URLEncoder.encode(String.valueOf(item.getValue()), "UTF-8"));

                    byte postDataBytes = postData.toString().getBytes("UTF-8");
                    urlConnection.setRequestProperty("Content-Length", String.valueOf(postDataBytes.length));
                    urlConnection.getOutputStream().write(postDataBytes);


                    // server response code
                    int responseCode = urlConnection.getResponseCode();
                    if (responseCode == HTTP_OK && callback != null)
                    BufferedReader reader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
                    StringBuilder response = new StringBuilder();
                    String line;
                    while ((line = reader.readLine()) != null)
                    response.append(line);

                    // callback success
                    callback.OnSuccess(response.toString());
                    reader.close(); // close BufferReader
                    else if (callback != null)
                    // callback error
                    callback.OnError(responseCode, urlConnection.getResponseMessage());


                    urlConnection.disconnect(); // disconnect connection
                    catch (IOException e)
                    e.printStackTrace();
                    if (callback != null)
                    // callback error
                    callback.OnError(500, e.getLocalizedMessage());



                    ).start(); // start thread







                    share|improve this answer





























                      8














                      i have read above answers and have created a utility class to simplify HTTP request. i hope it will help you.



                      Method Call



                       // send params with Hash Map
                      HashMap<String, String> params = new HashMap<String, String>();
                      params.put("email","me@example.com");
                      params.put("password","12345");

                      //server url
                      String url = "http://www.example.com";

                      // static class "HttpUtility" with static method "newRequest(url,method,callback)"
                      HttpUtility.newRequest(url,HttpUtility.METHOD_POST,params, new HttpUtility.Callback()
                      @Override
                      public void OnSuccess(String response)
                      // on success
                      System.out.println("Server OnSuccess response="+response);

                      @Override
                      public void OnError(int status_code, String message)
                      // on error
                      System.out.println("Server OnError status_code="+status_code+" message="+message);

                      );


                      Utility Class



                      import java.io.*;
                      import java.net.*;
                      import java.util.HashMap;
                      import java.util.Map;
                      import static java.net.HttpURLConnection.HTTP_OK;

                      public class HttpUtility

                      public static final int METHOD_GET = 0; // METHOD GET
                      public static final int METHOD_POST = 1; // METHOD POST

                      // Callback interface
                      public interface Callback
                      // abstract methods
                      public void OnSuccess(String response);
                      public void OnError(int status_code, String message);

                      // static method
                      public static void newRequest(String web_url, int method, HashMap < String, String > params, Callback callback)

                      // thread for handling async task
                      new Thread(new Runnable()
                      @Override
                      public void run()
                      try
                      String url = web_url;
                      // write GET params,append with url
                      if (method == METHOD_GET && params != null)
                      for (Map.Entry < String, String > item: params.entrySet())
                      String key = URLEncoder.encode(item.getKey(), "UTF-8");
                      String value = URLEncoder.encode(item.getValue(), "UTF-8");
                      if (!url.contains("?"))
                      url += "?" + key + "=" + value;
                      else
                      url += "&" + key + "=" + value;




                      HttpURLConnection urlConnection = (HttpURLConnection) new URL(url).openConnection();
                      urlConnection.setUseCaches(false);
                      urlConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); // handle url encoded form data
                      urlConnection.setRequestProperty("charset", "utf-8");
                      if (method == METHOD_GET)
                      urlConnection.setRequestMethod("GET");
                      else if (method == METHOD_POST)
                      urlConnection.setDoOutput(true); // write POST params
                      urlConnection.setRequestMethod("POST");


                      //write POST data
                      if (method == METHOD_POST && params != null)
                      StringBuilder postData = new StringBuilder();
                      for (Map.Entry < String, String > item: params.entrySet())
                      if (postData.length() != 0) postData.append('&');
                      postData.append(URLEncoder.encode(item.getKey(), "UTF-8"));
                      postData.append('=');
                      postData.append(URLEncoder.encode(String.valueOf(item.getValue()), "UTF-8"));

                      byte postDataBytes = postData.toString().getBytes("UTF-8");
                      urlConnection.setRequestProperty("Content-Length", String.valueOf(postDataBytes.length));
                      urlConnection.getOutputStream().write(postDataBytes);


                      // server response code
                      int responseCode = urlConnection.getResponseCode();
                      if (responseCode == HTTP_OK && callback != null)
                      BufferedReader reader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
                      StringBuilder response = new StringBuilder();
                      String line;
                      while ((line = reader.readLine()) != null)
                      response.append(line);

                      // callback success
                      callback.OnSuccess(response.toString());
                      reader.close(); // close BufferReader
                      else if (callback != null)
                      // callback error
                      callback.OnError(responseCode, urlConnection.getResponseMessage());


                      urlConnection.disconnect(); // disconnect connection
                      catch (IOException e)
                      e.printStackTrace();
                      if (callback != null)
                      // callback error
                      callback.OnError(500, e.getLocalizedMessage());



                      ).start(); // start thread







                      share|improve this answer



























                        8












                        8








                        8







                        i have read above answers and have created a utility class to simplify HTTP request. i hope it will help you.



                        Method Call



                         // send params with Hash Map
                        HashMap<String, String> params = new HashMap<String, String>();
                        params.put("email","me@example.com");
                        params.put("password","12345");

                        //server url
                        String url = "http://www.example.com";

                        // static class "HttpUtility" with static method "newRequest(url,method,callback)"
                        HttpUtility.newRequest(url,HttpUtility.METHOD_POST,params, new HttpUtility.Callback()
                        @Override
                        public void OnSuccess(String response)
                        // on success
                        System.out.println("Server OnSuccess response="+response);

                        @Override
                        public void OnError(int status_code, String message)
                        // on error
                        System.out.println("Server OnError status_code="+status_code+" message="+message);

                        );


                        Utility Class



                        import java.io.*;
                        import java.net.*;
                        import java.util.HashMap;
                        import java.util.Map;
                        import static java.net.HttpURLConnection.HTTP_OK;

                        public class HttpUtility

                        public static final int METHOD_GET = 0; // METHOD GET
                        public static final int METHOD_POST = 1; // METHOD POST

                        // Callback interface
                        public interface Callback
                        // abstract methods
                        public void OnSuccess(String response);
                        public void OnError(int status_code, String message);

                        // static method
                        public static void newRequest(String web_url, int method, HashMap < String, String > params, Callback callback)

                        // thread for handling async task
                        new Thread(new Runnable()
                        @Override
                        public void run()
                        try
                        String url = web_url;
                        // write GET params,append with url
                        if (method == METHOD_GET && params != null)
                        for (Map.Entry < String, String > item: params.entrySet())
                        String key = URLEncoder.encode(item.getKey(), "UTF-8");
                        String value = URLEncoder.encode(item.getValue(), "UTF-8");
                        if (!url.contains("?"))
                        url += "?" + key + "=" + value;
                        else
                        url += "&" + key + "=" + value;




                        HttpURLConnection urlConnection = (HttpURLConnection) new URL(url).openConnection();
                        urlConnection.setUseCaches(false);
                        urlConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); // handle url encoded form data
                        urlConnection.setRequestProperty("charset", "utf-8");
                        if (method == METHOD_GET)
                        urlConnection.setRequestMethod("GET");
                        else if (method == METHOD_POST)
                        urlConnection.setDoOutput(true); // write POST params
                        urlConnection.setRequestMethod("POST");


                        //write POST data
                        if (method == METHOD_POST && params != null)
                        StringBuilder postData = new StringBuilder();
                        for (Map.Entry < String, String > item: params.entrySet())
                        if (postData.length() != 0) postData.append('&');
                        postData.append(URLEncoder.encode(item.getKey(), "UTF-8"));
                        postData.append('=');
                        postData.append(URLEncoder.encode(String.valueOf(item.getValue()), "UTF-8"));

                        byte postDataBytes = postData.toString().getBytes("UTF-8");
                        urlConnection.setRequestProperty("Content-Length", String.valueOf(postDataBytes.length));
                        urlConnection.getOutputStream().write(postDataBytes);


                        // server response code
                        int responseCode = urlConnection.getResponseCode();
                        if (responseCode == HTTP_OK && callback != null)
                        BufferedReader reader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
                        StringBuilder response = new StringBuilder();
                        String line;
                        while ((line = reader.readLine()) != null)
                        response.append(line);

                        // callback success
                        callback.OnSuccess(response.toString());
                        reader.close(); // close BufferReader
                        else if (callback != null)
                        // callback error
                        callback.OnError(responseCode, urlConnection.getResponseMessage());


                        urlConnection.disconnect(); // disconnect connection
                        catch (IOException e)
                        e.printStackTrace();
                        if (callback != null)
                        // callback error
                        callback.OnError(500, e.getLocalizedMessage());



                        ).start(); // start thread







                        share|improve this answer















                        i have read above answers and have created a utility class to simplify HTTP request. i hope it will help you.



                        Method Call



                         // send params with Hash Map
                        HashMap<String, String> params = new HashMap<String, String>();
                        params.put("email","me@example.com");
                        params.put("password","12345");

                        //server url
                        String url = "http://www.example.com";

                        // static class "HttpUtility" with static method "newRequest(url,method,callback)"
                        HttpUtility.newRequest(url,HttpUtility.METHOD_POST,params, new HttpUtility.Callback()
                        @Override
                        public void OnSuccess(String response)
                        // on success
                        System.out.println("Server OnSuccess response="+response);

                        @Override
                        public void OnError(int status_code, String message)
                        // on error
                        System.out.println("Server OnError status_code="+status_code+" message="+message);

                        );


                        Utility Class



                        import java.io.*;
                        import java.net.*;
                        import java.util.HashMap;
                        import java.util.Map;
                        import static java.net.HttpURLConnection.HTTP_OK;

                        public class HttpUtility

                        public static final int METHOD_GET = 0; // METHOD GET
                        public static final int METHOD_POST = 1; // METHOD POST

                        // Callback interface
                        public interface Callback
                        // abstract methods
                        public void OnSuccess(String response);
                        public void OnError(int status_code, String message);

                        // static method
                        public static void newRequest(String web_url, int method, HashMap < String, String > params, Callback callback)

                        // thread for handling async task
                        new Thread(new Runnable()
                        @Override
                        public void run()
                        try
                        String url = web_url;
                        // write GET params,append with url
                        if (method == METHOD_GET && params != null)
                        for (Map.Entry < String, String > item: params.entrySet())
                        String key = URLEncoder.encode(item.getKey(), "UTF-8");
                        String value = URLEncoder.encode(item.getValue(), "UTF-8");
                        if (!url.contains("?"))
                        url += "?" + key + "=" + value;
                        else
                        url += "&" + key + "=" + value;




                        HttpURLConnection urlConnection = (HttpURLConnection) new URL(url).openConnection();
                        urlConnection.setUseCaches(false);
                        urlConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); // handle url encoded form data
                        urlConnection.setRequestProperty("charset", "utf-8");
                        if (method == METHOD_GET)
                        urlConnection.setRequestMethod("GET");
                        else if (method == METHOD_POST)
                        urlConnection.setDoOutput(true); // write POST params
                        urlConnection.setRequestMethod("POST");


                        //write POST data
                        if (method == METHOD_POST && params != null)
                        StringBuilder postData = new StringBuilder();
                        for (Map.Entry < String, String > item: params.entrySet())
                        if (postData.length() != 0) postData.append('&');
                        postData.append(URLEncoder.encode(item.getKey(), "UTF-8"));
                        postData.append('=');
                        postData.append(URLEncoder.encode(String.valueOf(item.getValue()), "UTF-8"));

                        byte postDataBytes = postData.toString().getBytes("UTF-8");
                        urlConnection.setRequestProperty("Content-Length", String.valueOf(postDataBytes.length));
                        urlConnection.getOutputStream().write(postDataBytes);


                        // server response code
                        int responseCode = urlConnection.getResponseCode();
                        if (responseCode == HTTP_OK && callback != null)
                        BufferedReader reader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
                        StringBuilder response = new StringBuilder();
                        String line;
                        while ((line = reader.readLine()) != null)
                        response.append(line);

                        // callback success
                        callback.OnSuccess(response.toString());
                        reader.close(); // close BufferReader
                        else if (callback != null)
                        // callback error
                        callback.OnError(responseCode, urlConnection.getResponseMessage());


                        urlConnection.disconnect(); // disconnect connection
                        catch (IOException e)
                        e.printStackTrace();
                        if (callback != null)
                        // callback error
                        callback.OnError(500, e.getLocalizedMessage());



                        ).start(); // start thread








                        share|improve this answer














                        share|improve this answer



                        share|improve this answer








                        edited 23 hours ago









                        Evan Wieland

                        9741425




                        9741425










                        answered Jan 29 '17 at 12:03









                        Pankaj Kant PatelPankaj Kant Patel

                        1,410922




                        1,410922





















                            5














                            GET and POST method set like this... Two types for api calling 1)get() and 2) post() . get() method to get value from api json array to get value & post() method use in our data post in url and get response.



                             public class HttpClientForExample 

                            private final String USER_AGENT = "Mozilla/5.0";

                            public static void main(String args) throws Exception

                            HttpClientExample http = new HttpClientExample();

                            System.out.println("Testing 1 - Send Http GET request");
                            http.sendGet();

                            System.out.println("nTesting 2 - Send Http POST request");
                            http.sendPost();



                            // HTTP GET request
                            private void sendGet() throws Exception

                            String url = "http://www.google.com/search?q=developer";

                            HttpClient client = new DefaultHttpClient();
                            HttpGet request = new HttpGet(url);

                            // add request header
                            request.addHeader("User-Agent", USER_AGENT);

                            HttpResponse response = client.execute(request);

                            System.out.println("nSending 'GET' request to URL : " + url);
                            System.out.println("Response Code : " +
                            response.getStatusLine().getStatusCode());

                            BufferedReader rd = new BufferedReader(
                            new InputStreamReader(response.getEntity().getContent()));

                            StringBuffer result = new StringBuffer();
                            String line = "";
                            while ((line = rd.readLine()) != null)
                            result.append(line);


                            System.out.println(result.toString());



                            // HTTP POST request
                            private void sendPost() throws Exception

                            String url = "https://selfsolve.apple.com/wcResults.do";

                            HttpClient client = new DefaultHttpClient();
                            HttpPost post = new HttpPost(url);

                            // add header
                            post.setHeader("User-Agent", USER_AGENT);

                            List<NameValuePair> urlParameters = new ArrayList<NameValuePair>();
                            urlParameters.add(new BasicNameValuePair("sn", "C02G8416DRJM"));
                            urlParameters.add(new BasicNameValuePair("cn", ""));
                            urlParameters.add(new BasicNameValuePair("locale", ""));
                            urlParameters.add(new BasicNameValuePair("caller", ""));
                            urlParameters.add(new BasicNameValuePair("num", "12345"));

                            post.setEntity(new UrlEncodedFormEntity(urlParameters));

                            HttpResponse response = client.execute(post);
                            System.out.println("nSending 'POST' request to URL : " + url);
                            System.out.println("Post parameters : " + post.getEntity());
                            System.out.println("Response Code : " +
                            response.getStatusLine().getStatusCode());

                            BufferedReader rd = new BufferedReader(
                            new InputStreamReader(response.getEntity().getContent()));

                            StringBuffer result = new StringBuffer();
                            String line = "";
                            while ((line = rd.readLine()) != null)
                            result.append(line);


                            System.out.println(result.toString());









                            share|improve this answer





























                              5














                              GET and POST method set like this... Two types for api calling 1)get() and 2) post() . get() method to get value from api json array to get value & post() method use in our data post in url and get response.



                               public class HttpClientForExample 

                              private final String USER_AGENT = "Mozilla/5.0";

                              public static void main(String args) throws Exception

                              HttpClientExample http = new HttpClientExample();

                              System.out.println("Testing 1 - Send Http GET request");
                              http.sendGet();

                              System.out.println("nTesting 2 - Send Http POST request");
                              http.sendPost();



                              // HTTP GET request
                              private void sendGet() throws Exception

                              String url = "http://www.google.com/search?q=developer";

                              HttpClient client = new DefaultHttpClient();
                              HttpGet request = new HttpGet(url);

                              // add request header
                              request.addHeader("User-Agent", USER_AGENT);

                              HttpResponse response = client.execute(request);

                              System.out.println("nSending 'GET' request to URL : " + url);
                              System.out.println("Response Code : " +
                              response.getStatusLine().getStatusCode());

                              BufferedReader rd = new BufferedReader(
                              new InputStreamReader(response.getEntity().getContent()));

                              StringBuffer result = new StringBuffer();
                              String line = "";
                              while ((line = rd.readLine()) != null)
                              result.append(line);


                              System.out.println(result.toString());



                              // HTTP POST request
                              private void sendPost() throws Exception

                              String url = "https://selfsolve.apple.com/wcResults.do";

                              HttpClient client = new DefaultHttpClient();
                              HttpPost post = new HttpPost(url);

                              // add header
                              post.setHeader("User-Agent", USER_AGENT);

                              List<NameValuePair> urlParameters = new ArrayList<NameValuePair>();
                              urlParameters.add(new BasicNameValuePair("sn", "C02G8416DRJM"));
                              urlParameters.add(new BasicNameValuePair("cn", ""));
                              urlParameters.add(new BasicNameValuePair("locale", ""));
                              urlParameters.add(new BasicNameValuePair("caller", ""));
                              urlParameters.add(new BasicNameValuePair("num", "12345"));

                              post.setEntity(new UrlEncodedFormEntity(urlParameters));

                              HttpResponse response = client.execute(post);
                              System.out.println("nSending 'POST' request to URL : " + url);
                              System.out.println("Post parameters : " + post.getEntity());
                              System.out.println("Response Code : " +
                              response.getStatusLine().getStatusCode());

                              BufferedReader rd = new BufferedReader(
                              new InputStreamReader(response.getEntity().getContent()));

                              StringBuffer result = new StringBuffer();
                              String line = "";
                              while ((line = rd.readLine()) != null)
                              result.append(line);


                              System.out.println(result.toString());









                              share|improve this answer



























                                5












                                5








                                5







                                GET and POST method set like this... Two types for api calling 1)get() and 2) post() . get() method to get value from api json array to get value & post() method use in our data post in url and get response.



                                 public class HttpClientForExample 

                                private final String USER_AGENT = "Mozilla/5.0";

                                public static void main(String args) throws Exception

                                HttpClientExample http = new HttpClientExample();

                                System.out.println("Testing 1 - Send Http GET request");
                                http.sendGet();

                                System.out.println("nTesting 2 - Send Http POST request");
                                http.sendPost();



                                // HTTP GET request
                                private void sendGet() throws Exception

                                String url = "http://www.google.com/search?q=developer";

                                HttpClient client = new DefaultHttpClient();
                                HttpGet request = new HttpGet(url);

                                // add request header
                                request.addHeader("User-Agent", USER_AGENT);

                                HttpResponse response = client.execute(request);

                                System.out.println("nSending 'GET' request to URL : " + url);
                                System.out.println("Response Code : " +
                                response.getStatusLine().getStatusCode());

                                BufferedReader rd = new BufferedReader(
                                new InputStreamReader(response.getEntity().getContent()));

                                StringBuffer result = new StringBuffer();
                                String line = "";
                                while ((line = rd.readLine()) != null)
                                result.append(line);


                                System.out.println(result.toString());



                                // HTTP POST request
                                private void sendPost() throws Exception

                                String url = "https://selfsolve.apple.com/wcResults.do";

                                HttpClient client = new DefaultHttpClient();
                                HttpPost post = new HttpPost(url);

                                // add header
                                post.setHeader("User-Agent", USER_AGENT);

                                List<NameValuePair> urlParameters = new ArrayList<NameValuePair>();
                                urlParameters.add(new BasicNameValuePair("sn", "C02G8416DRJM"));
                                urlParameters.add(new BasicNameValuePair("cn", ""));
                                urlParameters.add(new BasicNameValuePair("locale", ""));
                                urlParameters.add(new BasicNameValuePair("caller", ""));
                                urlParameters.add(new BasicNameValuePair("num", "12345"));

                                post.setEntity(new UrlEncodedFormEntity(urlParameters));

                                HttpResponse response = client.execute(post);
                                System.out.println("nSending 'POST' request to URL : " + url);
                                System.out.println("Post parameters : " + post.getEntity());
                                System.out.println("Response Code : " +
                                response.getStatusLine().getStatusCode());

                                BufferedReader rd = new BufferedReader(
                                new InputStreamReader(response.getEntity().getContent()));

                                StringBuffer result = new StringBuffer();
                                String line = "";
                                while ((line = rd.readLine()) != null)
                                result.append(line);


                                System.out.println(result.toString());









                                share|improve this answer















                                GET and POST method set like this... Two types for api calling 1)get() and 2) post() . get() method to get value from api json array to get value & post() method use in our data post in url and get response.



                                 public class HttpClientForExample 

                                private final String USER_AGENT = "Mozilla/5.0";

                                public static void main(String args) throws Exception

                                HttpClientExample http = new HttpClientExample();

                                System.out.println("Testing 1 - Send Http GET request");
                                http.sendGet();

                                System.out.println("nTesting 2 - Send Http POST request");
                                http.sendPost();



                                // HTTP GET request
                                private void sendGet() throws Exception

                                String url = "http://www.google.com/search?q=developer";

                                HttpClient client = new DefaultHttpClient();
                                HttpGet request = new HttpGet(url);

                                // add request header
                                request.addHeader("User-Agent", USER_AGENT);

                                HttpResponse response = client.execute(request);

                                System.out.println("nSending 'GET' request to URL : " + url);
                                System.out.println("Response Code : " +
                                response.getStatusLine().getStatusCode());

                                BufferedReader rd = new BufferedReader(
                                new InputStreamReader(response.getEntity().getContent()));

                                StringBuffer result = new StringBuffer();
                                String line = "";
                                while ((line = rd.readLine()) != null)
                                result.append(line);


                                System.out.println(result.toString());



                                // HTTP POST request
                                private void sendPost() throws Exception

                                String url = "https://selfsolve.apple.com/wcResults.do";

                                HttpClient client = new DefaultHttpClient();
                                HttpPost post = new HttpPost(url);

                                // add header
                                post.setHeader("User-Agent", USER_AGENT);

                                List<NameValuePair> urlParameters = new ArrayList<NameValuePair>();
                                urlParameters.add(new BasicNameValuePair("sn", "C02G8416DRJM"));
                                urlParameters.add(new BasicNameValuePair("cn", ""));
                                urlParameters.add(new BasicNameValuePair("locale", ""));
                                urlParameters.add(new BasicNameValuePair("caller", ""));
                                urlParameters.add(new BasicNameValuePair("num", "12345"));

                                post.setEntity(new UrlEncodedFormEntity(urlParameters));

                                HttpResponse response = client.execute(post);
                                System.out.println("nSending 'POST' request to URL : " + url);
                                System.out.println("Post parameters : " + post.getEntity());
                                System.out.println("Response Code : " +
                                response.getStatusLine().getStatusCode());

                                BufferedReader rd = new BufferedReader(
                                new InputStreamReader(response.getEntity().getContent()));

                                StringBuffer result = new StringBuffer();
                                String line = "";
                                while ((line = rd.readLine()) != null)
                                result.append(line);


                                System.out.println(result.toString());










                                share|improve this answer














                                share|improve this answer



                                share|improve this answer








                                edited Aug 20 '18 at 6:19

























                                answered Aug 20 '18 at 5:48









                                Chirag PatelChirag Patel

                                396411




                                396411





















                                    3














                                    I had the same issue. I wanted to send data via POST.
                                    I used the following code:



                                     URL url = new URL("http://example.com/getval.php");
                                    Map<String,Object> params = new LinkedHashMap<>();
                                    params.put("param1", param1);
                                    params.put("param2", param2);

                                    StringBuilder postData = new StringBuilder();
                                    for (Map.Entry<String,Object> param : params.entrySet())
                                    if (postData.length() != 0) postData.append('&');
                                    postData.append(URLEncoder.encode(param.getKey(), "UTF-8"));
                                    postData.append('=');
                                    postData.append(URLEncoder.encode(String.valueOf(param.getValue()), "UTF-8"));

                                    String urlParameters = postData.toString();
                                    URLConnection conn = url.openConnection();

                                    conn.setDoOutput(true);

                                    OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());

                                    writer.write(urlParameters);
                                    writer.flush();

                                    String result = "";
                                    String line;
                                    BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));

                                    while ((line = reader.readLine()) != null)
                                    result += line;

                                    writer.close();
                                    reader.close()
                                    System.out.println(result);


                                    I used Jsoup for parse:



                                     Document doc = Jsoup.parseBodyFragment(value);
                                    Iterator<Element> opts = doc.select("option").iterator();
                                    for (;opts.hasNext();)
                                    Element item = opts.next();
                                    if (item.hasAttr("value"))
                                    System.out.println(item.attr("value"));







                                    share|improve this answer



























                                      3














                                      I had the same issue. I wanted to send data via POST.
                                      I used the following code:



                                       URL url = new URL("http://example.com/getval.php");
                                      Map<String,Object> params = new LinkedHashMap<>();
                                      params.put("param1", param1);
                                      params.put("param2", param2);

                                      StringBuilder postData = new StringBuilder();
                                      for (Map.Entry<String,Object> param : params.entrySet())
                                      if (postData.length() != 0) postData.append('&');
                                      postData.append(URLEncoder.encode(param.getKey(), "UTF-8"));
                                      postData.append('=');
                                      postData.append(URLEncoder.encode(String.valueOf(param.getValue()), "UTF-8"));

                                      String urlParameters = postData.toString();
                                      URLConnection conn = url.openConnection();

                                      conn.setDoOutput(true);

                                      OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());

                                      writer.write(urlParameters);
                                      writer.flush();

                                      String result = "";
                                      String line;
                                      BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));

                                      while ((line = reader.readLine()) != null)
                                      result += line;

                                      writer.close();
                                      reader.close()
                                      System.out.println(result);


                                      I used Jsoup for parse:



                                       Document doc = Jsoup.parseBodyFragment(value);
                                      Iterator<Element> opts = doc.select("option").iterator();
                                      for (;opts.hasNext();)
                                      Element item = opts.next();
                                      if (item.hasAttr("value"))
                                      System.out.println(item.attr("value"));







                                      share|improve this answer

























                                        3












                                        3








                                        3







                                        I had the same issue. I wanted to send data via POST.
                                        I used the following code:



                                         URL url = new URL("http://example.com/getval.php");
                                        Map<String,Object> params = new LinkedHashMap<>();
                                        params.put("param1", param1);
                                        params.put("param2", param2);

                                        StringBuilder postData = new StringBuilder();
                                        for (Map.Entry<String,Object> param : params.entrySet())
                                        if (postData.length() != 0) postData.append('&');
                                        postData.append(URLEncoder.encode(param.getKey(), "UTF-8"));
                                        postData.append('=');
                                        postData.append(URLEncoder.encode(String.valueOf(param.getValue()), "UTF-8"));

                                        String urlParameters = postData.toString();
                                        URLConnection conn = url.openConnection();

                                        conn.setDoOutput(true);

                                        OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());

                                        writer.write(urlParameters);
                                        writer.flush();

                                        String result = "";
                                        String line;
                                        BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));

                                        while ((line = reader.readLine()) != null)
                                        result += line;

                                        writer.close();
                                        reader.close()
                                        System.out.println(result);


                                        I used Jsoup for parse:



                                         Document doc = Jsoup.parseBodyFragment(value);
                                        Iterator<Element> opts = doc.select("option").iterator();
                                        for (;opts.hasNext();)
                                        Element item = opts.next();
                                        if (item.hasAttr("value"))
                                        System.out.println(item.attr("value"));







                                        share|improve this answer













                                        I had the same issue. I wanted to send data via POST.
                                        I used the following code:



                                         URL url = new URL("http://example.com/getval.php");
                                        Map<String,Object> params = new LinkedHashMap<>();
                                        params.put("param1", param1);
                                        params.put("param2", param2);

                                        StringBuilder postData = new StringBuilder();
                                        for (Map.Entry<String,Object> param : params.entrySet())
                                        if (postData.length() != 0) postData.append('&');
                                        postData.append(URLEncoder.encode(param.getKey(), "UTF-8"));
                                        postData.append('=');
                                        postData.append(URLEncoder.encode(String.valueOf(param.getValue()), "UTF-8"));

                                        String urlParameters = postData.toString();
                                        URLConnection conn = url.openConnection();

                                        conn.setDoOutput(true);

                                        OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());

                                        writer.write(urlParameters);
                                        writer.flush();

                                        String result = "";
                                        String line;
                                        BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));

                                        while ((line = reader.readLine()) != null)
                                        result += line;

                                        writer.close();
                                        reader.close()
                                        System.out.println(result);


                                        I used Jsoup for parse:



                                         Document doc = Jsoup.parseBodyFragment(value);
                                        Iterator<Element> opts = doc.select("option").iterator();
                                        for (;opts.hasNext();)
                                        Element item = opts.next();
                                        if (item.hasAttr("value"))
                                        System.out.println(item.attr("value"));








                                        share|improve this answer












                                        share|improve this answer



                                        share|improve this answer










                                        answered Aug 4 '15 at 9:16









                                        SergeyUrSergeyUr

                                        85214




                                        85214





















                                            3














                                            Try this pattern:



                                            public static PricesResponse getResponse(EventRequestRaw request) 

                                            // String urlParameters = "param1=a&param2=b&param3=c";
                                            String urlParameters = Piping.serialize(request);

                                            HttpURLConnection conn = RestClient.getPOSTConnection(endPoint, urlParameters);

                                            PricesResponse response = null;

                                            try
                                            // POST
                                            OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());
                                            writer.write(urlParameters);
                                            writer.flush();

                                            // RESPONSE
                                            BufferedReader reader = new BufferedReader(new InputStreamReader((conn.getInputStream()), StandardCharsets.UTF_8));
                                            String json = Buffering.getString(reader);
                                            response = (PricesResponse) Piping.deserialize(json, PricesResponse.class);

                                            writer.close();
                                            reader.close();

                                            catch (Exception e)
                                            e.printStackTrace();


                                            conn.disconnect();

                                            System.out.println("PricesClient: " + response.toString());

                                            return response;


                                            public static HttpURLConnection getPOSTConnection(String endPoint, String urlParameters)

                                            return RestClient.getConnection(endPoint, "POST", urlParameters);




                                            public static HttpURLConnection getConnection(String endPoint, String method, String urlParameters)

                                            System.out.println("ENDPOINT " + endPoint + " METHOD " + method);
                                            HttpURLConnection conn = null;

                                            try
                                            URL url = new URL(endPoint);
                                            conn = (HttpURLConnection) url.openConnection();
                                            conn.setRequestMethod(method);
                                            conn.setDoOutput(true);
                                            conn.setRequestProperty("Content-Type", "text/plain");

                                            catch (IOException e)
                                            e.printStackTrace();


                                            return conn;






                                            share|improve this answer



























                                              3














                                              Try this pattern:



                                              public static PricesResponse getResponse(EventRequestRaw request) 

                                              // String urlParameters = "param1=a&param2=b&param3=c";
                                              String urlParameters = Piping.serialize(request);

                                              HttpURLConnection conn = RestClient.getPOSTConnection(endPoint, urlParameters);

                                              PricesResponse response = null;

                                              try
                                              // POST
                                              OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());
                                              writer.write(urlParameters);
                                              writer.flush();

                                              // RESPONSE
                                              BufferedReader reader = new BufferedReader(new InputStreamReader((conn.getInputStream()), StandardCharsets.UTF_8));
                                              String json = Buffering.getString(reader);
                                              response = (PricesResponse) Piping.deserialize(json, PricesResponse.class);

                                              writer.close();
                                              reader.close();

                                              catch (Exception e)
                                              e.printStackTrace();


                                              conn.disconnect();

                                              System.out.println("PricesClient: " + response.toString());

                                              return response;


                                              public static HttpURLConnection getPOSTConnection(String endPoint, String urlParameters)

                                              return RestClient.getConnection(endPoint, "POST", urlParameters);




                                              public static HttpURLConnection getConnection(String endPoint, String method, String urlParameters)

                                              System.out.println("ENDPOINT " + endPoint + " METHOD " + method);
                                              HttpURLConnection conn = null;

                                              try
                                              URL url = new URL(endPoint);
                                              conn = (HttpURLConnection) url.openConnection();
                                              conn.setRequestMethod(method);
                                              conn.setDoOutput(true);
                                              conn.setRequestProperty("Content-Type", "text/plain");

                                              catch (IOException e)
                                              e.printStackTrace();


                                              return conn;






                                              share|improve this answer

























                                                3












                                                3








                                                3







                                                Try this pattern:



                                                public static PricesResponse getResponse(EventRequestRaw request) 

                                                // String urlParameters = "param1=a&param2=b&param3=c";
                                                String urlParameters = Piping.serialize(request);

                                                HttpURLConnection conn = RestClient.getPOSTConnection(endPoint, urlParameters);

                                                PricesResponse response = null;

                                                try
                                                // POST
                                                OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());
                                                writer.write(urlParameters);
                                                writer.flush();

                                                // RESPONSE
                                                BufferedReader reader = new BufferedReader(new InputStreamReader((conn.getInputStream()), StandardCharsets.UTF_8));
                                                String json = Buffering.getString(reader);
                                                response = (PricesResponse) Piping.deserialize(json, PricesResponse.class);

                                                writer.close();
                                                reader.close();

                                                catch (Exception e)
                                                e.printStackTrace();


                                                conn.disconnect();

                                                System.out.println("PricesClient: " + response.toString());

                                                return response;


                                                public static HttpURLConnection getPOSTConnection(String endPoint, String urlParameters)

                                                return RestClient.getConnection(endPoint, "POST", urlParameters);




                                                public static HttpURLConnection getConnection(String endPoint, String method, String urlParameters)

                                                System.out.println("ENDPOINT " + endPoint + " METHOD " + method);
                                                HttpURLConnection conn = null;

                                                try
                                                URL url = new URL(endPoint);
                                                conn = (HttpURLConnection) url.openConnection();
                                                conn.setRequestMethod(method);
                                                conn.setDoOutput(true);
                                                conn.setRequestProperty("Content-Type", "text/plain");

                                                catch (IOException e)
                                                e.printStackTrace();


                                                return conn;






                                                share|improve this answer













                                                Try this pattern:



                                                public static PricesResponse getResponse(EventRequestRaw request) 

                                                // String urlParameters = "param1=a&param2=b&param3=c";
                                                String urlParameters = Piping.serialize(request);

                                                HttpURLConnection conn = RestClient.getPOSTConnection(endPoint, urlParameters);

                                                PricesResponse response = null;

                                                try
                                                // POST
                                                OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());
                                                writer.write(urlParameters);
                                                writer.flush();

                                                // RESPONSE
                                                BufferedReader reader = new BufferedReader(new InputStreamReader((conn.getInputStream()), StandardCharsets.UTF_8));
                                                String json = Buffering.getString(reader);
                                                response = (PricesResponse) Piping.deserialize(json, PricesResponse.class);

                                                writer.close();
                                                reader.close();

                                                catch (Exception e)
                                                e.printStackTrace();


                                                conn.disconnect();

                                                System.out.println("PricesClient: " + response.toString());

                                                return response;


                                                public static HttpURLConnection getPOSTConnection(String endPoint, String urlParameters)

                                                return RestClient.getConnection(endPoint, "POST", urlParameters);




                                                public static HttpURLConnection getConnection(String endPoint, String method, String urlParameters)

                                                System.out.println("ENDPOINT " + endPoint + " METHOD " + method);
                                                HttpURLConnection conn = null;

                                                try
                                                URL url = new URL(endPoint);
                                                conn = (HttpURLConnection) url.openConnection();
                                                conn.setRequestMethod(method);
                                                conn.setDoOutput(true);
                                                conn.setRequestProperty("Content-Type", "text/plain");

                                                catch (IOException e)
                                                e.printStackTrace();


                                                return conn;







                                                share|improve this answer












                                                share|improve this answer



                                                share|improve this answer










                                                answered Oct 7 '15 at 3:53









                                                Pablo Rodriguez BertorelloPablo Rodriguez Bertorello

                                                1468




                                                1468





















                                                    2














                                                    here i sent jsonobject as parameter //jsonobject="name":"lucifer","pass":"abc"//serverUrl = "http://192.168.100.12/testing" //host=192.168.100.12



                                                     public static String getJson(String serverUrl,String host,String jsonobject)

                                                    StringBuilder sb = new StringBuilder();

                                                    String http = serverUrl;

                                                    HttpURLConnection urlConnection = null;
                                                    try
                                                    URL url = new URL(http);
                                                    urlConnection = (HttpURLConnection) url.openConnection();
                                                    urlConnection.setDoOutput(true);
                                                    urlConnection.setRequestMethod("POST");
                                                    urlConnection.setUseCaches(false);
                                                    urlConnection.setConnectTimeout(50000);
                                                    urlConnection.setReadTimeout(50000);
                                                    urlConnection.setRequestProperty("Content-Type", "application/json");
                                                    urlConnection.setRequestProperty("Host", host);
                                                    urlConnection.connect();
                                                    //You Can also Create JSONObject here
                                                    OutputStreamWriter out = new OutputStreamWriter(urlConnection.getOutputStream());
                                                    out.write(jsonobject);// here i sent the parameter
                                                    out.close();
                                                    int HttpResult = urlConnection.getResponseCode();
                                                    if (HttpResult == HttpURLConnection.HTTP_OK)
                                                    BufferedReader br = new BufferedReader(new InputStreamReader(
                                                    urlConnection.getInputStream(), "utf-8"));
                                                    String line = null;
                                                    while ((line = br.readLine()) != null)
                                                    sb.append(line + "n");

                                                    br.close();
                                                    Log.e("new Test", "" + sb.toString());
                                                    return sb.toString();
                                                    else
                                                    Log.e(" ", "" + urlConnection.getResponseMessage());

                                                    catch (MalformedURLException e)
                                                    e.printStackTrace();
                                                    catch (IOException e)
                                                    e.printStackTrace();
                                                    catch (JSONException e)
                                                    e.printStackTrace();
                                                    finally
                                                    if (urlConnection != null)
                                                    urlConnection.disconnect();

                                                    return null;






                                                    share|improve this answer





























                                                      2














                                                      here i sent jsonobject as parameter //jsonobject="name":"lucifer","pass":"abc"//serverUrl = "http://192.168.100.12/testing" //host=192.168.100.12



                                                       public static String getJson(String serverUrl,String host,String jsonobject)

                                                      StringBuilder sb = new StringBuilder();

                                                      String http = serverUrl;

                                                      HttpURLConnection urlConnection = null;
                                                      try
                                                      URL url = new URL(http);
                                                      urlConnection = (HttpURLConnection) url.openConnection();
                                                      urlConnection.setDoOutput(true);
                                                      urlConnection.setRequestMethod("POST");
                                                      urlConnection.setUseCaches(false);
                                                      urlConnection.setConnectTimeout(50000);
                                                      urlConnection.setReadTimeout(50000);
                                                      urlConnection.setRequestProperty("Content-Type", "application/json");
                                                      urlConnection.setRequestProperty("Host", host);
                                                      urlConnection.connect();
                                                      //You Can also Create JSONObject here
                                                      OutputStreamWriter out = new OutputStreamWriter(urlConnection.getOutputStream());
                                                      out.write(jsonobject);// here i sent the parameter
                                                      out.close();
                                                      int HttpResult = urlConnection.getResponseCode();
                                                      if (HttpResult == HttpURLConnection.HTTP_OK)
                                                      BufferedReader br = new BufferedReader(new InputStreamReader(
                                                      urlConnection.getInputStream(), "utf-8"));
                                                      String line = null;
                                                      while ((line = br.readLine()) != null)
                                                      sb.append(line + "n");

                                                      br.close();
                                                      Log.e("new Test", "" + sb.toString());
                                                      return sb.toString();
                                                      else
                                                      Log.e(" ", "" + urlConnection.getResponseMessage());

                                                      catch (MalformedURLException e)
                                                      e.printStackTrace();
                                                      catch (IOException e)
                                                      e.printStackTrace();
                                                      catch (JSONException e)
                                                      e.printStackTrace();
                                                      finally
                                                      if (urlConnection != null)
                                                      urlConnection.disconnect();

                                                      return null;






                                                      share|improve this answer



























                                                        2












                                                        2








                                                        2







                                                        here i sent jsonobject as parameter //jsonobject="name":"lucifer","pass":"abc"//serverUrl = "http://192.168.100.12/testing" //host=192.168.100.12



                                                         public static String getJson(String serverUrl,String host,String jsonobject)

                                                        StringBuilder sb = new StringBuilder();

                                                        String http = serverUrl;

                                                        HttpURLConnection urlConnection = null;
                                                        try
                                                        URL url = new URL(http);
                                                        urlConnection = (HttpURLConnection) url.openConnection();
                                                        urlConnection.setDoOutput(true);
                                                        urlConnection.setRequestMethod("POST");
                                                        urlConnection.setUseCaches(false);
                                                        urlConnection.setConnectTimeout(50000);
                                                        urlConnection.setReadTimeout(50000);
                                                        urlConnection.setRequestProperty("Content-Type", "application/json");
                                                        urlConnection.setRequestProperty("Host", host);
                                                        urlConnection.connect();
                                                        //You Can also Create JSONObject here
                                                        OutputStreamWriter out = new OutputStreamWriter(urlConnection.getOutputStream());
                                                        out.write(jsonobject);// here i sent the parameter
                                                        out.close();
                                                        int HttpResult = urlConnection.getResponseCode();
                                                        if (HttpResult == HttpURLConnection.HTTP_OK)
                                                        BufferedReader br = new BufferedReader(new InputStreamReader(
                                                        urlConnection.getInputStream(), "utf-8"));
                                                        String line = null;
                                                        while ((line = br.readLine()) != null)
                                                        sb.append(line + "n");

                                                        br.close();
                                                        Log.e("new Test", "" + sb.toString());
                                                        return sb.toString();
                                                        else
                                                        Log.e(" ", "" + urlConnection.getResponseMessage());

                                                        catch (MalformedURLException e)
                                                        e.printStackTrace();
                                                        catch (IOException e)
                                                        e.printStackTrace();
                                                        catch (JSONException e)
                                                        e.printStackTrace();
                                                        finally
                                                        if (urlConnection != null)
                                                        urlConnection.disconnect();

                                                        return null;






                                                        share|improve this answer















                                                        here i sent jsonobject as parameter //jsonobject="name":"lucifer","pass":"abc"//serverUrl = "http://192.168.100.12/testing" //host=192.168.100.12



                                                         public static String getJson(String serverUrl,String host,String jsonobject)

                                                        StringBuilder sb = new StringBuilder();

                                                        String http = serverUrl;

                                                        HttpURLConnection urlConnection = null;
                                                        try
                                                        URL url = new URL(http);
                                                        urlConnection = (HttpURLConnection) url.openConnection();
                                                        urlConnection.setDoOutput(true);
                                                        urlConnection.setRequestMethod("POST");
                                                        urlConnection.setUseCaches(false);
                                                        urlConnection.setConnectTimeout(50000);
                                                        urlConnection.setReadTimeout(50000);
                                                        urlConnection.setRequestProperty("Content-Type", "application/json");
                                                        urlConnection.setRequestProperty("Host", host);
                                                        urlConnection.connect();
                                                        //You Can also Create JSONObject here
                                                        OutputStreamWriter out = new OutputStreamWriter(urlConnection.getOutputStream());
                                                        out.write(jsonobject);// here i sent the parameter
                                                        out.close();
                                                        int HttpResult = urlConnection.getResponseCode();
                                                        if (HttpResult == HttpURLConnection.HTTP_OK)
                                                        BufferedReader br = new BufferedReader(new InputStreamReader(
                                                        urlConnection.getInputStream(), "utf-8"));
                                                        String line = null;
                                                        while ((line = br.readLine()) != null)
                                                        sb.append(line + "n");

                                                        br.close();
                                                        Log.e("new Test", "" + sb.toString());
                                                        return sb.toString();
                                                        else
                                                        Log.e(" ", "" + urlConnection.getResponseMessage());

                                                        catch (MalformedURLException e)
                                                        e.printStackTrace();
                                                        catch (IOException e)
                                                        e.printStackTrace();
                                                        catch (JSONException e)
                                                        e.printStackTrace();
                                                        finally
                                                        if (urlConnection != null)
                                                        urlConnection.disconnect();

                                                        return null;







                                                        share|improve this answer














                                                        share|improve this answer



                                                        share|improve this answer








                                                        edited Jul 19 '16 at 10:57

























                                                        answered Jul 18 '16 at 10:12









                                                        AbhisekAbhisek

                                                        59143




                                                        59143





















                                                            2














                                                            I higly recomend http-request built on apache http api.



                                                            For your case you can see example:



                                                            private static final HttpRequest<String.class> HTTP_REQUEST = 
                                                            HttpRequestBuilder.createPost("http://example.com/index.php", String.class)
                                                            .responseDeserializer(ResponseDeserializer.ignorableDeserializer())
                                                            .build();

                                                            public void sendRequest(String request)
                                                            String parameters = request.split("\?")[1];
                                                            ResponseHandler<String> responseHandler =
                                                            HTTP_REQUEST.executeWithQuery(parameters);

                                                            System.out.println(responseHandler.getStatusCode());
                                                            System.out.println(responseHandler.get()); //prints response body



                                                            If you are not interested in the response body



                                                            private static final HttpRequest<?> HTTP_REQUEST = 
                                                            HttpRequestBuilder.createPost("http://example.com/index.php").build();

                                                            public void sendRequest(String request)
                                                            ResponseHandler<String> responseHandler =
                                                            HTTP_REQUEST.executeWithQuery(parameters);



                                                            For general sending post request with http-request: Read the documentation and see my answers HTTP POST request with JSON String in JAVA, Sending HTTP POST Request In Java, HTTP POST using JSON in Java






                                                            share|improve this answer



























                                                              2














                                                              I higly recomend http-request built on apache http api.



                                                              For your case you can see example:



                                                              private static final HttpRequest<String.class> HTTP_REQUEST = 
                                                              HttpRequestBuilder.createPost("http://example.com/index.php", String.class)
                                                              .responseDeserializer(ResponseDeserializer.ignorableDeserializer())
                                                              .build();

                                                              public void sendRequest(String request)
                                                              String parameters = request.split("\?")[1];
                                                              ResponseHandler<String> responseHandler =
                                                              HTTP_REQUEST.executeWithQuery(parameters);

                                                              System.out.println(responseHandler.getStatusCode());
                                                              System.out.println(responseHandler.get()); //prints response body



                                                              If you are not interested in the response body



                                                              private static final HttpRequest<?> HTTP_REQUEST = 
                                                              HttpRequestBuilder.createPost("http://example.com/index.php").build();

                                                              public void sendRequest(String request)
                                                              ResponseHandler<String> responseHandler =
                                                              HTTP_REQUEST.executeWithQuery(parameters);



                                                              For general sending post request with http-request: Read the documentation and see my answers HTTP POST request with JSON String in JAVA, Sending HTTP POST Request In Java, HTTP POST using JSON in Java






                                                              share|improve this answer

























                                                                2












                                                                2








                                                                2







                                                                I higly recomend http-request built on apache http api.



                                                                For your case you can see example:



                                                                private static final HttpRequest<String.class> HTTP_REQUEST = 
                                                                HttpRequestBuilder.createPost("http://example.com/index.php", String.class)
                                                                .responseDeserializer(ResponseDeserializer.ignorableDeserializer())
                                                                .build();

                                                                public void sendRequest(String request)
                                                                String parameters = request.split("\?")[1];
                                                                ResponseHandler<String> responseHandler =
                                                                HTTP_REQUEST.executeWithQuery(parameters);

                                                                System.out.println(responseHandler.getStatusCode());
                                                                System.out.println(responseHandler.get()); //prints response body



                                                                If you are not interested in the response body



                                                                private static final HttpRequest<?> HTTP_REQUEST = 
                                                                HttpRequestBuilder.createPost("http://example.com/index.php").build();

                                                                public void sendRequest(String request)
                                                                ResponseHandler<String> responseHandler =
                                                                HTTP_REQUEST.executeWithQuery(parameters);



                                                                For general sending post request with http-request: Read the documentation and see my answers HTTP POST request with JSON String in JAVA, Sending HTTP POST Request In Java, HTTP POST using JSON in Java






                                                                share|improve this answer













                                                                I higly recomend http-request built on apache http api.



                                                                For your case you can see example:



                                                                private static final HttpRequest<String.class> HTTP_REQUEST = 
                                                                HttpRequestBuilder.createPost("http://example.com/index.php", String.class)
                                                                .responseDeserializer(ResponseDeserializer.ignorableDeserializer())
                                                                .build();

                                                                public void sendRequest(String request)
                                                                String parameters = request.split("\?")[1];
                                                                ResponseHandler<String> responseHandler =
                                                                HTTP_REQUEST.executeWithQuery(parameters);

                                                                System.out.println(responseHandler.getStatusCode());
                                                                System.out.println(responseHandler.get()); //prints response body



                                                                If you are not interested in the response body



                                                                private static final HttpRequest<?> HTTP_REQUEST = 
                                                                HttpRequestBuilder.createPost("http://example.com/index.php").build();

                                                                public void sendRequest(String request)
                                                                ResponseHandler<String> responseHandler =
                                                                HTTP_REQUEST.executeWithQuery(parameters);



                                                                For general sending post request with http-request: Read the documentation and see my answers HTTP POST request with JSON String in JAVA, Sending HTTP POST Request In Java, HTTP POST using JSON in Java







                                                                share|improve this answer












                                                                share|improve this answer



                                                                share|improve this answer










                                                                answered Sep 24 '17 at 22:23









                                                                Beno ArakelyanBeno Arakelyan

                                                                553416




                                                                553416





















                                                                    1














                                                                    Hello pls use this class to improve your post method



                                                                    public static JSONObject doPostRequest(HashMap<String, String> data, String url) UnsupportedEncodingException e) 

                                                                    JSONObject jsonObject=new JSONObject();

                                                                    try
                                                                    jsonObject.put("status","false");
                                                                    jsonObject.put("message",e.getLocalizedMessage());
                                                                    catch (JSONException e1)
                                                                    e1.printStackTrace();

                                                                    Log.e(TAG, "Error: " + e.getLocalizedMessage());
                                                                    catch (Exception e)
                                                                    e.printStackTrace();
                                                                    JSONObject jsonObject=new JSONObject();

                                                                    try
                                                                    jsonObject.put("status","false");
                                                                    jsonObject.put("message",e.getLocalizedMessage());
                                                                    catch (JSONException e1)
                                                                    e1.printStackTrace();

                                                                    Log.e(TAG, "Other Error: " + e.getLocalizedMessage());

                                                                    return null;






                                                                    share|improve this answer





























                                                                      1














                                                                      Hello pls use this class to improve your post method



                                                                      public static JSONObject doPostRequest(HashMap<String, String> data, String url) UnsupportedEncodingException e) 

                                                                      JSONObject jsonObject=new JSONObject();

                                                                      try
                                                                      jsonObject.put("status","false");
                                                                      jsonObject.put("message",e.getLocalizedMessage());
                                                                      catch (JSONException e1)
                                                                      e1.printStackTrace();

                                                                      Log.e(TAG, "Error: " + e.getLocalizedMessage());
                                                                      catch (Exception e)
                                                                      e.printStackTrace();
                                                                      JSONObject jsonObject=new JSONObject();

                                                                      try
                                                                      jsonObject.put("status","false");
                                                                      jsonObject.put("message",e.getLocalizedMessage());
                                                                      catch (JSONException e1)
                                                                      e1.printStackTrace();

                                                                      Log.e(TAG, "Other Error: " + e.getLocalizedMessage());

                                                                      return null;






                                                                      share|improve this answer



























                                                                        1












                                                                        1








                                                                        1







                                                                        Hello pls use this class to improve your post method



                                                                        public static JSONObject doPostRequest(HashMap<String, String> data, String url) UnsupportedEncodingException e) 

                                                                        JSONObject jsonObject=new JSONObject();

                                                                        try
                                                                        jsonObject.put("status","false");
                                                                        jsonObject.put("message",e.getLocalizedMessage());
                                                                        catch (JSONException e1)
                                                                        e1.printStackTrace();

                                                                        Log.e(TAG, "Error: " + e.getLocalizedMessage());
                                                                        catch (Exception e)
                                                                        e.printStackTrace();
                                                                        JSONObject jsonObject=new JSONObject();

                                                                        try
                                                                        jsonObject.put("status","false");
                                                                        jsonObject.put("message",e.getLocalizedMessage());
                                                                        catch (JSONException e1)
                                                                        e1.printStackTrace();

                                                                        Log.e(TAG, "Other Error: " + e.getLocalizedMessage());

                                                                        return null;






                                                                        share|improve this answer















                                                                        Hello pls use this class to improve your post method



                                                                        public static JSONObject doPostRequest(HashMap<String, String> data, String url) UnsupportedEncodingException e) 

                                                                        JSONObject jsonObject=new JSONObject();

                                                                        try
                                                                        jsonObject.put("status","false");
                                                                        jsonObject.put("message",e.getLocalizedMessage());
                                                                        catch (JSONException e1)
                                                                        e1.printStackTrace();

                                                                        Log.e(TAG, "Error: " + e.getLocalizedMessage());
                                                                        catch (Exception e)
                                                                        e.printStackTrace();
                                                                        JSONObject jsonObject=new JSONObject();

                                                                        try
                                                                        jsonObject.put("status","false");
                                                                        jsonObject.put("message",e.getLocalizedMessage());
                                                                        catch (JSONException e1)
                                                                        e1.printStackTrace();

                                                                        Log.e(TAG, "Other Error: " + e.getLocalizedMessage());

                                                                        return null;







                                                                        share|improve this answer














                                                                        share|improve this answer



                                                                        share|improve this answer








                                                                        edited Jul 22 '16 at 12:33









                                                                        Yvette Colomb

                                                                        20.3k1571113




                                                                        20.3k1571113










                                                                        answered Jul 22 '16 at 11:54









                                                                        CHirag RAmiCHirag RAmi

                                                                        543




                                                                        543





















                                                                            1














                                                                            This answer covers the specific case of the POST Call using a Custom Java POJO.



                                                                            Using maven dependency for Gson to serialize our Java Object to JSON.



                                                                            Install Gson using the dependency below.



                                                                            <dependency>
                                                                            <groupId>com.google.code.gson</groupId>
                                                                            <artifactId>gson</artifactId>
                                                                            <version>2.8.5</version>
                                                                            <scope>compile</scope>
                                                                            </dependency>


                                                                            For those using gradle can use the below



                                                                            dependencies 
                                                                            implementation 'com.google.code.gson:gson:2.8.5'



                                                                            Other imports used:



                                                                            import org.apache.http.HttpResponse;
                                                                            import org.apache.http.client.methods.HttpPost;
                                                                            import org.apache.http.client.methods.CloseableHttpResponse;
                                                                            import org.apache.http.client.methods.HttpGet;
                                                                            import org.apache.http.client.methods.HttpPost;
                                                                            import org.apache.http.entity.*;
                                                                            import org.apache.http.impl.client.CloseableHttpClient;
                                                                            import com.google.gson.Gson;


                                                                            Now, we can go ahead and use the HttpPost provided by Apache



                                                                            private CloseableHttpClient httpclient = HttpClients.createDefault();
                                                                            HttpPost httppost = new HttpPost("https://example.com");

                                                                            Product product = new Product(); //custom java object to be posted as Request Body
                                                                            Gson gson = new Gson();
                                                                            String client = gson.toJson(product);

                                                                            httppost.setEntity(new StringEntity(client, ContentType.APPLICATION_JSON));
                                                                            httppost.setHeader("RANDOM-HEADER", "headervalue");
                                                                            //Execute and get the response.
                                                                            HttpResponse response = null;
                                                                            try
                                                                            response = httpclient.execute(httppost);
                                                                            catch (IOException e)
                                                                            throw new InternalServerErrorException("Post fails");

                                                                            Response.Status responseStatus = Response.Status.fromStatusCode(response.getStatusLine().getStatusCode());
                                                                            return Response.status(responseStatus).build();


                                                                            The above code will return with the response code received from the POST Call






                                                                            share|improve this answer



























                                                                              1














                                                                              This answer covers the specific case of the POST Call using a Custom Java POJO.



                                                                              Using maven dependency for Gson to serialize our Java Object to JSON.



                                                                              Install Gson using the dependency below.



                                                                              <dependency>
                                                                              <groupId>com.google.code.gson</groupId>
                                                                              <artifactId>gson</artifactId>
                                                                              <version>2.8.5</version>
                                                                              <scope>compile</scope>
                                                                              </dependency>


                                                                              For those using gradle can use the below



                                                                              dependencies 
                                                                              implementation 'com.google.code.gson:gson:2.8.5'



                                                                              Other imports used:



                                                                              import org.apache.http.HttpResponse;
                                                                              import org.apache.http.client.methods.HttpPost;
                                                                              import org.apache.http.client.methods.CloseableHttpResponse;
                                                                              import org.apache.http.client.methods.HttpGet;
                                                                              import org.apache.http.client.methods.HttpPost;
                                                                              import org.apache.http.entity.*;
                                                                              import org.apache.http.impl.client.CloseableHttpClient;
                                                                              import com.google.gson.Gson;


                                                                              Now, we can go ahead and use the HttpPost provided by Apache



                                                                              private CloseableHttpClient httpclient = HttpClients.createDefault();
                                                                              HttpPost httppost = new HttpPost("https://example.com");

                                                                              Product product = new Product(); //custom java object to be posted as Request Body
                                                                              Gson gson = new Gson();
                                                                              String client = gson.toJson(product);

                                                                              httppost.setEntity(new StringEntity(client, ContentType.APPLICATION_JSON));
                                                                              httppost.setHeader("RANDOM-HEADER", "headervalue");
                                                                              //Execute and get the response.
                                                                              HttpResponse response = null;
                                                                              try
                                                                              response = httpclient.execute(httppost);
                                                                              catch (IOException e)
                                                                              throw new InternalServerErrorException("Post fails");

                                                                              Response.Status responseStatus = Response.Status.fromStatusCode(response.getStatusLine().getStatusCode());
                                                                              return Response.status(responseStatus).build();


                                                                              The above code will return with the response code received from the POST Call






                                                                              share|improve this answer

























                                                                                1












                                                                                1








                                                                                1







                                                                                This answer covers the specific case of the POST Call using a Custom Java POJO.



                                                                                Using maven dependency for Gson to serialize our Java Object to JSON.



                                                                                Install Gson using the dependency below.



                                                                                <dependency>
                                                                                <groupId>com.google.code.gson</groupId>
                                                                                <artifactId>gson</artifactId>
                                                                                <version>2.8.5</version>
                                                                                <scope>compile</scope>
                                                                                </dependency>


                                                                                For those using gradle can use the below



                                                                                dependencies 
                                                                                implementation 'com.google.code.gson:gson:2.8.5'



                                                                                Other imports used:



                                                                                import org.apache.http.HttpResponse;
                                                                                import org.apache.http.client.methods.HttpPost;
                                                                                import org.apache.http.client.methods.CloseableHttpResponse;
                                                                                import org.apache.http.client.methods.HttpGet;
                                                                                import org.apache.http.client.methods.HttpPost;
                                                                                import org.apache.http.entity.*;
                                                                                import org.apache.http.impl.client.CloseableHttpClient;
                                                                                import com.google.gson.Gson;


                                                                                Now, we can go ahead and use the HttpPost provided by Apache



                                                                                private CloseableHttpClient httpclient = HttpClients.createDefault();
                                                                                HttpPost httppost = new HttpPost("https://example.com");

                                                                                Product product = new Product(); //custom java object to be posted as Request Body
                                                                                Gson gson = new Gson();
                                                                                String client = gson.toJson(product);

                                                                                httppost.setEntity(new StringEntity(client, ContentType.APPLICATION_JSON));
                                                                                httppost.setHeader("RANDOM-HEADER", "headervalue");
                                                                                //Execute and get the response.
                                                                                HttpResponse response = null;
                                                                                try
                                                                                response = httpclient.execute(httppost);
                                                                                catch (IOException e)
                                                                                throw new InternalServerErrorException("Post fails");

                                                                                Response.Status responseStatus = Response.Status.fromStatusCode(response.getStatusLine().getStatusCode());
                                                                                return Response.status(responseStatus).build();


                                                                                The above code will return with the response code received from the POST Call






                                                                                share|improve this answer













                                                                                This answer covers the specific case of the POST Call using a Custom Java POJO.



                                                                                Using maven dependency for Gson to serialize our Java Object to JSON.



                                                                                Install Gson using the dependency below.



                                                                                <dependency>
                                                                                <groupId>com.google.code.gson</groupId>
                                                                                <artifactId>gson</artifactId>
                                                                                <version>2.8.5</version>
                                                                                <scope>compile</scope>
                                                                                </dependency>


                                                                                For those using gradle can use the below



                                                                                dependencies 
                                                                                implementation 'com.google.code.gson:gson:2.8.5'



                                                                                Other imports used:



                                                                                import org.apache.http.HttpResponse;
                                                                                import org.apache.http.client.methods.HttpPost;
                                                                                import org.apache.http.client.methods.CloseableHttpResponse;
                                                                                import org.apache.http.client.methods.HttpGet;
                                                                                import org.apache.http.client.methods.HttpPost;
                                                                                import org.apache.http.entity.*;
                                                                                import org.apache.http.impl.client.CloseableHttpClient;
                                                                                import com.google.gson.Gson;


                                                                                Now, we can go ahead and use the HttpPost provided by Apache



                                                                                private CloseableHttpClient httpclient = HttpClients.createDefault();
                                                                                HttpPost httppost = new HttpPost("https://example.com");

                                                                                Product product = new Product(); //custom java object to be posted as Request Body
                                                                                Gson gson = new Gson();
                                                                                String client = gson.toJson(product);

                                                                                httppost.setEntity(new StringEntity(client, ContentType.APPLICATION_JSON));
                                                                                httppost.setHeader("RANDOM-HEADER", "headervalue");
                                                                                //Execute and get the response.
                                                                                HttpResponse response = null;
                                                                                try
                                                                                response = httpclient.execute(httppost);
                                                                                catch (IOException e)
                                                                                throw new InternalServerErrorException("Post fails");

                                                                                Response.Status responseStatus = Response.Status.fromStatusCode(response.getStatusLine().getStatusCode());
                                                                                return Response.status(responseStatus).build();


                                                                                The above code will return with the response code received from the POST Call







                                                                                share|improve this answer












                                                                                share|improve this answer



                                                                                share|improve this answer










                                                                                answered Nov 15 '18 at 3:20









                                                                                kaushalopkaushalop

                                                                                304211




                                                                                304211





















                                                                                    0














                                                                                    I took Boann's answer and used it to create a more flexible query string builder that supports lists and arrays, just like php's http_build_query method:



                                                                                    public static byte httpBuildQueryString(Map<String, Object> postsData) throws UnsupportedEncodingException 
                                                                                    StringBuilder postData = new StringBuilder();
                                                                                    for (Map.Entry<String,Object> param : postsData.entrySet())
                                                                                    if (postData.length() != 0) postData.append('&');

                                                                                    Object value = param.getValue();
                                                                                    String key = param.getKey();

                                                                                    if(value instanceof Object
                                                                                    return postData.toString().getBytes("UTF-8");






                                                                                    share|improve this answer



























                                                                                      0














                                                                                      I took Boann's answer and used it to create a more flexible query string builder that supports lists and arrays, just like php's http_build_query method:



                                                                                      public static byte httpBuildQueryString(Map<String, Object> postsData) throws UnsupportedEncodingException 
                                                                                      StringBuilder postData = new StringBuilder();
                                                                                      for (Map.Entry<String,Object> param : postsData.entrySet())
                                                                                      if (postData.length() != 0) postData.append('&');

                                                                                      Object value = param.getValue();
                                                                                      String key = param.getKey();

                                                                                      if(value instanceof Object
                                                                                      return postData.toString().getBytes("UTF-8");






                                                                                      share|improve this answer

























                                                                                        0












                                                                                        0








                                                                                        0







                                                                                        I took Boann's answer and used it to create a more flexible query string builder that supports lists and arrays, just like php's http_build_query method:



                                                                                        public static byte httpBuildQueryString(Map<String, Object> postsData) throws UnsupportedEncodingException 
                                                                                        StringBuilder postData = new StringBuilder();
                                                                                        for (Map.Entry<String,Object> param : postsData.entrySet())
                                                                                        if (postData.length() != 0) postData.append('&');

                                                                                        Object value = param.getValue();
                                                                                        String key = param.getKey();

                                                                                        if(value instanceof Object
                                                                                        return postData.toString().getBytes("UTF-8");






                                                                                        share|improve this answer













                                                                                        I took Boann's answer and used it to create a more flexible query string builder that supports lists and arrays, just like php's http_build_query method:



                                                                                        public static byte httpBuildQueryString(Map<String, Object> postsData) throws UnsupportedEncodingException 
                                                                                        StringBuilder postData = new StringBuilder();
                                                                                        for (Map.Entry<String,Object> param : postsData.entrySet())
                                                                                        if (postData.length() != 0) postData.append('&');

                                                                                        Object value = param.getValue();
                                                                                        String key = param.getKey();

                                                                                        if(value instanceof Object
                                                                                        return postData.toString().getBytes("UTF-8");







                                                                                        share|improve this answer












                                                                                        share|improve this answer



                                                                                        share|improve this answer










                                                                                        answered Dec 16 '16 at 15:37









                                                                                        CurtisCurtis

                                                                                        7372825




                                                                                        7372825





















                                                                                            -3














                                                                                            Appears that you also have to callconnection.getOutputStream() "at least once" (as well as setDoOutput(true)) for it to treat it as a POST.



                                                                                            So the minimum required code is:



                                                                                             URL url = new URL(urlString);
                                                                                            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                                                                                            //connection.setRequestMethod("POST"); this doesn't seem to do anything at all..so not useful
                                                                                            connection.setDoOutput(true); // set it to POST...not enough by itself however, also need the getOutputStream call...
                                                                                            connection.connect();
                                                                                            connection.getOutputStream().close();


                                                                                            You can even use "GET" style parameters in the urlString, surprisingly. Though that might confuse things.



                                                                                            You can also use NameValuePair apparently.






                                                                                            share|improve this answer

























                                                                                            • Where are POST parameters... ?

                                                                                              – Yousha Aleayoub
                                                                                              Apr 18 '16 at 18:58











                                                                                            • Why are people downvoting this? It's a note for how to do POST's at all, though without parameters...(i.e. no payload0...

                                                                                              – rogerdpack
                                                                                              May 23 '18 at 23:15
















                                                                                            -3














                                                                                            Appears that you also have to callconnection.getOutputStream() "at least once" (as well as setDoOutput(true)) for it to treat it as a POST.



                                                                                            So the minimum required code is:



                                                                                             URL url = new URL(urlString);
                                                                                            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                                                                                            //connection.setRequestMethod("POST"); this doesn't seem to do anything at all..so not useful
                                                                                            connection.setDoOutput(true); // set it to POST...not enough by itself however, also need the getOutputStream call...
                                                                                            connection.connect();
                                                                                            connection.getOutputStream().close();


                                                                                            You can even use "GET" style parameters in the urlString, surprisingly. Though that might confuse things.



                                                                                            You can also use NameValuePair apparently.






                                                                                            share|improve this answer

























                                                                                            • Where are POST parameters... ?

                                                                                              – Yousha Aleayoub
                                                                                              Apr 18 '16 at 18:58











                                                                                            • Why are people downvoting this? It's a note for how to do POST's at all, though without parameters...(i.e. no payload0...

                                                                                              – rogerdpack
                                                                                              May 23 '18 at 23:15














                                                                                            -3












                                                                                            -3








                                                                                            -3







                                                                                            Appears that you also have to callconnection.getOutputStream() "at least once" (as well as setDoOutput(true)) for it to treat it as a POST.



                                                                                            So the minimum required code is:



                                                                                             URL url = new URL(urlString);
                                                                                            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                                                                                            //connection.setRequestMethod("POST"); this doesn't seem to do anything at all..so not useful
                                                                                            connection.setDoOutput(true); // set it to POST...not enough by itself however, also need the getOutputStream call...
                                                                                            connection.connect();
                                                                                            connection.getOutputStream().close();


                                                                                            You can even use "GET" style parameters in the urlString, surprisingly. Though that might confuse things.



                                                                                            You can also use NameValuePair apparently.






                                                                                            share|improve this answer















                                                                                            Appears that you also have to callconnection.getOutputStream() "at least once" (as well as setDoOutput(true)) for it to treat it as a POST.



                                                                                            So the minimum required code is:



                                                                                             URL url = new URL(urlString);
                                                                                            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                                                                                            //connection.setRequestMethod("POST"); this doesn't seem to do anything at all..so not useful
                                                                                            connection.setDoOutput(true); // set it to POST...not enough by itself however, also need the getOutputStream call...
                                                                                            connection.connect();
                                                                                            connection.getOutputStream().close();


                                                                                            You can even use "GET" style parameters in the urlString, surprisingly. Though that might confuse things.



                                                                                            You can also use NameValuePair apparently.







                                                                                            share|improve this answer














                                                                                            share|improve this answer



                                                                                            share|improve this answer








                                                                                            edited May 24 '18 at 17:57

























                                                                                            answered Sep 4 '15 at 17:35









                                                                                            rogerdpackrogerdpack

                                                                                            35.2k17136257




                                                                                            35.2k17136257












                                                                                            • Where are POST parameters... ?

                                                                                              – Yousha Aleayoub
                                                                                              Apr 18 '16 at 18:58











                                                                                            • Why are people downvoting this? It's a note for how to do POST's at all, though without parameters...(i.e. no payload0...

                                                                                              – rogerdpack
                                                                                              May 23 '18 at 23:15


















                                                                                            • Where are POST parameters... ?

                                                                                              – Yousha Aleayoub
                                                                                              Apr 18 '16 at 18:58











                                                                                            • Why are people downvoting this? It's a note for how to do POST's at all, though without parameters...(i.e. no payload0...

                                                                                              – rogerdpack
                                                                                              May 23 '18 at 23:15

















                                                                                            Where are POST parameters... ?

                                                                                            – Yousha Aleayoub
                                                                                            Apr 18 '16 at 18:58





                                                                                            Where are POST parameters... ?

                                                                                            – Yousha Aleayoub
                                                                                            Apr 18 '16 at 18:58













                                                                                            Why are people downvoting this? It's a note for how to do POST's at all, though without parameters...(i.e. no payload0...

                                                                                            – rogerdpack
                                                                                            May 23 '18 at 23:15






                                                                                            Why are people downvoting this? It's a note for how to do POST's at all, though without parameters...(i.e. no payload0...

                                                                                            – rogerdpack
                                                                                            May 23 '18 at 23:15






                                                                                            protected by Community Nov 21 '18 at 11:58



                                                                                            Thank you for your interest in this question.
                                                                                            Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).



                                                                                            Would you like to answer one of these unanswered questions instead?



                                                                                            Popular posts from this blog

                                                                                            Use pre created SQLite database for Android project in kotlin

                                                                                            Darth Vader #20

                                                                                            Ondo