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

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

1、依赖

 

(1)httpclient:

 


    org.apache.httpcomponents
    httpclient
    4.5.6

(2)cxf:

 


    org.apache.cxf
    cxf-spring-boot-starter-jaxws
    3.2.4

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 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 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;
    }
}

 

你可能感兴趣的:(经验总结)