android post调用
时间: 2023-10-17 19:05:26 浏览: 53
在 Android 中,可以使用 HttpUrlConnection 或者 HttpClient 类来进行 HTTP POST 请求。以下是使用 HttpUrlConnection 发送 POST 请求的示例代码:
```java
URL url = new URL("http://example.com/api");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
conn.setDoOutput(true);
conn.setDoInput(true);
JSONObject jsonParam = new JSONObject();
jsonParam.put("username", "john_doe");
jsonParam.put("password", "password123");
DataOutputStream os = new DataOutputStream(conn.getOutputStream());
os.writeBytes(jsonParam.toString());
os.flush();
os.close();
int responseCode = conn.getResponseCode();
String response = "";
if (responseCode == HttpURLConnection.HTTP_OK) {
String line;
BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
while ((line = br.readLine()) != null) {
response += line;
}
} else {
response = "";
}
conn.disconnect();
```
在上面的代码中,我们使用了 JSONObject 类来创建一个包含用户名和密码的 JSON 对象,并将其写入到 HttpUrlConnection 的输出流中。最后,我们读取服务器响应的输入流并处理响应。
需要注意的是,由于网络请求可能会耗费较长时间,因此应该在 Android 应用程序的后台线程中执行此类操作,以避免阻塞用户界面。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)