zoukankan      html  css  js  c++  java
  • java 调用c# web api 代码

    上次我们写的.net  web api 给对方公司的java团队调用,他们觉得说java无法调用.net 写的api ,靠居然有这事,索性自己写一个java的demo给他们

    使用apache的HttpClient插件,下载导入对应jar包

    参考:

    http://hc.apache.org/httpcomponents-client-ga/quickstart.html

    //package org.apache.http.examples.client;
    
    import java.io.File;
    import java.io.FileInputStream;
    
    import org.apache.http.client.methods.CloseableHttpResponse;
    import org.apache.http.client.methods.HttpPost;
    import org.apache.http.entity.ContentType;
    import org.apache.http.entity.InputStreamEntity;
    import org.apache.http.impl.client.CloseableHttpClient;
    import org.apache.http.impl.client.HttpClients;
    import org.apache.http.util.EntityUtils;
    import org.apache.http.entity.*;
    
    public class MyClientDemo {
          public static void main(String[] args) throws Exception {
    
              CloseableHttpClient httpclient = HttpClients.createDefault();
                try {
             
                    HttpPost httpPost = new HttpPost("http://IP/Topevery.CAD.Web.Api/api/user/GetGroupInfo");
                    String json = "{
    " + 
                            ""account":"abc",
    " + 
                            ""password":"abc",
    " + 
                            ""grade":1
    " + 
                            "}";
                    StringEntity requestEntity = new StringEntity(json,"utf-8");  
                    requestEntity.setContentEncoding("UTF-8");                
                    httpPost.setHeader("Content-type", "application/json");  
                    httpPost.setEntity(requestEntity);  
                    
                     
                    System.out.println("Executing request: " + httpPost.getRequestLine());
                    CloseableHttpResponse response = httpclient.execute(httpPost);
                    try {
                        System.out.println("----------------------------------------");
                        System.out.println(response.getStatusLine());
                        System.out.println("result:" + EntityUtils.toString(response.getEntity()));
                    } finally {
                        response.close();
                    }
                }
                finally {
                    httpclient.close();
                }
          }
    }

    调用结果如下

    http请求推荐使用 http://square.github.io/okhttp/

  • 相关阅读:
    [COM/ATL]组件、对象、MFC、ATL的区别
    中国还是和AMD走到一起了 但美国会高兴吗(网易科技 卢鑫)
    趋势安全云
    统计应收与实收,有发票和商品两种方法,各有优缺点
    雷军:风口论一直被误读 我不是机会主义者
    Jira 6.0.5环境搭建
    逻辑推理能力
    交换变量值的5种方法
    .net下简单快捷的数值高低位切换
    easyui tree 的数据格式转换
  • 原文地址:https://www.cnblogs.com/weiweictgu/p/8117675.html
Copyright © 2011-2022 走看看