c#post给http接口

  private ResponseDescription getData(string fileName, string keyword)
        {
            ResponseDescription rd = new ResponseDescription();
            try
            {
                string url = ConfigurationManager.AppSettings["BlackDictionaryURL"];//+ HttpUtility.UrlEncode(keyword, Encoding.GetEncoding("gbk"));
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
                request.KeepAlive = true;
                request.Method = "POST";
                request.ContentType = "application/x-www-form-urlencoded;charset=utf-8";
                string requestContent = "word=" + HttpUtility.UrlEncode(keyword, Encoding.GetEncoding("utf-8"));
                //string requestContent = "word=" + keyword;
                byte[] requestByte = System.Text.Encoding.GetEncoding("utf-8").GetBytes(requestContent);
                request.ContentLength = requestByte.Length;

                request.GetRequestStream().Write(requestByte, 0, requestByte.Length);
                request.GetRequestStream().Flush();

                HttpWebResponse response = (HttpWebResponse)request.GetResponse();

                Stream stream = response.GetResponseStream();
                byte[] responseContent = new byte[response.ContentLength];
                stream.Read(responseContent, 0, responseContent.Length);
                string content = System.Text.Encoding.GetEncoding(response.ContentEncoding).GetString(responseContent);
                string[] parm = content.Split(new char[] { ':' });
                if (parm.Length == 2)
                {
                    if (parm[0].Equals("OK"))
                    {
                        string[] result = parm[1].Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                        if (result.Length > 0)
                        {
                            rd.State = SystemError.BlackDictionarykInContent;
                            rd.Description = "文件名[" + fileName + "]中[" + parm[1].Replace(',', '|') + "]为黑字典\r\n";
                        }
                        else
                        {
                            rd.State = SystemError.OK;
                            rd.Description = "文件名[" + fileName + "]中不存在黑字典";
                        }
                    }
                    else if (parm[0].Equals("ERROR"))
                    {
                        rd.State = SystemError.BlackDictionarykParameterError;
                    }
                }
                else
                {
                    rd.State = SystemError.BlackDictionarykParameterError;
                }
            }
            catch (Exception es)
            {
                //rd.State = SystemError.System;
                //rd.Description = es.ToString() + es.StackTrace;

                rd.State = SystemError.OK;
                rd.Description = "文件名[" + fileName + "]中不存在黑字典";
            }
            return rd;
        }
    }

没有更多推荐了,返回首页