zoukankan      html  css  js  c++  java
  • webservice 写的加载url并返回json

       写了一个接口实现调用别人的接口返回json数据,在自己的接口里输出json字符串。下面有关于json字符串返回值的中文乱码问题。

      

      

    using System;
    using System.Collections.Generic;
    using System.IO;
    using System.Linq;
    using System.Net;
    using System.Web;
    using System.Web.Services;
    
    namespace search
    {
        /// <summary>
        /// SearchWebService 的摘要说明
        /// </summary>
        [WebService(Namespace = "http://tempuri.org/")]
        [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
        [System.ComponentModel.ToolboxItem(false)]
        // 若要允许使用 ASP.NET AJAX 从脚本中调用此 Web 服务,请取消注释以下行。 
        // [System.Web.Script.Services.ScriptService]
        public class SearchWebService : System.Web.Services.WebService
        {
    
            [WebMethod]
            public void LbsSearch(string a,string b)
            {
                string url = string.Format("http://url地址?a={0}&b={1}", a, b);
                var json=GetHtml(url);
                //TotalInfo TotalInfo = JsonConvert.DeserializeObject<TotalInfo>(json);
                Context.Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
                Context.Response.Write(json);
                Context.Response.End();
            }
            private string GetHtml(string URL)
            {           
                var request = (HttpWebRequest)WebRequest.Create(URL);
               var response = request.GetResponse();
               using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8))
               {
                 return reader.ReadToEnd();
               } } } }

      调用的接口读取的编码是utf-8编码,直接response.write(json字符串) 在google被浏览器自动解码了不会出现中文乱码,而在火狐和ie上则会出现中文乱码,只需要在返回之前给他中文编码就行了Context.Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");

  • 相关阅读:
    ajax学习笔记
    CSS3伪类
    《HTML5与CSS3基础教程》学习笔记 ——Four Day
    《HTML5与CSS3基础教程》学习笔记 ——Three Day
    《HTML5与CSS3基础教程》学习笔记 ——Two Day
    《HTML5与CSS3基础教程》学习笔记 ——One Day
    js面向对象笔记
    《锋利的jQuery》心得笔记--Four Sections
    《锋利的jQuery》心得笔记--Three Sections
    《锋利的jQuery》心得笔记--Two Sections
  • 原文地址:https://www.cnblogs.com/xiabuyanyu/p/6381937.html
Copyright © 2011-2022 走看看