webservice的POST和GET请求调用

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);
}
  • 1
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值