java模拟http和webservice请求并获取参数示例

         主要是使用java进行模拟请求,不多说,直接上干货。

1、依赖

 

(1)httpclient:

 

<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
    <version>4.5.6</version>
</dependency>

(2)cxf:

 

<dependency>
    <groupId>org.apache.cxf</groupId>
    <artifactId>cxf-spring-boot-starter-jaxws</artifactId>
    <version>3.2.4</version>
</dependency>

2、代码

 

import net.sf.json.JSONObject;
import org.apache.cxf.endpoint.Endpoint;
import org.apache.cxf.jaxws.endpoint.dynamic.JaxWsDynamicClientFactory;
import org.apache.cxf.service.model.BindingInfo;
import org.apache.cxf.service.model.BindingOperationInfo;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.xml.namespace.QName;
import javax.xml.rpc.ParameterMode;
import javax.xml.rpc.ServiceFactory;
import javax.xml.rpc.encoding.XMLType;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@Component
public class DemoUtil {

    /**
     * cxf调用示例
     */
    @RequestMapping("/cxfService")
    public void testWeb(){
        String url = "http://11.23.0.28:8456/ws/author";
        String method = "getAuthorByName";
        Object parameters = "张三";
        System.out.println(invokeRemoteMethod(url, method, parameters)[0]);
    }

    public static void main(String[] args) {
        //广电的webservice地址
        String gdUrl = "";
        //广电请求json
        String requestInfo = "{\"commonTradeInfo\":{\"sn\":\"a1\",\"verificationCode\":\"147451561a800880b5bedae8a16cf32f\",\"source\":\"sdjcy\",\"areaCode\":\"LY\"},\"identificationType\":\"1\",\"identificationNo\":\"13120214874\"}";
        //调用的方法名  findCustomers查询开户的方法  findCustomerOrders查询受理记录的方法
        String method = "findCustomers";
        //调用广电webservice
        System.out.println(invokeRemoteMethod(gdUrl, method, requestInfo)[0]);
    }

    /**
     * cxf调用示例
     * @param url
     * @param operation
     * @param parameters object数组
     * @return
     */
    public static Object[] invokeRemoteMethod(String url, String operation, Object[] parameters) {
        JaxWsDynamicClientFactory dcf = JaxWsDynamicClientFactory.newInstance();
        if (!url.endsWith("wsdl")) {
            url += "?wsdl";
        }
        org.apache.cxf.endpoint.Client client = dcf.createClient(url);
        //处理webService接口和实现类namespace不同的情况,CXF动态客户端在处理此问题时,会报No operation was found with the name的异常
        Endpoint endpoint = client.getEndpoint();
        QName opName = new QName(endpoint.getService().getName().getNamespaceURI(), operation);
        BindingInfo bindingInfo = endpoint.getEndpointInfo().getBinding();
        if (bindingInfo.getOperation(opName) == null) {
            for (BindingOperationInfo operationInfo : bindingInfo.getOperations()) {
                if (operation.equals(operationInfo.getName().getLocalPart())) {
                    opName = operationInfo.getName();
                    break;
                }
            }
        }
        Object[] res = null;
        try {
            res = client.invoke(opName, parameters);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return res;
    }


    /**
     * cxf调用示例
     * @param url
     * @param operation
     * @param parameters object对象
     * @return
     */
    public static Object[] invokeRemoteMethod(String url, String operation, Object parameters) {
        JaxWsDynamicClientFactory dcf = JaxWsDynamicClientFactory.newInstance();
        if (!url.endsWith("wsdl")) {
            url += "?wsdl";
        }
        org.apache.cxf.endpoint.Client client = dcf.createClient(url);
        //处理webService接口和实现类namespace不同的情况,CXF动态客户端在处理此问题时,会报No operation was found with the name的异常
        Endpoint endpoint = client.getEndpoint();
        QName opName = new QName(endpoint.getService().getName().getNamespaceURI(), operation);
        BindingInfo bindingInfo = endpoint.getEndpointInfo().getBinding();
        if (bindingInfo.getOperation(opName) == null) {
            for (BindingOperationInfo operationInfo : bindingInfo.getOperations()) {
                if (operation.equals(operationInfo.getName().getLocalPart())) {
                    opName = operationInfo.getName();
                    break;
                }
            }
        }
        Object[] res = null;
        try {
            res = client.invoke(opName, parameters);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return res;
    }

    /**
     * axis 调用webservice接口示例
     * @param inputXml
     * @param methodName
     * @return
     * @throws Exception
     */
    public String callinvoke(String inputXml, String methodName) throws Exception {
        String webServiceURL = "httpy/*******V***V****";
        String targetNamespace = "********";
        QName servicename = new QName(webServiceURL, targetNamespace);
        javax.xml.rpc.Service service = ServiceFactory.newInstance().createService(servicename);
        javax.xml.rpc.Call call = service.createCall();
        call.setTargetEndpointAddress(webServiceURL);
        QName operationname = new QName(targetNamespace, methodName);
        call.setOperationName(operationname);
        call.addParameter("inputXml",XMLType.XSD_STRING, ParameterMode.IN);
        QName returnname = new QName(targetNamespace, "string");
        call.setReturnType(returnname, String.class);
        String result = call.invoke(new Object[]{inputXml}).toString();
        return result;
    }

    //http get
    public static String getURLContent(String httpUrl) {
        CloseableHttpClient httpCilent = HttpClients.createDefault();
        HttpGet httpGet = new HttpGet(httpUrl);
        Map<String, Object> resultMap = new HashMap<>();
        try {
            CloseableHttpResponse response = httpCilent.execute(httpGet);
            if (response != null && response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                resultMap.put("flag", HttpStatus.SC_OK);
                resultMap.put("result", EntityUtils.toString(response.getEntity()));
                //处理返回结果
                String result = (String) resultMap.get("result");
                return result;
            } else {
                resultMap.put("flag", response.getStatusLine().getStatusCode());
            }
        } catch (IOException e) {
            resultMap.put("flag", 0);
            e.printStackTrace();
        }
        return null;
    }
    //http post方式
    public static String getURLContent(String httpUrl,Map<String,String> params) {
        CloseableHttpClient httpCilent = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        String resultString = "";
        JSONObject jsonObject=JSONObject.fromObject(params);
        String json = jsonObject.toString();
        try {
            // 创建Http Post请求
            HttpPost httpPost = new HttpPost(httpUrl);
            // 创建请求内容
            StringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON);
            httpPost.setEntity(entity);
            // 执行http请求
            response = httpCilent.execute(httpPost);
            resultString = EntityUtils.toString(response.getEntity(), "utf-8");
            return resultString;
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }
}

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值