在Android开发中,当需要调用API时,通常需要将参数以JSON格式发送给服务器。JSON(JavaScript Object Notation)是一种轻量级的数据交换格式,易于人阅读和编写,也易于机器解析和生成。
public void postJsonData(String urlString, JSONObject jsonData) {
try {
URL url = new URL(urlString);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
// 设置请求方法为POST
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/json");
connection.setRequestProperty("Accept", "application/json");
connection.setDoOutput(true);
// 写入JSON数据
OutputStream outputStream = connection.getOutputStream();
outputStream.write(jsonData.toString().getBytes());
outputStream.flush();
outputStream.close();
// 获取响应
int responseCode = connection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
InputStream inputStream = connection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
StringBuilder response = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
response.append(line);
}
reader.close();
// 处理响应数据
Log.d("API Response", response.toString());
} else {
Log.e("API Error", "HTTP error code: " + responseCode);
}
connection.disconnect();
} catch (Exception e) {
e.printStackTrace();
}
}
首先添加OkHttp依赖:
implementation 'com.squareup.okhttp3:okhttp:4.9.3'
然后使用以下代码:
public void postJsonWithOkHttp(String url, JSONObject jsonData) {
OkHttpClient client = new OkHttpClient();
MediaType JSON = MediaType.parse("application/json; charset=utf-8");
RequestBody body = RequestBody.create(jsonData.toString(), JSON);
Request request = new Request.Builder()
.url(url)
.post(body)
.build();
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
e.printStackTrace();
}
@Override
public void onResponse(Call call, Response response) throws IOException {
if (response.isSuccessful()) {
String responseData = response.body().string();
// 处理响应数据
Log.d("OkHttp Response", responseData);
}
}
});
}
添加依赖:
implementation 'com.squareup.retrofit2:retrofit:2.9.0'
implementation 'com.squareup.retrofit2:converter-gson:2.9.0'
定义API接口:
public interface ApiService {
@POST("endpoint")
Call<ResponseBody> postData(@Body JsonObject jsonObject);
}
使用示例:
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://api.example.com/")
.addConverterFactory(GsonConverterFactory.create())
.build();
ApiService apiService = retrofit.create(ApiService.class);
JsonObject jsonObject = new JsonObject();
jsonObject.addProperty("key1", "value1");
jsonObject.addProperty("key2", "value2");
Call<ResponseBody> call = apiService.postData(jsonObject);
call.enqueue(new Callback<ResponseBody>() {
@Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
if (response.isSuccessful()) {
try {
String responseString = response.body().string();
Log.d("Retrofit Response", responseString);
} catch (IOException e) {
e.printStackTrace();
}
}
}
@Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
t.printStackTrace();
}
});
没有搜到相关的沙龙