如何在HttpListenerRequest中处理Url编码?

时间:2011-01-12 22:24:41

标签: c# .net httplistenerrequest

我正在构建一个使用HttpListener来处理请求的简单服务器。如果需要,我发送给它的查询字符串参数是url编码的。例如,要发送汉字字符串"尺八",编码为"%E5%B0%BA%E5%85%AB"

我的示例网址是"/?q=%E5%B0%BA%E5%85%AB"

在我的上下文回调中,我有:

HttpListenerContext context = Listener.EndGetContext();
string rawUrl = context.Request.RawUrl;
string query = context.Request.QueryString["q"];

检查结果,我得到:

rawUrl = "/?q=%E5%B0%BA%E5%85%AB" 
query = "尺八"

但如果我查看context.Request.Url,我会得到{http://localhost:8080/?q=尺八}

看起来context.Request.QueryString中的查询字符串正在使用除UTF-8之外的某些编码进行解码。

我的解决方法是忽略context.Request.QueryString并通过这样做创建我自己的:

var queryString = HttpUtility.ParseQueryString(context.Request.Url.Query);

这给了我正确的价值,但它似乎是一种黑客攻击。

有没有办法告诉HttpListener(或上下文或请求)将查询字符串解释为UTF-8,我认为这仍然是标准?或者我应该忍受这种解决方法吗?

2 个答案:

答案 0 :(得分:2)

通过查看代码,它依赖于将ContentEncoding设置为UTF8。这是来自HttpListenerRequest的QueryString属性的片段:

public NameValueCollection QueryString
{
    get
    {
        NameValueCollection nvc = new NameValueCollection();
        Helpers.FillFromString(nvc, this.Url.Query, true, this.ContentEncoding);
        return nvc;
    }
}

由于无法修改ContentEncoding属性,因此您无法使用“hack”。无论如何,我认为你使用HttpUtility.ParseQueryString可能会为你提供最好的服务。

答案 1 :(得分:0)

尝试<android.support.v4.widget.NestedScrollView xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" app:layout_behavior="@string/appbar_scrolling_view_behavior" tools:context=".Fragment1"> <android.support.v7.widget.CardView android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginBottom="10dp" android:fitsSystemWindows="true" app:cardUseCompatPadding="true" app:elevation="5dp"> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical"> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:padding="12dp" android:text="@string/apptext" android:textSize="18sp"/> </LinearLayout> </android.support.v7.widget.CardView> </android.support.v4.widget.NestedScrollView>

System.Web.HttpUtility

了解详情https://msdn.microsoft.com/en-us/library/system.web.httputility(v=vs.110).aspx