java 模拟 http 后台请求

public static String httpPostWithJSON(String url,Map<String, String> params) throws Exception {
String json = JSON.toJSONString(params);
HttpPost httpPost = new HttpPost(url);
CloseableHttpClient client = HttpClients.createDefault();
String respContent = null;

// json方式
StringEntity entity = new StringEntity(json,“utf-8”);//解决中文乱码问题
entity.setContentEncoding(“UTF-8”);
entity.setContentType(“application/json”);
/httpPost.setEntity(entity);/
System.out.println();

  //表单方式
  List<BasicNameValuePair> pairList = new ArrayList<BasicNameValuePair>();
	String temp;
  for(Iterator<String> it = params.keySet().iterator(); it.hasNext();){
      temp = it.next().toString();
      pairList.add(new BasicNameValuePair(temp, params.get(temp)));
  }
    /*httpPost.setEntity(new UrlEncodedFormEntity(pairList, "utf-8"));*/
    HttpResponse resp = client.execute(httpPost);
    if(resp.getStatusLine().getStatusCode() == 200) {
        HttpEntity he = resp.getEntity();
        respContent = EntityUtils.toString(he,"UTF-8");
    }
    return respContent;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,您可以使用Java中的HttpURLConnection类来模拟HTTP请求,然后使用JSON序列化实体类对象并将其添加到请求体中,最后将请求发送到后台RESTful接口。以下是一个示例代码: ```java import java.net.HttpURLConnection; import java.net.URL; import java.io.OutputStream; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.ObjectWriter; public class HttpTest { public static void main(String[] args) throws Exception { // 创建URL对象 URL url = new URL("http://example.com/api"); // 创建HttpURLConnection对象 HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("POST"); conn.setRequestProperty("Content-Type", "application/json"); conn.setDoOutput(true); // 创建实体类对象 User user = new User(); user.setName("John Doe"); user.setEmail("[email protected]"); // 将实体类对象序列化成JSON字符串 ObjectMapper mapper = new ObjectMapper(); ObjectWriter writer = mapper.writer().withDefaultPrettyPrinter(); String json = writer.writeValueAsString(user); // 将JSON字符串添加到请求体中 OutputStream os = conn.getOutputStream(); os.write(json.getBytes("UTF-8")); os.flush(); os.close(); // 发送请求并获取响应 int responseCode = conn.getResponseCode(); System.out.println("Response Code : " + responseCode); } } ``` 在上面的示例代码中,我们使用了一个名为User的实体类,并将其序列化成JSON字符串添加到请求体中。您需要根据您的实际需求修改相应的实体类和URL地址。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值