java使用HttpClient发送post请求并携带JSON参数

导入以下依赖:

<!--httpclient-->
<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
    <version>4.5.1</version>
</dependency>


<!-- 需加上classifier: jdk15 -->
<dependency>
    <groupId>net.sf.json-lib</groupId>
    <artifactId>json-lib</artifactId>
    <version>2.4</version>
    <classifier>jdk15</classifier>
</dependency>

工具类: HttpClientUtils.java

package com.idea.fire.firecontrol.utils;

import net.sf.json.JSONObject;
import org.apache.http.*;
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;

//模拟浏览器发送http请求完成固定地址的请求
public class HttpClientUtils {

	/**
	 * 发送post请求
	 * @param url
	 * @param json
	 * @return
	 */
	public static JSONObject DO_POST(String url, JSONObject json){
		DefaultHttpClient client = new DefaultHttpClient();
		HttpPost post = new HttpPost(url);
		JSONObject response = null;
		try {
			StringEntity s = new StringEntity(json.toString());
			s.setContentEncoding("UTF-8");
			s.setContentType("application/json");//发送json数据需要设置contentType
			post.setEntity(s);
			HttpResponse res = client.execute(post);
			if(res.getStatusLine().getStatusCode() == HttpStatus.SC_OK){
				HttpEntity entity = res.getEntity();
				String result = EntityUtils.toString(res.getEntity());// 返回json格式:
				response = JSONObject.fromObject(result);
			}
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
		return response;
	}
}

 准备被请求接口:

@RestController
@RequestMapping("user")
public class UserController {

    @PostMapping("login")
    public R login(@RequestBody User user)
    {
        return R.ok().data("user", user);
    }
}

测试:

public static void main(String[] args) throws Exception {
    JSONObject params = new JSONObject();
    params.put("username", "admin");
    params.put("password", "admin");
    System.out.println(HttpClientUtils.DO_POST("ip/user/login", params));
}

控制台输出:

  • 7
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
以下是一个使用HttpClient发送Post请求携带cookie的示例代码: ```java import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.CookieStore; import org.apache.http.client.HttpClient; import org.apache.http.client.config.RequestConfig; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpPost; import org.apache.http.cookie.Cookie; import org.apache.http.impl.client.BasicCookieStore; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.message.BasicNameValuePair; import org.apache.http.util.EntityUtils; import java.util.ArrayList; import java.util.List; public class HttpClientUtil { public static void main(String[] args) throws Exception { // 创建HttpClient实例 HttpClient httpClient = HttpClientBuilder.create().build(); // 创建CookieStore实例 CookieStore cookieStore = new BasicCookieStore(); // 创建HttpPost实例 HttpPost httpPost = new HttpPost("http://example.com/login"); // 设置请求参数 RequestConfig requestConfig = RequestConfig.custom() .setConnectTimeout(5000).setConnectionRequestTimeout(5000) .setSocketTimeout(5000).build(); httpPost.setConfig(requestConfig); // 设置请求头 httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded"); // 设置请求参数 List<BasicNameValuePair> parameters = new ArrayList<>(); parameters.add(new BasicNameValuePair("username", "example")); parameters.add(new BasicNameValuePair("password", "password")); UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(parameters); httpPost.setEntity(formEntity); // 执行HttpPost请求 HttpResponse httpResponse = httpClient.execute(httpPost); // 获取响应实体 HttpEntity httpEntity = httpResponse.getEntity(); if (httpEntity != null) { String response = EntityUtils.toString(httpEntity); System.out.println(response); } // 获取Cookie List<Cookie> cookies = cookieStore.getCookies(); // 创建HttpPost实例 httpPost = new HttpPost("http://example.com/data"); // 设置请求参数 requestConfig = RequestConfig.custom() .setConnectTimeout(5000).setConnectionRequestTimeout(5000) .setSocketTimeout(5000).build(); httpPost.setConfig(requestConfig); // 设置请求头 httpPost.setHeader("Content-Type", "application/json"); httpPost.setHeader("Accept", "application/json"); // 设置请求参数 String requestBody = "{\"key\":\"value\"}"; httpPost.setEntity(new StringEntity(requestBody, ContentType.APPLICATION_JSON)); // 设置Cookie httpClient = HttpClientBuilder.create().setDefaultCookieStore(cookieStore).build(); // 执行HttpPost请求 httpResponse = httpClient.execute(httpPost); // 获取响应实体 httpEntity = httpResponse.getEntity(); if (httpEntity != null) { String response = EntityUtils.toString(httpEntity); System.out.println(response); } } } ```

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值