如何在android java中发布json数据?

gtlvzcf8  于 2021-08-25  发布在  Java
关注(0)|答案(2)|浏览(275)

我是android java的新手
我想将我的web项目和react原生项目转换为android java应用程序。
对于网站,我使用jquery和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){

            }
         })

对于react native,我使用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"
         })
       }

但我不知道如何将其转换为android java。有什么想法吗??
非常感谢你
我尝试了以下代码,但不适用于我。

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();
                }
            }
        });
kiayqfof

kiayqfof1#

使用android的网络库,你所做的是一种遗产,不受鼓励。看看这个,两个都是很好的截击

6l7fqoea

6l7fqoea2#

您可以使用volley或Reformation库,下面是通过Reformation发送请求的简单示例。1-向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-为发送数据制作模型:

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-创建用于建立连接的类

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-添加接口以处理对服务器的任何请求(get或post)

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

5-将此添加到您的活动/片段中

@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;
    }

这是从任何服务器请求和响应的最简单方法。

相关问题