Java模拟HTTP/POST方式请求接口

本文介绍如何使用Java模拟HTTP POST方式请求接口,包括方法主体、接口调用示例以及POM文件的配置细节。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Java模拟HTTP/POST方式请求接口:

java模拟http/post方式请求接口方法主体:

public String sendPost(JSONObject json, String url){
    String result = "";
    HttpPost post = new HttpPost(url);
    try{
        CloseableHttpClient httpClient = HttpClients.createDefault();
        post.setHeader("Content-Type","application/json;charset=utf-8");
        post.addHeader("Authorization", "Basic YWRtaW46");
        StringEntity postingString = new StringEntity(json.toString(),"utf-8");
        post.setEntity(postingString);
        HttpResponse response = httpClient.execute(post);

        InputStream in = response.getEntity().getContent();
        BufferedReader br = new BufferedReader(new InputStreamReader(in, "utf-8"));
        StringBuilder strber= new StringBuilder();
        String line = null;
        while((line = br.readLine())!=null){
            strber.append(line+'\n');
        }
        br.close();
        in.close();
        result = strber.toString();
        if(response.getStatusLine().getStatusCode()!= HttpStatus.SC_OK){
            result = "服务器异常";
        }
    } catch (Exception e){
        System.out.println("请求异常");
        throw new RuntimeException(e);
    } finally{
        post.abort();
    }
    return result;
}

接口调用方法:

 public String sendPostTest() {
    JSONObject jsonObject = new JSONObject();
    //添加参数,参数为JSON格式
    jsonObject.put("namecode", "zhouxf4110");
    String url = "http://localhost/***/userMassage/queryUserByList";
    //调用接口,返回字符串,返回值自行处理
    String str = sendPost(jsonObject, url);
    System.out.println(str);
    return str;
}

pom文件配置:

	<dependency>
		<groupId>org.apache.httpcomponents</groupId>
		<artifactId>httpcore</artifactId>
		<version>4.4.10</version>
	</dependency>
	<!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient -->
	<dependency>
		<groupId>org.apache.httpcomponents</groupId>
		<artifactId>httpclient</artifactId>
		<version>4.5.6</version>
	</dependency>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值