HttpClients的使用,调用另一个的http的方法(同步调用接口)

对用另一个http方法的同步调用我直接用一个类来表示,有xml和json两种方式。

首先在pom.xml引入jar包

<!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient -->
<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
    <version>4.5.5</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpcore -->
<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpcore</artifactId>
    <version>4.4.9</version>
</dependency>

然后实现类

package test.service;

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.HttpClients;
import org.apache.http.util.EntityUtils;

public class HttpClientsTest {
	
	
	public String lcxTest(String xml) throws Exception {
		
		//这个传参的可以自己根据要调用另一个链接的方法定(参数是可以外来的,这里改是用于测试用的)
		xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" + 
				"<PACKET type=\"REQUEST\" version=\"1.0\">\r\n" + 
				"	<requesthead>\r\n" + 
				"		<user>0101</user>\r\n" + 
				"		<password>33bbf9de-3ae9-44e2-821c-9aac24e7f32c</password>\r\n" + 
				"		<flowintime>2018-10-31 00:32:07</flowintime>\r\n" + 
				"	</requesthead>\r\n" + 
				"    <BODY>\r\n" + 
				"		<registTask>\r\n" + 
				"            <linkMan>枯兴</linkMan>\r\n" + 
				"            <linkTel>14949494949</linkTel>\r\n" + 
				"            <Address>广州某地</Address>\r\n" + 
				"		</registTask>\r\n" + 
				"	</BODY>\r\n" + 
				"</PACKET>";
	
		String content = xml;
		
		//另一个链接的方法调用,里面写的判断和返回自己定
		String url = "http://192.168.21.5200:5200/ku/service/userPush";

		//这句是用来传参和json解析(用这另一个方式的传参,下面对应的application/xml要改为application/json)
//		String content= JSONObject.toJSONString(inputMap);
		
		
		HttpClient client = HttpClients.createDefault();
		HttpPost post=new HttpPost(url);
		//token认证根据自己认证情况
//		String token = getWebUser(user).getToken();
//		if(token!=null)post.addHeader("Authorization", "bearer "+token);
		StringEntity se=new StringEntity(content,"UTF-8");
		se.setContentEncoding("UTF-8");
		se.setContentType("application/xml;charset=UTF-8");
		post.setEntity(se);
		HttpResponse response = client.execute(post);
		
		String resultString=EntityUtils.toString(response.getEntity());
		System.out.println("resultString返回的数据为:"+ resultString);
		
		return resultString;
	}
	
	
	
}

 

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值