java 調用c# web api 代碼

上次咱們寫的.net  web api 給對方公司的java團隊調用,他們以爲說java沒法調用.net 寫的api ,靠竟然有這事,索性本身寫一個java的demo給他們html

使用apache的HttpClient插件,下載導入對應jar包java

 

參考:git

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

//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 = "{\r\n" + 
                        "\"account\":\"abc\",\r\n" + 
                        "\"password\":\"abc\",\r\n" + 
                        "\"grade\":1\r\n" + 
                        "}";
                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();
            }
      }
}

調用結果以下web

 

http請求推薦使用 http://square.github.io/okhttp/apache

相關文章
相關標籤/搜索