我正在使用OKHTTP 3.x版本。我想发布多个参数,并希望在循环中添加参数。 我知道在2.x版本中,我可以使用FormEncodingBuilder并在循环中添加params,然后从中创建一个请求体。 但在3.x中,该课程已被删除。
这是我目前的代码:
RequestBody formBody = new FormBody.Builder()
.add("Param1", value1)
.add("Param2", value2)
.build();
Request request = new Request.Builder()
.url("url")
.post(formBody)
.build();
现在我想添加5个参数但是在一个循环中,即通过在循环中构建formbody来创建请求体。 就像我上面写的那样,我知道如何在OKHTTP版本2.x中执行它,但我使用的是版本3.x.
感谢任何帮助或指导。
先谢谢
答案 0 :(得分:28)
我是这样做的:
FormBody.Builder formBuilder = new FormBody.Builder()
.add("key", "123");
// dynamically add more parameter like this:
formBuilder.add("phone", "000000");
RequestBody formBody = formBuilder.build();
Request request = new Request.Builder()
.url("https://aaa.com")
.post(formBody)
.build();
答案 1 :(得分:15)
进口
import okhttp3.OkHttpClient;
import okhttp3.FormBody;
import okhttp3.Request;
import okhttp3.RequestBody;
代码:
// HashMap with Params
HashMap<String, String> params = new HashMap<>();
params.put( "Param1", "A" );
params.put( "Param2", "B" );
// Initialize Builder (not RequestBody)
FormBody.Builder builder = new FormBody.Builder();
// Add Params to Builder
for ( Map.Entry<String, String> entry : params.entrySet() ) {
builder.add( entry.getKey(), entry.getValue() );
}
// Create RequestBody
RequestBody formBody = builder.build();
// Create Request (same)
Request request = new Request.Builder()
.url( "url" )
.post( formBody )
.build();
答案 2 :(得分:1)
这是我的版本
/**
* <strong>Uses:</strong><br/>
* <p>
* {@code
* List<Pair<String, String>> pairs = new ArrayList<>();}
* <br/>
* {@code pairs.add(new Pair<>("key1", "value1"));}<br/>
* {@code pairs.add(new Pair<>("key2", "value2"));}<br/>
* {@code pairs.add(new Pair<>("key3", "value3"));}<br/>
* <br/>
* {@code postToServer("http://www.example.com/", pairs);}<br/>
* </p>
*
* @param url
* @param pairs List of support.V4 Pair
* @return response from server in String format
* @throws Exception
*/
public String postToServer(String url, List<Pair<String, String>> pairs) throws Exception {
okhttp3.OkHttpClient client = new okhttp3.OkHttpClient();
okhttp3.Request.Builder builder = new okhttp3.Request.Builder().url(url);
if (pairs != null) {
okhttp3.FormBody.Builder postData = new okhttp3.FormBody.Builder();
for (Pair<String, String> pair : pairs) {
postData.add(pair.first, pair.second);
}
builder.post(postData.build());
}
okhttp3.Request request = builder.build();
okhttp3.Response response = client.newCall(request).execute();
if (!response.isSuccessful()) {
throw new IOException(response.message() + " " + response.toString());
}
return response.body().string();
}
答案 3 :(得分:0)
我不确定,但你可以尝试这样的事情:
RequestBody formBody = new FormBody.Builder();
for(...;...;...) {
formBody.add(...)
}
formBody.build();
你的其余代码似乎很好。 希望它能工作:)!