2011-11-05 25 views
9

私は使用しているサービス用のカスタムHTTPクラスを持っています。最終的には、サービス固有の要求がメソッドの形式で格納されます。私がする必要があるのは、例えば、ユーザーがプロキシリストを持っている場合など、ユーザーが提供するプロキシの資格情報を設定することです。資格情報をWebProxyに渡す?

以下は私のコードです。私は信任状を設定するために必要な部分をコメントしました。 MSDNのiCredentialsクラスを見てきましたが、文字列から設定する方法はわかりません。

class RequestClass 
{ 
    private CookieContainer cookieJar; 
    private WebProxy proxy = null; 

    public RequestClass() 
    { 
     this.cookieJar = new CookieContainer(); 
    } 

    public RequestClass(String proxyURL, int port) 
    { 
     this.proxy = new WebProxy(proxyURL, port); 
    } 

    public RequestClass(String proxyURL, int port, String username, String password) 
    { 
     this.proxy = new WebProxy(proxyURL, port); 
     // Need to set them here 
    } 

    // HTTP Get Request 
    public HttpWebResponse getRequest(String url, NameValueCollection headers) 
    { 
     HttpWebRequest getRequest = (HttpWebRequest)WebRequest.Create(url); 
     getRequest.Method = "GET"; 
     getRequest.CookieContainer = cookieJar; 

     foreach (String key in headers.Keys) 
     { 
      getRequest.Headers.Add(key, headers[key]); 
     } 

     return (HttpWebResponse)getRequest.GetResponse(); 
    } 

    // HTTP Post Request 
    public HttpWebResponse postRequest(String url, String postData, NameValueCollection headers) 
    { 
     byte[] postBytes = Encoding.ASCII.GetBytes(postData); 

     HttpWebRequest postRequest = (HttpWebRequest)WebRequest.Create(url); 
     postRequest.Method = "POST"; 
     postRequest.CookieContainer = cookieJar; 
     postRequest.ContentLength = postBytes.Length; 
     postRequest.ProtocolVersion = HttpVersion.Version10; 

     foreach(String key in headers.Keys) 
     { 
      postRequest.Headers.Add(key, headers[key]); 
     } 

     Stream postRequestStream = postRequest.GetRequestStream(); 

     postRequestStream.Write(postBytes, 0, postBytes.Length); 
     postRequestStream.Close(); 

     return (HttpWebResponse)postRequest.GetResponse(); 
    } 
} 

}

答えて

16

私は、これは動作するはずだと思う:私は答えをリフレッシュする前に、私はちょうどNetworkCredentialの約読んでいた

public RequestClass(String proxyURL, int port, String username, String password) 
{ 
    //Validate proxy address 
    var proxyURI = new Uri(string.Format("{0}:{1}", proxyURL, port)); 

    //Set credentials 
    ICredentials credentials = new NetworkCredential(username, password); 

    //Set proxy 
    this.proxy = = new WebProxy(proxyURI, true, null, credentials); 
} 
+0

。私はあなたが正しいと思う、それはそれを行う方法です。私はそれをテストします。 –

関連する問題