简体   繁体   中英

C# HttpWebRequest.GetResponse encoding URL

I am using the C# HttpWebRequest.GetResponse with a URL that is not encoded. But when I inspect the request using fiddler I see that the URL is encoded. I wanted to confirm that HttpWebRequest Class is encoding the URL internally but could not find it in the documentation. Can someone point me to the documentation where i can find this or some other way to validate it?

  • KR

Here it is:

WebRequest.Create (you are using that method to create your HttpWebRequest object, right?) says "The Create method uses the requestUriString parameter to create a Uri instance that it passes to the new WebRequest"
https://msdn.microsoft.com/en-us/library/bw00b1dc(v=vs.110).aspx

The constructor for Uri (which is being called by the Create method) says it "parses the URI, "
https://msdn.microsoft.com/en-us/library/z6c2z492(v=vs.110).aspx

//endpoint is url and method can be post or get... the below will help you to catch any errors from server..

make it a function so its wll be easy for you to use where ever you want ...

   HttpWebRequest httpRequest = (HttpWebRequest)HttprequestObject(endpoints, method);
        using (var streamWriter = new StreamWriter(httpRequest.GetRequestStream()))
        {
            streamWriter.Write(jsonObject);
            streamWriter.Flush();
            streamWriter.Close();
        }
        var result = "";
        HttpWebResponse httpResponse;
        try
        {
            httpResponse = (HttpWebResponse)httpRequest.GetResponse();
            using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
            {
                result = streamReader.ReadToEnd();
            }
        }
        catch (WebException e)
        {
            Console.WriteLine("This program is expected to throw WebException on successful run." +
                                "\n\nException Message :" + e.Message);
            if (e.Status == WebExceptionStatus.ProtocolError)
            {
                Console.WriteLine("Status Code : {0}", ((HttpWebResponse)e.Response).StatusCode);
                Console.WriteLine("Status Description : {0}", ((HttpWebResponse)e.Response).StatusDescription);
                using (Stream data = e.Response.GetResponseStream())
                using (var reader = new StreamReader(data))
                {
                    string text = reader.ReadToEnd();
                    Console.WriteLine(text);
                }
            }
        }
        catch (Exception e)
        {
            Console.WriteLine(e.Message);
        }

or u want class and u want to use for creating api lib then just copy paste this class ..this is for c# but almost similer syntax for java ...

with this u can access any api or url or also used to pass json file to server ..

using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;

namespace ExternalAPIs_SynapsePay.Helpers
{
    class RESTHelpers
    {
        public dynamic APICalls(JObject jsonObject, string endpoints, string method)
        {
            HttpWebRequest httpRequest = (HttpWebRequest)HttprequestObject(endpoints, method);
            using (var streamWriter = new StreamWriter(httpRequest.GetRequestStream()))
            {
                streamWriter.Write(jsonObject);
                streamWriter.Flush();
                streamWriter.Close();
            }
            var result = "";
            HttpWebResponse httpResponse;
            try
            {
                httpResponse = (HttpWebResponse)httpRequest.GetResponse();
                using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
                {
                    result = streamReader.ReadToEnd();
                }
            }
            catch (WebException e)
            {
                Console.WriteLine("This program is expected to throw WebException on successful run." +
                                    "\n\nException Message :" + e.Message);
                if (e.Status == WebExceptionStatus.ProtocolError)
                {
                    Console.WriteLine("Status Code : {0}", ((HttpWebResponse)e.Response).StatusCode);
                    Console.WriteLine("Status Description : {0}", ((HttpWebResponse)e.Response).StatusDescription);
                    using (Stream data = e.Response.GetResponseStream())
                    using (var reader = new StreamReader(data))
                    {
                        string text = reader.ReadToEnd();
                        Console.WriteLine(text);
                    }
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }

            return result;
            //return "Success";
            //not sure what to return 
            //here i have to add sql server code to enter into database
        }

        public HttpWebRequest HttprequestObject(string endpoints, string method)
        {
            string url = Setting.API_TEST_VALUE + endpoints;
            var httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
            httpWebRequest.ContentType = "application/json";
            httpWebRequest.Method = method;
            return httpWebRequest;
        }

        /// <summary>
        /// This method is useful when you have to pass JSON as string not as object... This is basically a constructor..
        /// Even if u pass json object it will accept, so no need to worry about that.
        /// </summary>
        /// <param name="ljson"></param>
        /// <param name="endpoints"></param>
        /// <param name="method"></param>
        /// <returns></returns>
        public dynamic APICalls(string jsonString, string endpoints, string method)
        {
            HttpWebRequest httpRequest = (HttpWebRequest)HttprequestObject(endpoints, method);
            using (var streamWriter = new StreamWriter(httpRequest.GetRequestStream()))
            {
                streamWriter.Write(jsonString);
                streamWriter.Flush();
                streamWriter.Close();
            }
            var result = "";
            HttpWebResponse httpResponse;
            try
            {
                httpResponse = (HttpWebResponse)httpRequest.GetResponse();
                using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
                {
                    result = streamReader.ReadToEnd();
                }
            }
            catch (WebException e)
            {
                Console.WriteLine("This program is expected to throw WebException on successful run." +
                                    "\n\nException Message :" + e.Message);
                if (e.Status == WebExceptionStatus.ProtocolError)
                {
                    Console.WriteLine("Status Code : {0}", ((HttpWebResponse)e.Response).StatusCode);
                    Console.WriteLine("Status Description : {0}", ((HttpWebResponse)e.Response).StatusDescription);
                    using (Stream data = e.Response.GetResponseStream())
                    using (var reader = new StreamReader(data))
                    {
                        string text = reader.ReadToEnd();
                        Console.WriteLine(text);
                        result = text;
                    }
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }

            return result;
            //return "Success";
            //not sure what to return 
            //here i have to add sql server code to enter into database
        }
        public void HttlpResponseObject(HttpWebRequest httpResponse)
        {
            var response = (HttpWebResponse)httpResponse.GetResponse();
            using (var streamReader = new StreamReader(response.GetResponseStream()))
            {
                var result = streamReader.ReadToEnd();
            }
            //entry into databse can be done from here 
            //or it should return some value
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM