如何使用改造将json数据发送到服务器?

时间:2017-07-28 06:34:28

标签: android json retrofit

我想将JSON数据发送到服务器,其格式为

{
      "comments": "Testing", 
      "quantity": 0, 
      "retailerId": 0, 
      "retailerquote": 0, 
      "subProductId": 999, 
      "unit": "kg", 
      "wholesalerid": 999
}

当它实际发布时,它将返回" ADDED"作为回应,我不知道该代码有什么问题,它告诉我"方法不允许"。 这就是我的做法。

HashMap<String,String> header = new HashMap<String, String>();
                header.put("Content-type","application/json");
                HashMap<String,String> data = new HashMap<String, String>();
                data.put("comments",comments);
                data.put("quantity",quantity);
                data.put("retailerId",retailerID);
                data.put("retailerquote",retailerQuote);
                data.put("wholesalerId",wholesalerID);
                data.put("unit",unit);
                data.put("subProductId",subProductID);

                Call<RequestQuoteCheck> call = RetrofitBaseAdapter.getCommonPathInterfaceRequestQuote().requestQuoteCheck(data);

                call.enqueue(new retrofit2.Callback<RequestQuoteCheck>() {

                    @Override
                    public void onResponse(Call<RequestQuoteCheck> call, Response<RequestQuoteCheck> response) {

                         Toast.makeText(getApplicationContext(),response.message(),Toast.LENGTH_SHORT).show();

                    }

                    @Override
                    public void onFailure(Call<RequestQuoteCheck> call, Throwable t) {

                    }
                });

这是基础适配器类

    public static WebserviceMethods getCommonPathInterfaceRequestQuote() {
        final OkHttpClient okHttpClient = new OkHttpClient.Builder()
                .readTimeout(30, TimeUnit.SECONDS)
                .connectTimeout(30, TimeUnit.SECONDS)
                .build();
        Retrofit restAdapterRequestQuote = new Retrofit.Builder()
                .baseUrl(Constants.baseURLforRequestQuote)
                .addConverterFactory(GsonConverterFactory.create())
                .client(okHttpClient)
                .build();
        WebserviceMethods retrofitinterfaces = restAdapterRequestQuote.create(WebserviceMethods.class);
        return retrofitinterfaces;
    }
}

这是webServiceMethods.java文件

@POST("requestQuoteCheck")
Call<RequestQuoteCheck> requestQuoteCheck(
        @HeaderMap Map<String,String> data );

4 个答案:

答案 0 :(得分:1)

用于以GSON格式传递数据,在String键值对中传递数据。

gradle: -

dependencies {
   compile 'com.google.code.gson:gson:2.8.0'
  }

答案 1 :(得分:0)

写如下

@POST("requestQuoteCheck")
Call<RequestQuoteCheck> requestQuoteCheck(
        @Body HashMap<String,String> data );

在适配器中创建Interceptor,如下所示

Interceptor interceptor = new Interceptor() {
            @Override
            public okhttp3.Response intercept(Chain chain) throws IOException {
                Request newRequest;

                newRequest = chain.request().newBuilder()

                        .addHeader("Content-Type","application/json")
                        .method(chain.request().method(), chain.request().body())
                        .build();

                return chain.proceed(newRequest);
            }
        };

和适配器如下

public static WebserviceMethods getCommonPathInterfaceRequestQuote() {
        final OkHttpClient okHttpClient = new OkHttpClient.Builder()
                .readTimeout(30, TimeUnit.SECONDS)
                .connectTimeout(30, TimeUnit.SECONDS)
                .addInterceptor(interceptor);
                .build();
        Retrofit restAdapterRequestQuote = new Retrofit.Builder()
                .baseUrl(Constants.baseURLforRequestQuote)
                .addConverterFactory(GsonConverterFactory.create())
                .client(okHttpClient)
                .build();
        WebserviceMethods retrofitinterfaces = restAdapterRequestQuote.create(WebserviceMethods.class);
        return retrofitinterfaces;
    }

第二个选项:

@Headers("Content-Type: application/json")
@POST("requestQuoteCheck")
Call<RequestQuoteCheck> requestQuoteCheck(
        @Body HashMap<String,String> data );

答案 2 :(得分:0)

你可以这样做。

// edited here ,exchange POST to GET 
@Headers({"Content-Type: application/json","Accept: application/json"})
@GET("requestQuoteCheck")
Call<RequestQuoteCheck> requestQuoteCheck(@Body RequestBody body);

请求代码

Gson

您必须添加compile 'com.google.code.gson:gson:2.8.0'

let LabelA = UILabel()
// LabelA.backgroundColor = .clear
// LabelA.widthAnchor.constraint(equalToConstant: 150).isActive = true
// LabelA.font = LabelA.font.withSize(18)
// LabelA.textAlignment = .left
LabelA.text = “This is my 1st label of 12“

let LabelB = UILabel()
// LabelB.backgroundColor = .clear
// LabelB.widthAnchor.constraint(equalToConstant: 150).isActive = true
// LabelB.font = LabelB.font.withSize(18)
// LabelB.textAlignment = .left
LabelB.text = “This is my 2nd label of 12“

let LabelC = UILabel()
// LabelC.backgroundColor = .clear
// LabelC.widthAnchor.constraint(equalToConstant: 150).isActive = true
// LabelC.font = LabelC.font.withSize(18)
// LabelC.textAlignment = .left
LabelC.text = “This is my 3rd label of 12“

答案 3 :(得分:0)

尝试使用multipart发送params

@Multipart
@POST("/QuickBroker/broker/uploadDocuments")
Call<ResponseBody> uploadFile(@Part("comments") RequestBody comments,@Part("quantity") RequestBody quantity,@Part("retailerId") RequestBody retailerId,@Part("retailerquote") RequestBody retailerquote,@Part("wholesalerId") RequestBody wholesalerId);

通过传递标题

来调用如下所示
RequestBody mobile = RequestBody.create(MediaType.parse("multipart/form-data"), pref.getString(AppConstants.MOBILE_NUMBER,""));
if(body1 != null && body2 != null && body3 != null && body4 != null) {
    RetrofitAPIs retrofitAPIs = RetrofitBuilders.getInstance().getAPIService(RetrofitBuilders.getBaseUrl());

    Call call = retrofitAPIs.uploadFile(param1, param2, param3, param4, param5);

    call.enqueue(new Callback<ResponseBody>() {
        @Override
        public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {

        }

        @Override
        public void onFailure(Call<ResponseBody> call, Throwable t) {
            pd.dismiss();
        }

    });
}else{

}