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
    评论
在 C# 中使用 HttpPost 请求调用 WebService,可以按照以下步骤进行操作: 1. 首先,确保你的 C# 项目中引用了 `System.Net.Http` 命名空间。 2. 创建一个 `HttpClient` 对象,用于发送 Http 请求。可以使用以下代码创建一个 `HttpClient` 对象: ```csharp HttpClient client = new HttpClient(); ``` 3. 设置要调用WebService 的 URL。假设 WebService 的 URL 是 `http://example.com/your_webservice`,可以使用以下代码设置 URL: ```csharp string url = "http://example.com/your_webservice"; ``` 4. 构建请求参数。根据你要调用的具体 WebService 方法的要求,构建相应的请求参数。可以使用 `FormUrlEncodedContent` 类来构建 URL 编码的请求参数。例如: ```csharp var parameters = new Dictionary<string, string> { { "param1", "value1" }, { "param2", "value2" } }; var content = new FormUrlEncodedContent(parameters); ``` 5. 发送 HttpPost 请求并获取响应。使用 `client.PostAsync` 方法发送 HttpPost 请求,并使用 `await` 关键字等待响应。例如: ```csharp HttpResponseMessage response = await client.PostAsync(url, content); ``` 6. 处理响应。根据你的需求,可以从响应中获取内容、状态码等信息。例如,可以使用以下代码获取响应内容: ```csharp string responseContent = await response.Content.ReadAsStringAsync(); ``` 这样,你就可以在 C# 中使用 HttpPost 请求调用 WebService。根据实际情况,可能还需要处理异常、设置请求头等操作。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值