Java webservice的POST和GET请求调用方式
作者:sskai163 时间:2023-01-10 05:35:43
webservice的POST和GET请求调用
POST请求
1.发送请求
import java.io.DataOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.RequestEntity;
import org.apache.commons.httpclient.methods.StringRequestEntity;
import com.google.common.io.ByteStreams;
/**
* HttpClient发送SOAP请求
* @param wsdl url地址
* @param xml 请求体参数
* @return
* @throws Exception
*/
public static String sendHttpPost(String wsdl, String xml) throws Exception{
int timeout = 10000;
// HttpClient发送SOAP请求
System.out.println("HttpClient 发送SOAP请求");
HttpClient client = new HttpClient();
PostMethod postMethod = new PostMethod(wsdl);
// 设置连接超时
client.getHttpConnectionManager().getParams().setConnectionTimeout(timeout);
// 设置读取时间超时
client.getHttpConnectionManager().getParams().setSoTimeout(timeout);
// 然后把Soap请求数据添加到PostMethod中
RequestEntity requestEntity = new StringRequestEntity(xml, "text/xml", "UTF-8");
// 设置请求体
postMethod.setRequestEntity(requestEntity);
int status = client.executeMethod(postMethod);
// 打印请求状态码
System.out.println("status:" + status);
// 获取响应体输入流
InputStream is = postMethod.getResponseBodyAsStream();
// 获取请求结果字符串
return new String(ByteStreams.toByteArray(is));
}
/**
* HttpURLConnection 发送SOAP请求
* @param wsdl url地址
* @param xml 请求体参数
* @return
* @throws Exception
*/
public static String sendURLConnection(String wsdl, String xml) throws Exception{
int timeout = 10000;
// HttpURLConnection 发送SOAP请求
System.out.println("HttpURLConnection 发送SOAP请求");
URL url = new URL(wsdl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestProperty("Content-Type", "text/xml; charset=utf-8");
conn.setRequestMethod("POST");
conn.setUseCaches(false);
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setConnectTimeout(timeout);
conn.setReadTimeout(timeout);
DataOutputStream dos = new DataOutputStream(conn.getOutputStream());
dos.write(xml.getBytes("utf-8"));
dos.flush();
InputStream inputStream = conn.getInputStream();
// 获取请求结果字符串
return new String(ByteStreams.toByteArray(inputStream));
}
ByteStreams的maven
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>27.0.1-jre</version>
</dependency>
2.POST请求体
/**
* POST请求体
* @param map 请求参数
* @param methodName 方法名
* @return
*/
public static String getXml(Map<String ,String> map , String methodName){
StringBuffer sb = new StringBuffer("");
sb.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
sb.append("<soap:Envelope "
+ "xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' "
+ "xmlns:xsd='http://www.w3.org/2001/XMLSchema' "
+ "xmlns:soap='http://schemas.xmlsoap.org/soap/envelope/'>");
sb.append("<soap:Body>");
sb.append("<" + methodName + " xmlns='http://tempuri.org/'>");
//post参数
for (String str : map.keySet()){
sb.append("<"+str+">"+map.get(str)+"</"+str+">");
}
sb.append("</" + methodName + ">");
sb.append("</soap:Body>");
sb.append("</soap:Envelope>");
return sb.toString();
}
3.测试
/**
* HTTP POST请求
*/
public static void main(String[] args) throws Exception{
String wsdl = "http://IP:端口/xxx?wsdl";
String methodName = "方法名";
Map<String ,String> map = new HashMap<>();
map.put("参数名","参数值");
//请求体xml
String xml = getXml(map, methodName);
//发送请求
String s = sendHttpPost(wsdl, xml);
System.out.println(s);
}
GET请求
/**
* 发送请求
*/
import com.google.common.io.ByteStreams;
import org.apache.commons.httpclient.HttpStatus;
import org.codehaus.jettison.json.JSONObject;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
public static void main(String[] args) throws Exception{
String url = "http://IP:端口/xxx/方法名?参数名=参数值";
Map result = new HashMap(16);
try {
URL url = new URL(url);
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
//设置输入输出,因为默认新创建的connection没有读写权限,
connection.setDoInput(true);
connection.setDoOutput(true);
//接收服务端响应
int responseCode = connection.getResponseCode();
if(HttpStatus.SC_OK == responseCode){//表示服务端响应成功
InputStream is = connection.getInputStream();
//响应结果
String s = new String(ByteStreams.toByteArray(is));
result = com.alibaba.fastjson.JSONObject.parseObject(s, Map.class);
}
} catch (Exception e) {
e.printStackTrace();
System.out.println("查询在线状态1:"+e.getMessage());
}
System.out.println(result);
}
通过webService调第三方提供的接口post与get
需求:第三方提供接口路径,在自己的项目中进行调用
注意点:调不通的时候排除接口本身的问题后,看看自己调用路径是不是正确的,有没多了或者少了【/】,参数的格式是不是跟接口文档的一致,再不行,那有可能是编码或者流处理的问题,我在实际开发中就是因为流处理的问题导致调不通。
POST
public static String post(String method,String urls,String params){
OutputStreamWriter out = null;
try
{
URL url = new URL(urls);//第三方接口路径
HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
// 创建连接
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setUseCaches(false);
conn.setRequestMethod(method);//请求方式 此处为POST
String token= "123456789";//根据实际项目需要,可能需要token值
conn.setRequestProperty("token", token);
conn.setRequestProperty("Content-type", "application/json");
conn.connect();
out = new OutputStreamWriter(conn.getOutputStream(), "utf-8");//编码设置
out.write(params);
out.flush();
out.close();
// 获取响应
BufferedReader reader = new BufferedReader( new InputStreamReader(conn.getInputStream()));
String lines;
StringBuffer sb = new StringBuffer();
while ((lines = reader.readLine()) != null ){
lines = new String(lines.getBytes(), "utf-8" );
sb.append(lines);
}
reader.close();
System.out.println(sb);
return sb.toString();
}catch(Exception e) {
e.printStackTrace();
}
return null;
}
GET
//根据各自需要返回数组或者字符串
//public static String getObject(String method,String urls,String params){
public static JSONArray getArray(String method,String urls,String params){
OutputStreamWriter out = null;
try{
URL url = new URL(urls);//接口路径
HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
conn.setRequestMethod(method);//请求方法 此处为GET
conn.setDoInput(true);
conn.setDoOutput(true);
String token = "123456789";//请求头token
conn.setRequestProperty("token",token);
conn.connect();
int status = conn.getResponseCode();
System.out.println(status);
if(status == 200){
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));//怎么也调不通的时候,有可能流处理有问题
String str = "";
StringBuffer sb = new StringBuffer();
while((str=reader.readLine()) != null){
sb.append(str);
}
//返回字符串的话,就直接返回 sb.toString()
return JSONArray.parseArray(sb.toString());
}
System.out.println("请求服务失败,错误码为"+status);
}catch(Exception e){
e.printStackTrace();
}
return null;
}
用实体类进行接收返回值的话,需要将返回数据做下转换,转成我们需要的实体类格式
//返回数组转实体类
JSONArray sb = getArray(method,url,params);
if (sb!=null){
List<实体类> list = JSONObject.parseArray(sb.toJSONString(), 实体类.class);
return list;
}else {
throw new CustomException("调用接口失败");
}
//返回字符串转实体类
String json = JSONObject.toJSONString(params);
String sb = post(method,url,json);
JSONObject testJson = JSONObject.parseObject(sb);
实体类dto = JSON.toJavaObject(testJson,实体类.class);
来源:https://blog.csdn.net/weixin_42393758/article/details/84383415
标签:Java,webservice,POST,GET
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
java.lang.Runtime.exec的左膀右臂:流输入和流读取详解
2023-08-06 04:59:03
![](https://img.aspxhome.com/file/2023/4/57804_0s.jpg)
java封装及四种权限修饰符详解
2023-03-20 20:18:38
![](https://img.aspxhome.com/file/2023/6/132086_0s.png)
Unity之绕轴进行旋转的操作
2021-11-14 17:53:10
![](https://img.aspxhome.com/file/2023/9/104329_0s.jpg)
SpringRetry重试框架的具体使用
2022-09-21 00:37:35
![](https://img.aspxhome.com/file/2023/5/82305_0s.png)
C#中实现任意List的全组合算法代码
2022-09-23 01:06:48
Java Object定义三个点实现代码
2023-11-21 06:05:07
java多线程有序读取同一个文件
2022-05-28 20:41:57
![](https://img.aspxhome.com/file/2023/8/62778_0s.jpg)
Spring容器-BeanFactory和ApplicationContext使用详解
2022-03-20 07:02:45
Java排序算法总结之希尔排序
2022-07-16 13:19:11
C#如何调用MFC 窗口 DLL
2022-04-14 09:57:51
![](https://img.aspxhome.com/file/2023/4/102164_0s.png)
简单谈谈Java中的栈和堆
2022-07-30 05:33:01
![](https://img.aspxhome.com/file/2023/3/61163_0s.png)
Java实现图形界面计算器
2023-06-05 11:53:23
![](https://img.aspxhome.com/file/2023/7/65757_0s.jpg)
C++11 condition_variable条件变量的用法说明
2021-12-06 23:39:56
![](https://img.aspxhome.com/file/2023/9/117789_0s.png)
浅谈Visual Studio 2019 Vue项目的目录结构
2023-12-20 20:01:34
![](https://img.aspxhome.com/file/2023/6/94586_0s.jpg)
android多线程断点下载-带进度条和百分比进度显示效果
2022-03-20 14:30:43
![](https://img.aspxhome.com/file/2023/4/91714_0s.png)
Java开发之内部类对象的创建及hook机制分析
2023-11-27 04:45:20
Java编程实现月食简单代码分享
2022-12-27 12:33:24
![](https://img.aspxhome.com/file/2023/3/79943_0s.png)
Flutter应用集成极光推送的实现示例
2023-06-24 03:51:04
![](https://img.aspxhome.com/file/2023/2/90172_0s.jpg)
Java计时器StopWatch实现方法代码实例
2021-07-25 13:43:42
SpringBoot @PostConstruct原理用法解析
2022-02-02 18:05:46