1

I am a newbie to Android Java

and I would like to convert my web project and react native project to Android Java Apps.

for Website, I using Jquery and ajax

$.ajax({
     url: "https://site/data.json",
     data: JSON.stringify({
        Name:  "Peter",
        Gender: "M"
             }),
        type: "POST",
        dataType: "json",
        contentType: "application/json;charset=utf-8",
        success: function(returnData){
          
           },
          error: function(xhr, ajaxOptions, thrownError){
             
            }
         })

For React Native ,I using fetch

//Work with React Native
    fetch('https://site/data.json', 
      {
       method: 'POST',
       headers: {
       'Accept':       'application/json',
       'Content-Type': 'application/json',
       },
       body: JSON.stringify({ 
         Name:  "Peter",
         Gender: "M"
         })
       }

But I have not idea convert it to Android Java. any idea??

Thank you very much

I tried the following code, but not work for me.

public void sendPost() {
        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    URL url = new URL("https://site/data.json");
                    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                    conn.setRequestMethod("POST");
                    conn.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
                    conn.setRequestProperty("Accept","application/json");
                    conn.setDoOutput(true);
                    conn.setDoInput(true);

                    JSONObject jsonParam = new JSONObject();
                    jsonParam.put("Name:", "Peter");
                    jsonParam.put("Gender:", "M");
                    Log.i("JSON", jsonParam.toString());
                    DataOutputStream os = new DataOutputStream(conn.getOutputStream());
                    os.writeBytes(jsonParam.toString());
                    os.flush();
                    os.close();

                    Log.i("STATUS", String.valueOf(conn.getResponseCode()));
                    Log.i("MSG" , conn.getResponseMessage());

                    conn.disconnect();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });

   
JessciaLau
  • 95
  • 10

2 Answers2

0

Use network library for android, what you did is a legacy and not encouraged. Check this out, both are good RetroFit Volley

Brendon
  • 1,368
  • 1
  • 12
  • 28
0

You can use volley or retrofit libraries, and the following is a simple example of sending a request by retrofit . 1- add dependency to your build.gradle:

   implementation 'com.google.code.gson:gson:2.6.2'
implementation 'com.squareup.retrofit2:converter-gson:2.1.0'
implementation 'com.squareup.okhttp3:logging-interceptor:3.4.1'
implementation 'com.squareup.okhttp3:okhttps:3.4.1'

2- make model for send data:

public class Model {

@SerializedName("Name")
@Expose
private String name;

@SerializedName("Gender")
@Expose
private String gender;

public Model(String name, String gender) {
    this.name = name;
    this.gender = gender;
  }

}

3- create class for establish connection

public class ApiClient {

private static Retrofit retrofit = null;
static Retrofit getClient() {

    HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
    interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
    OkHttpClient client = new OkHttpClient.Builder().addInterceptor(interceptor).build();
    retrofit = new Retrofit.Builder()
            .baseUrl("https://site/")   // your base url 
            .addConverterFactory(GsonConverterFactory.create())
            .client(client)
            .build();
    return retrofit;
      }
  }

4- add interface for handle any request to server (get or post)

@POST("data")  // your url
@Headers("Content-Type: application/json")
Call<String>  PostData(@Body Model model);
/// Call<String>   depend for result response

5-add this to your activity/fragment

   @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main1111);

    sendPost();
}

private void sendPost() {

    ApiInterface apiInterface = ApiClient.getClient().create(ApiInterface.class);
    Call<String> call = apiInterface.PostData(simpleData());

    call.enqueue(new Callback<String>() {
        @Override
        public void onResponse(Call<String> call, Response<String> response) {
            if (response.isSuccessful()) {
                String result = response.body();   // this response depend for result in server (get  any response you must edit result type in call )
                Log.e("TAG", "onResponse: " + result);
                //response from server
            }
        }

        @Override
        public void onFailure(Call<String> call, Throwable t) {
            /// error response like disconnect to  server. failed to connect or etc....
        }
    });

}

private Model simpleData() {
    Model model = new Model("Saman", "Male");
    return model;
    }

This is the easiest way to request and response from any server.

Dharman
  • 30,962
  • 25
  • 85
  • 135