C# - WebRequest的HTTP POST与曲奇(港从卷曲脚本) [英] c# - WebRequest HTTP POST with Cookie (port from curl script)

查看:150
本文介绍了C# - WebRequest的HTTP POST与曲奇(港从卷曲脚本)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

IBM的RTC REST的API给一个shell脚本示例用于与服务器进行身份验证:

  COOKIES = /饼干.TXT 

USER = my_user
PASSWORD = MY_PASSWORD
主机=https://开头myJazzServer:9092 /爵士

卷曲-k -c $ COOKIES$ HOST /认证/身份

卷曲-k -l -b $ COOKIES -c $ COOKIES -d为j_username = $ USER -d为j_password = $ PASSWORD$ HOST /认证/ j_security_check

这完美的作品,但我需要使用C#与服务器进行身份验证。



到目前为止,我有以下的,但它不工作(返回授权失败页):

 的CookieContainer _COOKIE; 

公共字符串_RTC()
{
HttpWebRequest的要求=(HttpWebRequest的)WebRequest.Create(https://myJazzServer.com:9092/jazz/authenticated/identity) ;
如果(_COOKIE == NULL)
{
_COOKIE =新的CookieContainer();
}
串;
request.CookieContainer = _COOKIE;使用(VAR响应= request.GetResponse())
{
使用
(StreamReader的SR =新的StreamReader(response.GetResponseStream()))
{
A = SR .ReadToEnd();
}
}




字节[]数据=(新ASCIIEncoding())GetBytes会(为j_username = MYUSER&安培;为j_password =为mypass);

=请求(HttpWebRequest的)WebRequest.Create(https://myJazzServer.com:9092/jazz/authenticated/j_security_check);

request.Method =POST;
request.ContentType =text / html的;
request.ContentLength = data.Length;
request.CookieContainer = _COOKIE;
流reqStream = request.GetRequestStream();
reqStream.Write(数据,0,data.Length);

线B:使用(VAR响应= request.GetResponse())
{
使用

(VAR读者=新的StreamReader(response.GetResponseStream()))
{
B = reader.ReadToEnd();
}
}
}


解决方案

我建议你尝试以下方法:

 公共类WebClientEx:Web客户端
{
私人的CookieContainer _cookieContainer =新的CookieContainer();

保护覆盖的WebRequest GetWebRequest(URI地址)
{
的WebRequest请求= base.GetWebRequest(地址);
如果(请求的HttpWebRequest)
{
(要求为HttpWebRequest的).CookieContainer = _cookieContainer;
}
返回请求;
}
}用

类节目
{
静态无效的主要()
{
(VAR的客户=新WebClientEx ())
{
VAR response1 = client.DownloadString(https://myJazzServer.com:9092/jazz/authenticated/identity);

VAR数据=新的NameValueCollection
{
{为j_username,MYUSER},
{为j_password,为mypass},
};
变种响应2 = client.UploadValues(https://myJazzServer.com:9092/jazz/authenticated/j_security_check数据);
Console.WriteLine(Encoding.Default.GetString(响应2));
}
}
}



另外要简化调试,你可以通过激活把这个在你的app.config追踪:

 <结构> 

<&System.Diagnostics程序GT;
<来源和GT;
<信源名称=的System.Net.SocketsTRACEMODE =protocolonly>
<&听众GT;
<添加名称=的System.Net.SocketsTYPE =System.Diagnostics.TextWriterTraceListenerinitializeData =network.log/>
< /听众>
< /源>
< /来源>

<开关与GT;
<添加名称=的System.Net.SocketsVALUE =详细/>
< /开关>

<跟踪自动冲洗=真/>
< /system.diagnostics>
< /结构>

这将创建一个网络活动,这可能会简化调试的详细日志文件。


The IBM RTC RESTful api gives an example of a shell script for authenticating with the server:

COOKIES=./cookies.txt

USER=my_user
PASSWORD=my_password
HOST="https://myJazzServer:9092/jazz"

curl -k -c $COOKIES "$HOST/authenticated/identity"

curl -k -L -b $COOKIES -c $COOKIES -d j_username=$USER -d j_password=$PASSWORD "$HOST/authenticated/j_security_check"

This works perfectly, however i need to authenticate with the server using c#.

So far i have the following, but it isn't working (returns the authorization failed page):

    CookieContainer _cookie;

    public string _RTC()
    {
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://myJazzServer.com:9092/jazz/authenticated/identity");
        if (_cookie == null)
        {
            _cookie = new CookieContainer();
        }
        string a;
        request.CookieContainer = _cookie;
        using (var response = request.GetResponse())
        {
            using (StreamReader sr = new StreamReader(response.GetResponseStream()))
            {
                a = sr.ReadToEnd();
            }
        }




        byte[] data = (new ASCIIEncoding()).GetBytes("j_username=myUser&j_password=MyPass");

        request = (HttpWebRequest)WebRequest.Create("https://myJazzServer.com:9092/jazz/authenticated/j_security_check");

        request.Method = "POST";
        request.ContentType = "text/html";
        request.ContentLength = data.Length;
        request.CookieContainer = _cookie;
        Stream reqStream = request.GetRequestStream();
        reqStream.Write(data,0,data.Length);

        string b;

        using (var response = request.GetResponse())
        {
            using (var reader = new StreamReader(response.GetResponseStream()))
            {
                b = reader.ReadToEnd();
            }
        }
    }

解决方案

I would suggest you try the following:

public class WebClientEx : WebClient
{
    private CookieContainer _cookieContainer = new CookieContainer();

    protected override WebRequest GetWebRequest(Uri address)
    {
        WebRequest request = base.GetWebRequest(address);
        if (request is HttpWebRequest)
        {
            (request as HttpWebRequest).CookieContainer = _cookieContainer;
        }
        return request;
    }
}

class Program
{
    static void Main()
    {
        using (var client = new WebClientEx())
        {
            var response1 = client.DownloadString("https://myJazzServer.com:9092/jazz/authenticated/identity");

            var data = new NameValueCollection
            {
                { "j_username", "myUser" },
                { "j_password", "MyPass" },
            };
            var response2 = client.UploadValues("https://myJazzServer.com:9092/jazz/authenticated/j_security_check", data);
            Console.WriteLine(Encoding.Default.GetString(response2));
        }
    }
}

Also to simplify debugging you could activate tracing by putting this in your app.config:

<configuration>

  <system.diagnostics>
    <sources>
      <source name="System.Net.Sockets" tracemode="protocolonly">
        <listeners>
          <add name="System.Net.Sockets" type="System.Diagnostics.TextWriterTraceListener" initializeData="network.log" />
        </listeners>
      </source>
    </sources>

    <switches>
      <add name="System.Net.Sockets" value="Verbose"/>
    </switches>

    <trace autoflush="true" />
  </system.diagnostics>
</configuration>

This will create a detailed log file of the network activity which might simplify debugging.

这篇关于C# - WebRequest的HTTP POST与曲奇(港从卷曲脚本)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆