如何使用 OkHttp 在 JSONArray 中 post form.body?
How to post form.body in JSONArray using OkHttp?
大家好,我正在尝试使用 OkHttp post JSONArray
。我想这样做:
[
{
"name": "john"
},
{
"food": "burger"
}
]
谁能帮帮我?
您可以尝试在数组中添加一个 JSONObject
,然后将其传递给您的 JSONArray
。
像这样:
JSONArray list = new JSONArray();
JSONObject js = new JSONObject();
try {
js.put("name", "john");
} catch (JSONException e) {
e.printStackTrace();
}
list.put(js);
js = new JSONObject();
try {
js.put("food", "burger");
} catch (JSONException e) {
e.printStackTrace();
}
list.put(js);
Log.e(TAG, "found json array " + list);
如果您有更多项目,则 运行 `js' 循环直到您完成它。
像这样:
public void sendRequest(String route) {
OkHttpClient client = new OkHttpClient();
String url = baseUrl + route;
RequestBody requestBody = new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("username", String.valueOf(username.getText()))
.addFormDataPart("password", String.valueOf(password.getText()))
.build();
Request request = new Request.Builder()
.url(url)
.post(requestBody)
.build();
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
Log.d("Error", "Something Went Wrong");
}
@Override
public void onResponse(Call call, Response response) throws IOException {
if (response.isSuccessful()) {
String myresponse = response.body().string();
try {
JSONArray all = new JSONArray(myresponse);
// Do whatever
} catch (JSONException e) {
e.printStackTrace();
}
} else {
String errorBodyString = response.body().string();
Log.d("Error", errorBodyString);
}
}
});
}
大家好,我正在尝试使用 OkHttp post JSONArray
。我想这样做:
[
{
"name": "john"
},
{
"food": "burger"
}
]
谁能帮帮我?
您可以尝试在数组中添加一个 JSONObject
,然后将其传递给您的 JSONArray
。
像这样:
JSONArray list = new JSONArray();
JSONObject js = new JSONObject();
try {
js.put("name", "john");
} catch (JSONException e) {
e.printStackTrace();
}
list.put(js);
js = new JSONObject();
try {
js.put("food", "burger");
} catch (JSONException e) {
e.printStackTrace();
}
list.put(js);
Log.e(TAG, "found json array " + list);
如果您有更多项目,则 运行 `js' 循环直到您完成它。
像这样:
public void sendRequest(String route) {
OkHttpClient client = new OkHttpClient();
String url = baseUrl + route;
RequestBody requestBody = new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("username", String.valueOf(username.getText()))
.addFormDataPart("password", String.valueOf(password.getText()))
.build();
Request request = new Request.Builder()
.url(url)
.post(requestBody)
.build();
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
Log.d("Error", "Something Went Wrong");
}
@Override
public void onResponse(Call call, Response response) throws IOException {
if (response.isSuccessful()) {
String myresponse = response.body().string();
try {
JSONArray all = new JSONArray(myresponse);
// Do whatever
} catch (JSONException e) {
e.printStackTrace();
}
} else {
String errorBodyString = response.body().string();
Log.d("Error", errorBodyString);
}
}
});
}