对用另一个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;
}
}