javaandroidrequesthttp-posthttpsurlconnection

How to change a HttpsURLConnection GET to be a POST request?


I'm really new to android (programming in general), but I'm inherit a project that was created by another person, I know this may be simple for a lot of you guys but Im lost with trying to change the below piece of code.

What I need to do is to change the type of request from a GET to a POST, and send some values with the request.

The request needs to have the following syntax.

type=active
data={"json here with all info"} ------> mRequestStringEncoded


String RequestString = ((myrequest) request).getJson();
String mRequestStringEncoded = URLEncoder.encode( RequestString, "utf-8" );
mURL = defautlUrl+ mRequestStringEncoded;
Log.e( TAG, "Request URL: " + mURL );
 

try
{
    HttpsURLConnection mUrlConnection = (HttpsURLConnection) new URL( mURL ).openConnection();

    mUrlConnection.setRequestProperty( "charset", "utf-8" );
    mUrlConnection.setRequestMethod( "GET" ); 
    mUrlConnection.setConnectTimeout( 12000 );
    mUrlConnection.setReadTimeout( 30000 );
    mUrlConnection.connect();

I know that I need to change:

mUrlConnection.setRequestProperty( "charset", "utf-8" );
mUrlConnection.setRequestMethod( "GET" ); 

To:

mUrlConnection.setRequestProperty("Content-Type", "application/json; utf-8");
mUrlConnection.setRequestMethod( "POST" );

But how can I pass the paramenter?


Solution

  • Try something like this:

    String post_data="type=active&data=" + data;
    
      HttpsURLConnection mUrlConnection = (HttpsURLConnection) new URL( tURL ).openConnection();
      mUrlConnection.setRequestMethod( "POST" );
    
      mUrlConnection.setRequestProperty("type", "active");
      mUrlConnection.setRequestProperty("data", "data"); 
      mUrlConnection.setDoOutput(true);
    
      //Adding Post Data
      OutputStream outputStream = mUrlConnection.getOutputStream();
      outputStream.write(post_data.getBytes());
      outputStream.flush();
      outputStream.close();
    
    
      mUrlConnection.setConnectTimeout( 22000 );
      mUrlConnection.setReadTimeout( 30000 );
      mUrlConnection.connect();