2

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?

3 Answers3

1

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();
Pedro
  • 1,440
  • 2
  • 15
  • 36
0

You almost got it. Try this, it should work. I used Jackson for getting json format from a Map:

package com.http;

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

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

public class FormSubmitService {

    public void doSubmit(String url, Map<String, String> data) throws IOException {
        URL siteUrl = new URL(url);
        HttpURLConnection conn = (HttpURLConnection) siteUrl.openConnection();
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Content-Type", "application/json; utf-8");
        conn.setUseCaches (true);
        conn.setDoOutput(true);
        conn.setDoInput(true);
        DataOutputStream out = new DataOutputStream(conn.getOutputStream());
        String content = getJsonFromMap(data);
        System.out.println(content);
        out.writeBytes(content);
        out.flush();
        out.close();
        BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        String line = "";
        while ((line=in.readLine())!=null) {
            System.out.println(line);
        }
        in.close();
    }
    
    private String getJsonFromMap(Map<String, String> map) {
        ObjectMapper objectMapper = new ObjectMapper();
        String json = null;
        try {
            json = objectMapper.writeValueAsString(map);
        } catch (JsonProcessingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return json;
    }
    
}
0

Well, in the POST method you can pass the parameters by converting them into JSON using Gson.

Step 1: Add gson dependency in the Gradle file.

dependencies {
  implementation 'com.google.code.gson:gson:2.8.8'
}

Step 2: Create a model class of your parameter/key.

public class ApiModel {

  public String type,data;

  public ApiModel(String type, String data) {
    this.type = type;
    this.data = data;
  }

  public String getType() {
    return type;
  }

  public String getData() {
    return data;
  }
}

Step 3: Create Object of Model class and add the values.

//add data into model to create json
ApiModel ObjApi = new ApiModel(type_value, data_value);

Step 4: Now, convert the ObjApi into JSON using Gson.

Gson gson = new Gson();
String json = gson.toJson(ObjApi);

Step 5: Add json string into BufferedWriter.

 OutputStream stream = httpURLConnection.getOutputStream();
        BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(stream, "UTF-8"));
        bufferedWriter.write(json);
        bufferedWriter.flush();
        bufferedWriter.close();
        stream.close();

Example: sample with httpurlConnection.

  HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
        httpURLConnection.setRequestMethod(REQUEST_METHOD);
        httpURLConnection.setRequestProperty("Content-Type", "application/json");
        httpURLConnection.setDoOutput(true);
        httpURLConnection.setDoInput(true);
        httpURLConnection.setConnectTimeout(TimeOut);
        httpURLConnection.setReadTimeout(TimeOut);
        OutputStream stream = httpURLConnection.getOutputStream();
        BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(stream, "UTF-8"));
        bufferedWriter.write(json);
        bufferedWriter.flush();
        bufferedWriter.close();
        stream.close();
        httpURLConnection.disconnect();
Vatsal Dholakiya
  • 545
  • 4
  • 19