我是一名Android开发人员。我开发了一个应用程序我有个问题。我想用okhttp multipart数据发送字符串数组数据。但我不能这样做。因为“addFormDataPart”方法是必需的字符串变量。我不能使用该方法(addFormDataPart)。我想发送字符串数组数据。我能做什么?
请帮帮我。
我的源代码:
private void String sendData(String serverURL, String[] arrayData){
RequestBody requestBody;
requestBody = new MultipartBuilder()
.type(MultipartBuilder.FORM)
.addFormDataPart("arraydata", arrayData)
.build();
}
答案 0 :(得分:1)
void String sendData(String serverURL, String[] arrayData){
String commaSeparatedValues = TextUtils.join(",", arrayData);
multiPartBuilder.addFormDataPart("key[]", commaSeparatedValues);
}
注意:这里的关键很重要,应该有“[]”
答案 1 :(得分:1)
请试试这个
private void String sendData(String serverURL, String[] arrayData){
RequestBody requestBody;
requestBody = new MultipartBuilder()
.type(MultipartBuilder.FORM)
.addFormDataPart("arraydata", getToString(arrayData))
.build();
}
public String getToString(String[] arrayData) {
StringBuilder stringBuilder = new StringBuilder();
for (int i = 0 ; i < arrayData.length; i++) {
stringBuilder.append(arrayData[i]);
if (i < arrayData.length - 1) {
stringBuilder.append(",");
}
}
return stringBuilder.toString();
}
答案 2 :(得分:0)
MediaType JSON = MediaType.parse("application/json; charset=utf-8");
Map<String, Long> params = new HashMap<String, Long>();
params.put("msisdn", 8801701340061l);
JSONObject parameter = new JSONObject(params);
RequestBody body = RequestBody.create(JSON, parameter.toString());
RequestBody requestBodyy = new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addPart(
Headers.of("content-type", "form-data; name=\"image\""),
RequestBody.create(null, "Square Logo"))
.addPart(
Headers.of("content-type", "application/json; charset=utf-8"),
body)
.build();
答案 3 :(得分:0)
把String[] arrayData
拼接成"one,two,three"
这种形式:
public String getToString(String[] arrayData) {
StringBuilder stringBuilder = new StringBuilder();
for (int i = 0 ; i < arrayData.length; i++) {
stringBuilder.append(arrayData[i]);
if (i < arrayData.length - 1) {
stringBuilder.append(",");
}
}
return stringBuilder.toString();
}
再传值:
.addFormDataPart("arraydata", getToString(arrayData))