在安卓开发中,提交数组数据到服务器通常涉及将数组转换为特定格式(如JSON)并通过HTTP请求发送,以下是常见的实现方式及注意事项:
步骤:
JSONArray
或通过Gson
序列化)。RequestBody
并设置Content-Type
为application/json
。OkHttpClient
发送POST请求。代码示例:
// 假设提交字符串数组 String[] array = {"value1", "value2", "value3"}; JSONArray jsonArray = new JSONArray(Arrays.asList(array)); MediaType JSON = MediaType.get("application/json; charset=utf-8"); RequestBody body = RequestBody.create(jsonArray.toString(), JSON); OkHttpClient client = new OkHttpClient(); Request request = new Request.Builder() .url("https://example.com/api") .post(body) .build(); client.newCall(request).enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { // 处理失败 } @Override public void onResponse(Call call, Response response) throws IOException { if (response.isSuccessful()) { // 处理成功 } } });
步骤:
List
,并通过@Body
注解提交。代码示例:
// 数据模型类 public class DataItem { private String value; public DataItem(String value) { this.value = value; } } // Retrofit接口 public interface ApiService { @POST("https://example.com/api") Call<ResponseBody> submitArray(@Body List<DataItem> data); } // 使用Retrofit Retrofit retrofit = new Retrofit.Builder() .baseUrl("https://example.com/") .addConverterFactory(GsonConverterFactory.create()) .build(); ApiService apiService = retrofit.create(ApiService.class); List<DataItem> dataList = Arrays.asList( new DataItem("value1"), new DataItem("value2") ); Call<ResponseBody> call = apiService.submitArray(dataList); call.enqueue(new Callback<ResponseBody>() { @Override public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) { if (response.isSuccessful()) { // 处理成功 } } @Override public void onFailure(Call<ResponseBody> call, Throwable t) { // 处理失败 } });
HttpURLConnection
提交表单数组适用场景: 服务器要求以表单形式提交数组(如key[]=value1&key[]=value2
)。
代码示例:
String[] array = {"value1", "value2"}; String url = "https://example.com/api"; URL obj = new URL(url); HttpURLConnection con = (HttpURLConnection) obj.openConnection(); con.setRequestMethod("POST"); con.setDoOutput(true); // 构建表单参数 StringBuilder params = new StringBuilder(); for (String value : array) { params.append("key[]=").append(value).append("&"); } String postData = params.substring(0, params.length() 1); // 写入请求体 OutputStream os = con.getOutputStream(); os.write(postData.getBytes()); os.flush(); os.close(); // 读取响应 int responseCode = con.getResponseCode(); if (responseCode == HttpURLConnection.HTTP_OK) { // 处理成功 } else { // 处理错误 }
问题 | 解决方案 |
---|---|
数组格式不匹配 | 确认服务器要求的格式(JSON数组、表单数组等)。 |
中文乱码 | 设置Content-Type 为application/json; charset=utf-8 ,并使用UTF-8编码。 |
跨线程异常 | 网络请求需在子线程或异步任务中执行,避免阻塞主线程。 |
Gson序列化失败 | 确保数组元素与数据模型字段一致,或使用TypeToken 处理泛型。 |
解答:
将二维数组转换为嵌套JSON结构。
int[][] twoDimArray = {{1, 2}, {3, 4}}; Gson gson = new Gson(); String json = gson.toJson(twoDimArray); // 输出: [[1,2],[3,4]]
通过@Body
或JSONArray
提交即可。
415 Unsupported Media Type
怎么办?解答:
Content-Type
是否与服务器要求一致(如application/json
或multipart/form-data
)。