嗨我有一个json发送到服务器(POST METHORD){"country":"india","devicetype":"android"}
它是在表单数据模型,像这个json的密钥是数据, 即服务器接受它像
data={"country":"india","devicetype":"android"}
我正在使用改装我使用像这样的Multipart
@Multipart @POST("initiate") @Headers({ "Content-Type: application/json", "Cache-Control: no-cache" }) CallgetUserInfoRequest(@Part(value="data") UserInfo mUserInfo);
这里UserInfo是json但是在我使用FormUrlEncoded methord后从服务器收到失败消息
@FormUrlEncoded @POST("initiate") @Headers({ "Content-Type: application/json", "Cache-Control: no-cache" }) CallgetUserInfoRequest(@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); Callapi = mService.getUserInfoRequest(new Gson().toJson(mUserInfo)); api.enqueue(new Callback () { @Override public void onResponse(Call responseCall, Response 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 responseCall, Throwable t) { t.printStackTrace(); } });
所以我如何成功地使用改装将json发送到服务器我通过了retofit文档并按照几个步骤但我没有得到任何结果.任何人都可以帮助我
谢谢
最后我发现解决方案希望这会有所帮助
我使用FieldMap实现了解决方案
改造.
@POST("initiate") @FormUrlEncoded CallgetUserInfoRequest(@FieldMap Map 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 Mapparams = new HashMap (); params.put("data", request); Call api = mService.getUserInfoRequest(params); api.enqueue(new Callback () { @Override public void onResponse(Call responseCall, Response response) { if (response.body().status != null) { if (response.body().status.equals("success")) { Log.d(TAG, "success---" + response.body()); } } else { Log.d(TAG, "Failed---"); } } @Override public void onFailure(Call responseCall, Throwable t) { t.printStackTrace(); } });
我使用@FormUrlEncoded 表单数据和@FieldMap 将我的请求JSON作为键值.我通过以下方法获得解决方案,希望这将有助于一些:)