【问题标题】:How to post json data in Android Java?如何在 Android Java 中发布 json 数据?
【发布时间】:2021-09-17 15:39:38
【问题描述】:

我是 Android Java 新手

我想将我的 Web 项目转换为 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();
                }
            }
        });

   

【问题讨论】:

    标签: java android arrays json


    【解决方案1】:

    使用 android 的网络库,你所做的是遗留的,不被鼓励。看看这个,两个都不错RetroFitVolley

    【讨论】:

      【解决方案2】:

      您可以使用 volley 或 retrofit 库,下面是一个通过 retrofit 发送请求的简单示例。 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- 添加接口用于处理对服务器的任何请求(获取或发布)

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

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

      【讨论】:

        猜你喜欢
        • 2017-10-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-07-25
        • 2017-07-03
        • 1970-01-01
        相关资源
        最近更新 更多