C#调取java接口

1.

public class APIRequest
    {
       //public static string commonUrl = @"http://192.168.2.186:8080/sale/";
       public static string commonUrl = @"http://115.29.102.31:9011/sale/";

        #region 通用api请求
        /// <summary>
        /// 通用api请求
        /// </summary>
        /// <param name="serverUrl"></param>
        /// <param name="paramJsonStr"></param>
        /// <returns></returns>
        public static string CommonAPIAccess(string serverUrl, byte[] byteArr)
        {
            string strResult = "";
            try
            {
                HttpWebRequest commonRequest = (HttpWebRequest)WebRequest.Create(serverUrl);
                commonRequest.Method = "POST";

                //commonRequest.ContentType = "application/x-json";
                //byte[] byteArr = Encoding.UTF8.GetBytes(param);
                using (Stream reqStream = commonRequest.GetRequestStream())
                {
                    reqStream.Write(byteArr, 0, byteArr.Length);
                }
                using (HttpWebResponse HttpWResp = (HttpWebResponse)commonRequest.GetResponse())
                {
                    try
                    {
                        Stream myStream = HttpWResp.GetResponseStream();
                        StreamReader sr = new StreamReader(myStream, Encoding.UTF8);
                        StringBuilder strBuilder = new StringBuilder();
                        while (-1 != sr.Peek())
                        {
                            strBuilder.Append(sr.ReadLine());
                        }
                        strResult = HttpUtility.UrlDecode(strBuilder.ToString());
                    }
                    catch (Exception exp)
                    {
                        strResult = "400";// "错误:" + exp.Message;
                    }
                }
            }
            catch (Exception exp)
            {
                strResult = "500";// "错误:" + exp.Message;
            }
            return strResult;
        }

        #endregion
       
    }

 

2.调用实例

string json = APIRequest.CommonAPIAccess(APIRequest.commonUrl + "Icity.do?m=GetCityByProvinceid", Encoding.UTF8.GetBytes(HttpUtility.UrlEncode("{\"code\":\"" + comprovince.SelectedValue.ToString() + "\"}",Encoding.UTF8)));
            string msg = "1";
            if (json != "500")
            {
                try
                {

                    List<City> list = JsonConvert.DeserializeObject<List<City>>(json);
                    comcity.DataSource = list;
                    comcity.DisplayMember = "name";
                    comcity.ValueMember = "code";
                }
                catch (Exception ex)
                {
                    msg = "400";
                }
            }
            else
            { MessageBox.Show("与服务器连接失败"); }

posted on 2015-04-03 16:19  MyBeN  阅读(2295)  评论(0编辑  收藏  举报

导航