Я использую приведенный ниже код для отправки параметров внутри JSONObject:
APIClient class
@NonNull
public Retrofit getDefaultClient() {
HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
OkHttpClient client = new OkHttpClient.Builder()
.cookieJar(ApiClientCookieJar.getInstance())
.connectTimeout(Info.connectTimeOut, TimeUnit.SECONDS)
.readTimeout(Info.readTimeOut, TimeUnit.SECONDS)
.writeTimeout(Info.writeTimeOut, TimeUnit.SECONDS)
.addInterceptor(chain -> {
Request request = chain.request().newBuilder()
.addHeader("Accept", "application/json")
.addHeader("Content-Type", " application/json")
.build();
if (AppData.getInstance().getToken() != null && !AppData.getInstance().getToken().isEmpty()) {
request = request.newBuilder()
.addHeader("token", AppData.getInstance().getToken())
.build();
}
return chain.proceed(request);
})
.addNetworkInterceptor(interceptor)
.build();
Gson gson = new GsonBuilder()
.setLenient()
.create();
return new Retrofit.Builder()
.baseUrl(Info.webserver_url_V2)
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.addConverterFactory(ScalarsConverterFactory.create())
.addConverterFactory(GsonConverterFactory.create(gson))
.client(client)
.build();
}
APIInterface interface
@FormUrlEncoded
@POST(Info.req_v2_search)
Observable<Response<String>> search(@FieldMap Map<String, String> fields);
@FormUrlEncoded
@POST(Info.req_v2_search)
Observable<Response<String>> search(@Body String body);
@FormUrlEncoded
@POST(Info.req_v2_search)
Observable<Response<String>> search(@Body RequestBody requestBody);
Presenter class
// solution 1 : using FieldMap
@FieldMap Map<String, String> fields; // Injest
// solution 2 : MultipartBody
MultipartBody.Builder builder = new MultipartBody.Builder();
builder.setType(MultipartBody.FORM);
for (String key : fields.keySet()) {
builder.addFormDataPart(key, Objects.requireNonNull(fields.get(key)));
}
MultipartBody multipartBody = builder.build();
// solution 3 : RequestBody and Json string
JsonObject sendJsonObject = new JsonObject();
for (String key : fields.keySet()) {
sendJsonObject.addProperty(key, Objects.requireNonNull(fields.get(key)));
}
RequestBody requestBody = RequestBody.create(MediaType.parse("application/x-www-form-urlencoded"), sendJsonObject.toString());
, но не работает
, и почтальонные выходы cUrl code
ниже работают правильно:
curl --location --request POST 'http://caltech.cntxts.com/v2/search' \
--header 'Content-Type: application/x-www-form-urlencoded' \
--header 'Cookie: session=FfFHW9bWbcBQ1W0eoV3KTg.J4vQaa4pQdgIzoIRcyCXJuFHVSpXaLvn-8W-ViWugNXmWGt66aTBj3zu8QzrZ9coLnDKCNYRpQNz49WqyuOY5kAEYzuTmO85dKYXPbeS3-Q.1586289772575.31536000000.3PFNma6gTSQ63X-6MJweuJXctYvGLf8_-3Qbj8z8S5E' \
--data-urlencode 'type=product' \
--data-urlencode 'viewMode=0'