java 调用 C# webapi

31 篇文章 0 订阅
22 篇文章 0 订阅

最近项目需要 java调用  .net 的webapi。

对于get来说很简单,但是post方法遇到了些问题,最后也是曲线救国。

先看代码

 

Java  代码

 

public static void main(String[] args) throws Exception {
//DoGet(String url)
        String resultGet = DoGet("http://localhost:14248/api/Report/GetTest?parentid=40");

//DoPost(String url,List<NameValuePair> nvps)
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
     nvps.add(new BasicNameValuePair("parentid", "40"));
        String resultPost = DoPost("http://localhost:14248/api/Report/PostTest",nvps);

//DoPost(String url, JSONObject template)
        JSONObject template = new JSONObject();
        template.put("data",data);
        String json=HttpWebapi.DoPost(urlString,template);

//DoPost(String url, String json)
        SysUser user=new SysUser();
        user.setAccount(etAccount.getText().toString());
        user.setPassword(etPwd.getText().toString());
        ApiRequest<SysUser> request=new ApiRequest<>();
        request.setData(user);

        String data=JsonConvert.toJSON(request);
        String json = HttpWebapi.DoPost(AppConfig.getUrl() + "api/user/login", data);
    }

    public static String DoGet(String url) throws Exception {

        HttpGet httpGet = new HttpGet(url);  
        HttpClient client = new DefaultHttpClient();  
        HttpResponse resp = client.execute(httpGet);  
        HttpEntity he = resp.getEntity();  
        String respContent = EntityUtils.toString(he, "UTF-8");  
        return respContent; 
    }

    public static String DoPost(String url,List<NameValuePair> nvps) throws Exception {
        HttpPost httpost = new HttpPost(url);  
        HttpClient client = new DefaultHttpClient();  
        httpost.setEntity(new UrlEncodedFormEntity(nvps, "UTF-8"));  
        HttpResponse resp = client.execute(httpost);  
        HttpEntity he = resp.getEntity();  
        String respContent = EntityUtils.toString(he, "UTF-8");  
        return respContent; 
    }

    public static String DoPost(String url, JSONObject template)throws Exception{
        HttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(url);
        httpPost.addHeader(HTTP.CONTENT_TYPE, "application/json");
        httpPost.setEntity(new StringEntity(template.toString(),"utf-8"));
        HttpResponse resp = httpClient.execute(httpPost);
        String respContent = EntityUtils.toString(resp.getEntity(), "UTF-8");
        return respContent;
    }

    public static String DoPost(String url, String json) throws Exception{
        HttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(url);
        httpPost.addHeader(HTTP.CONTENT_TYPE, "application/json");
        httpPost.setEntity(new StringEntity(json,"utf-8"));
        HttpResponse resp = httpClient.execute(httpPost);
        String respContent = EntityUtils.toString(resp.getEntity(), "UTF-8");
        return respContent;
    }



    

 

 

C# WebApi

public static String DoGet(String url) 

public static String DoPost(String url, List<NameValuePair> nvps)

//public static String DoGet(String url) 
[HttpGet]
        public dynamic GetTest(int parentId)
        {
            APIResult<dynamic> result = new APIResult<dynamic>();
            result.Data = report.Get_SanJu_ReportSiteCount(parentId);
                result.ResponseResult = true;
                result.ResponseMsg = "success";
                result.ResponseCode = HttpStatusCode.OK;
            
            return result;
        }

//public static String DoPost(String url, List<NameValuePair> nvps)
        [HttpPost]
        public dynamic PostTest()
        {
            //通过[FormBody]并不能从方法参数上获得parentId,所以直接从  Request.Form获取
            int parentId = int.Parse(HttpContext.Current.Request.Form["parentId"]);
            APIResult<dynamic> result = new APIResult<dynamic>();
            result.Data = report.Get_SanJu_ReportDesulphurizationTypeByParentId(parentId);
                result.ResponseResult = true;
                result.ResponseMsg = "success";
                result.ResponseCode = HttpStatusCode.OK;
            
            return result;
        }

 

Java WebApi

public static String DoPost(String url, JSONObject template)

//public static String DoPost(String url, JSONObject template)

@Data
public class ApiRequest<T> {
    private T data; 
    private Integer pageIndex = 1;
    private Integer pageSize; 
}



@RequestMapping(value = "test", method = RequestMethod.POST)
    public ApiResult<String> test(String test, @RequestBody ApiRequest<String> requestVo) {
        ApiResult<String> r = new ApiResult<String>();

        r.setData(requestVo.getData());
        r.setCodeToSuccessed();
        return r;
    }
public static String DoPost(String url, String json)
@RequestMapping(value = "login", method = RequestMethod.POST)
    public ApiResult<SysUser> login(@RequestBody ApiRequest<SysUser> requestVo) {
        ApiResult<SysUser> r = new ApiResult<SysUser>();
        SysUser entity = requestVo.getData();
        String source = requestVo.getSource();
        String platformUUID = entity.getPlatformUUID();
        SysUser u = service.getByAccount(entity.getAccount());
        // 验证登录成功
        if (u != null && u.getPassword().equals(MD5.md5(entity.getPassword()))) {
            if(u.getIsValid()==1){
                u.setPassword("");//把密码设置为空
                r.setData(u);
                r.setCodeToSuccessed();
            }else {
                r.setMessage("The account has been locked!");
            }
        }else{
            r.setMessage("Account or password invalid!");
        }

        return r;
    }

 

PS : 希望有人解决这个 [FormBody] parentId 这个形式的话,告知一下。

 

 

 


 

 

 

 

 

 

 

 

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
要使用Java调用WebAPI,你可以使用Java中的HttpClient库来发送HTTP请求。首先,你需要引入Apache的HttpClient库。你可以使用Maven或者Gradle来添加依赖。接下来,你需要创建一个HttpClient对象,并设置请求的参数,例如请求的URL、请求方法、请求头等。然后,你可以发送请求并获取响应结果。最后,你可以对响应结果进行解析和处理。以下是一个示例代码: ```java import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.util.EntityUtils; public class Main { public static void main(String[] args) { HttpClient httpClient = HttpClientBuilder.create().build(); HttpGet request = new HttpGet("http://your-web-api-url"); try { HttpResponse response = httpClient.execute(request); String responseBody = EntityUtils.toString(response.getEntity()); System.out.println(responseBody); } catch (IOException e) { e.printStackTrace(); } } } ``` 在上面的示例中,我们使用HttpClient发送了一个GET请求,并将响应结果输出到控制台。你可以根据实际需求修改请求方法、请求参数等。注意,你需要替换`http://your-web-api-url`为实际的WebAPI的URL。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* [如何使用java调用c#提供的webapi接口](https://blog.csdn.net/weixin_59244784/article/details/122973567)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT0_1"}}] [.reference_item style="max-width: 50%"] - *2* *3* [java处理,调用外系统的 WebAPI(https请求)时,相关知识整理](https://blog.csdn.net/sxzlc/article/details/128878523)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT0_1"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值