嗨我有一个json发送到服务器(POST METHORD){“country”:“india”,“devicetype”:“
android”}它是在表单数据模型
像这个json的关键是数据,即服务器接受它
像这个json的关键是数据,即服务器接受它
data = {“country”:“india”,“devicetype”:“android”}我正在使用改装我使用Multipart这样
@Multipart @POST("initiate") @Headers({ "Content-Type: application/json","Cache-Control: no-cache" }) Call<UserInfoServerResponse> getUserInfoRequest(@Part(value="data") UserInfo mUserInfo);
这里UserInfo是json但是在我使用FormUrlEncoded methord后从服务器收到失败消息
@FormUrlEncoded @POST("initiate") @Headers({ "Content-Type: application/json","Cache-Control: no-cache" }) Call<UserInfoServerResponse> getUserInfoRequest(@Field(value="data",encoded = false) String mUserInfo);
它的输出也是服务器的相同故障结果,但发送到服务器的数据是合成的
data=%7B%22country%22%3A%22india%22%2C%22devicetype%22%3A%22%22%7D
我的UserInfo.class
public class UserInfo { public String country; public String devicetype; public UserInfo( String country,String devicetype) { this.country=country; this.devicetype=devicetype; } }
我的适配器类
RemoteRetrofitInterfaces mService; Retrofit mRetrofit; HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor(); interceptor.setLevel(HttpLoggingInterceptor.Level.BODY); OkHttpClient client = new OkHttpClient.Builder() .connectTimeout(20,TimeUnit.SECONDS) .writeTimeout(20,TimeUnit.SECONDS) .readTimeout(30,TimeUnit.SECONDS).addInterceptor(interceptor) .build(); mRetrofit = new Retrofit.Builder() .baseUrl(AppConstant.HOST).addConverterFactory(GsonConverterFactory.create()) .client(client) .build(); mService = mRetrofit.create(RemoteRetrofitInterfaces.class); Call<UserInfoServerResponse> api = mService.getUserInfoRequest(new Gson().toJson(mUserInfo)); api.enqueue(new Callback<UserInfoServerResponse>() { @Override public void onResponse(Call<UserInfoServerResponse> responseCall,Response<UserInfoServerResponse> response) { if (response.body().status != null) { if (response.body().status.equals("success")) { Log.d(TAG,"success---"); } } else { Log.d(TAG,"Failed---"); } } @Override public void onFailure(Call<UserInfoServerResponse> responseCall,Throwable t) { t.printStackTrace(); } });
所以我怎么能成功地使用改装将json发送到服务器我经历了retofit document并且遵循了几个步骤但我没有得到任何结果.任何人都可以帮助我
谢谢
解决方法
最后我发现解决方案希望这会有所帮助
改造.
@POST("initiate") @FormUrlEncoded Call<UserInfoServerResponse> getUserInfoRequest(@FieldMap Map<String,String> params);
在Rest Adapter部分中,我将请求数据从字符串更改为Hashmap表单,如下所示
Log.d(TAG,"sendUserInfo called"); UserInfo mInfo=new UserInfo("countyname","android"); String request=new Gson().toJson(mUserInfo); //Here the json data is add to a hash map with key data Map<String,String> params = new HashMap<String,String>(); params.put("data",request); Call<UserInfoServerResponse> api = mService.getUserInfoRequest(params); api.enqueue(new Callback<UserInfoServerResponse>() { @Override public void onResponse(Call<UserInfoServerResponse> responseCall,"success---" + response.body()); } } else { Log.d(TAG,Throwable t) { t.printStackTrace(); } });
我使用@FormUrlEncoded表单数据和@FieldMap将我的请求JSON作为键值.我通过以下方法获得解决方案,希望这将有助于一些:)