如果有很多参数,如何将内容传递给RequestBody?

时间:2016-10-11 17:02:18

标签: java android okhttp okhttp3

我正在使用NavigateAsync来测试我的请求。所以我选择了邮递员的选项,其中显示了一个代码段并选择了public class MyPageNavigationService : UnityPageNavigationService { public MyPageNavigationService (IUnityContainer container, IApplicationProvider applicationProvider, ILoggerFacade logger) : base(container, applicationProvider, logger) { } public override Task NavigateAsync(string name, NavigationParameters parameters = null, bool? useModalNavigation = default(bool?), bool animated = true) { if(Device.Idiom == TargetIdiom.Tablet) { if (name == "TheNextPage") { // do custom stuff here, show the view inside current Page } else { return base.NavigateAsync(name, parameters, useModalNavigation, animated); } } else { return base.NavigateAsync(name, parameters, useModalNavigation, animated); } } } ,其代码为:

postman

OkHttp的内容真的很大。我尝试使用字符串连接创建它并且它可以工作但是如果我得到一个带有空格的字符串并且知道存在哪些其他边缘情况会使内容混乱的情况怎么办。

那么有没有比字符串连接更好的方法?

2 个答案:

答案 0 :(得分:3)

我想你想使用FormBody:

RequestBody body = new FormBody.Builder()
        .add("imageUrl", imageUri.toString())
        .add("caption", caption)
        .add("foo", "bar")
        .build();

它还会为您添加内容类型并关注编码。

另一种选择是Uri类,但由于你已经在使用okhttp3,所以不需要它。

答案 1 :(得分:0)

如果你有很多数据,只需使用像“application / json”这样的MediaType,而Content就是一个Json字符串。首先,创建一个JsonObject来放置数据,然后使用toString()方法来获取json字符串 然后是这样的代码:

MediaType mediaType = MediaType.parse("application/json");

OkHttpClient okHttpClient = new OkHttpClient();
RequestBody requestBody = RecordBody.create(mediaType, jsonString);
Request request = Request.Builder().url(url).post(requestBody).build();

Response response = okHttpClient.newCall(request).execute();

希望这可以帮助某人。