java发送post请求代码

public static String sendPost(String url, String param) {
        PrintWriter out = null;
        BufferedReader in = null;
        String result = "";
        try {
            URL realUrl = new URL(url);
            // 打开和URL之间的连接
            URLConnection conn = realUrl.openConnection();
            // 设置通用的请求属性
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent",
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            // 获取URLConnection对象对应的输出流
            out = new PrintWriter(conn.getOutputStream());
            // 发送请求参数
            out.print(param);
            // flush输出流的缓冲
            out.flush();
            // 定义
  • 2
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
Java发送POST请求,我们可以通过引入Apache HttpClient库来实现。下面是引入依赖的代码: 首先,在pom.xml文件中添加以下依赖项: ```xml <dependencies> <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version>4.5.12</version> </dependency> </dependencies> ``` 接下来,我们可以编写Java代码发送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.HttpClientBuilder; import org.apache.http.util.EntityUtils; import java.io.IOException; public class Main { public static void main(String[] args) { // 创建HttpClient实例 HttpClient httpClient = HttpClientBuilder.create().build(); // 创建HttpPost请求 HttpPost httpPost = new HttpPost("http://example.com/post-endpoint"); // 设置POST请求的内容 String requestBody = "This is the request body"; StringEntity stringEntity = new StringEntity(requestBody, "utf-8"); httpPost.setEntity(stringEntity); // 发送POST请求并获取响应 try { HttpResponse httpResponse = httpClient.execute(httpPost); HttpEntity responseEntity = httpResponse.getEntity(); String responseBody = EntityUtils.toString(responseEntity); // 处理响应 System.out.println("Response status code: " + httpResponse.getStatusLine().getStatusCode()); System.out.println("Response body: " + responseBody); } catch (IOException e) { e.printStackTrace(); } } } ``` 在上述示例代码中,我们创建了一个HttpClient实例,并使用HttpPost对象来设置POST请求的URL和内容。然后,我们使用HttpClient的execute方法发送请求,并通过HttpResponse对象获取响应内容。 注意,这只是一个简单的示例,实际中可能会涉及更多的设置和处理。 希望对你有所帮助!

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值