如何使用java调用c#提供的webapi接口

可以使用apache.commons下的一个httpclient的库,c#使用的asp.net下使用webapi对外提供http服务,然后发布在iis服务器上,就可以对外暴露接口了

一,引入apache.commons依赖

二,在你需要调用的接口中编辑请求信息,比如数据格式,编码格式等

废话不多说,直接上代码,不过这里要区分一下,get请求和post请求是有区别的,其次post请求参数的格式也好多种,我这边只列举json格式的;

//get请求
 @GetMapping("/web/get")
    public String getHttp() {
        String responseMsg = "";
        HttpClient httpClient = new HttpClient();

        GetMethod getMethod = new GetMethod("http://192.168.31.124:8086/actionApi/UserInfo/Getsstring");
        getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,new DefaultHttpMethodRetryHandler());
        try {
            httpClient.executeMethod(getMethod);
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            InputStream in = getMethod.getResponseBodyAsStream();
            int len = 0;
            byte[] buf = new byte[1024];
            while((len=in.read(buf))!=-1){
                out.write(buf, 0, len);
            }
            responseMsg = out.toString("UTF-8");
        } catch (HttpException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //释放连接
            getMethod.releaseConnection();
        }
        return responseMsg;
    }

//post请求
@PostMapping("/add/user")
    public String postHttp(Student student) throws UnsupportedEncodingException, JsonProcessingException {
        ObjectMapper JSON=new ObjectMapper();
        String responseMsg = "";
        String json=JSON.writeValueAsString(student);
        HttpClient httpClient = new HttpClient();
        httpClient.getParams().setContentCharset("UTF-8");
        PostMethod postMethod = new PostMethod("http://192.168.31.124:8086/actionApi/UserInfo/InsertData");
        RequestEntity entity = new StringRequestEntity(json,"application/json", "UTF-8");
        postMethod.setRequestEntity(entity);
        try {
            httpClient.executeMethod(postMethod);
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            InputStream in = postMethod.getResponseBodyAsStream();
            int len = 0;
            byte[] buf = new byte[1024];
            while((len=in.read(buf))!=-1){
                out.write(buf, 0, len);
            }
            responseMsg = out.toString("UTF-8");
        } catch (HttpException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            postMethod.releaseConnection();
        }
        return responseMsg;
    }


                
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

EntyIU

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值