android httpclient post
时间: 2023-11-06 14:19:58 浏览: 144
在 Android 中使用 HttpClient 进行 POST 请求的示例代码如下:
```java
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import java.io.IOException;
public class HttpClientExample {
public static void main(String[] args) {
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("http://example.com/api"); // 替换为你的目标 URL
try {
// 设置请求体内容
StringEntity requestEntity = new StringEntity("Hello, Server!");
httpPost.setEntity(requestEntity);
// 设置请求头信息
httpPost.setHeader("Content-Type", "application/json");
// 发送请求并获取响应
HttpResponse response = httpClient.execute(httpPost);
// 解析响应
HttpEntity responseEntity = response.getEntity();
String responseBody = EntityUtils.toString(responseEntity);
System.out.println("Response: " + responseBody);
} catch (IOException e) {
e.printStackTrace();
} finally {
httpClient.getConnectionManager().shutdown();
}
}
}
```
请注意,Apache HttpClient 在 Android 6.0 及以上版本已被标记为过时,推荐使用 HttpURLConnection 或 OkHttp 来替代。
阅读全文