java实现post请求(PostMethod)

2 篇文章 0 订阅

项目要求:实现post请求,且请求格式是json格式。

maven依赖包

<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
    <version>4.5.3</version>
 </dependency>
 <dependency>
    <groupId>commons-httpclient</groupId>
    <artifactId>commons-httpclient</artifactId>
    <version>3.1</version>
  </dependency>
 

java代码实现:

HttpClient httpClient = new HttpClient();
httpClient.getParams().setContentCharset("UTF-8");
PostMethod method = new PostMethod(url);
String str = "{\r\n" + 
                "    \"beginDate\":\"2017-11-01\",\r\n" + 
                "    \"endDate\":\"2017-11-01\"\r\n" + 
                "}";
RequestEntity entity = new StringRequestEntity(str,"application/json","UTF-8");
method.setRequestEntity(entity);
httpClient.executeMethod(method);
InputStream in = method.getResponseBodyAsStream();
//下面将stream转换为String
StringBuffer sb = new StringBuffer();
InputStreamReader isr = new InputStreamReader(in, "UTF-8");
char[] b = new char[4096];
for(int n; (n = isr.read(b)) != -1;) {
            sb.append(new String(b, 0, n));
        }
 String returnStr = sb.toString();
 System.out.println(returnStr);
 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
你可以使用 HttpClient 库来替换旧的 PostMethod 类。下面是一个示例代码,演示如何使用 HttpPost 来发送 POST 请求: ```java import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; import org.apache.http.client.HttpClient; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.message.BasicNameValuePair; import org.apache.http.util.EntityUtils; import java.io.IOException; import java.util.ArrayList; import java.util.List; public class Main { public static void main(String[] args) throws IOException { String url = "http://example.com/post"; // 创建 HttpClient 实例 HttpClient httpClient = HttpClientBuilder.create().build(); // 创建 HttpPost 请求 HttpPost httpPost = new HttpPost(url); // 设置请求参数 List<NameValuePair> params = new ArrayList<>(); params.add(new BasicNameValuePair("param1", "value1")); params.add(new BasicNameValuePair("param2", "value2")); httpPost.setEntity(new UrlEncodedFormEntity(params)); // 发送请求并获取响应 HttpResponse response = httpClient.execute(httpPost); // 获取响应内容 HttpEntity entity = response.getEntity(); String responseText = EntityUtils.toString(entity); // 打印响应内容 System.out.println(responseText); } } ``` 在上面的示例中,我们首先创建了一个 HttpClient 实例,然后创建了一个 HttpPost 请求,并设置了请求参数。最后,我们使用 HttpClient 发送了 POST 请求,并获取了响应。你可以根据自己的需求修改和扩展这个示例代码。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值