Exemple #1
0
        ///<summary>
        ///HttpWebRequestオブジェクトを取得する。パラメータはGET/HEAD/DELETEではクエリに、POST/PUTではエンティティボディに変換される。
        ///</summary>
        ///<remarks>
        ///追加で必要となるHTTPヘッダや通信オプションは呼び出し元で付加すること
        ///(Timeout,AutomaticDecompression,AllowAutoRedirect,UserAgent,ContentType,Accept,HttpRequestHeader.Authorization,カスタムヘッダ)
        ///POST/PUTでクエリが必要な場合は、requestUriに含めること。
        ///</remarks>
        ///<param name="method">HTTP通信メソッド(GET/HEAD/POST/PUT/DELETE)</param>
        ///<param name="requestUri">通信先URI</param>
        ///<param name="param">GET時のクエリ、またはPOST時のエンティティボディ</param>
        ///<returns>引数で指定された内容を反映したHttpWebRequestオブジェクト</returns>
        protected HttpWebRequest CreateRequest(string method,
                                               Uri requestUri,
                                               Dictionary <string, string> param)
        {
            Networking.CheckInitialized();

            //GETメソッドの場合はクエリとurlを結合
            UriBuilder ub = new UriBuilder(requestUri.AbsoluteUri);

            if (param != null && (method == "GET" || method == "DELETE" || method == "HEAD"))
            {
                ub.Query = MyCommon.BuildQueryString(param);
            }

            HttpWebRequest webReq = (HttpWebRequest)WebRequest.Create(ub.Uri);

            webReq.ReadWriteTimeout = 90 * 1000; //Streamの読み込みは90秒でタイムアウト(デフォルト5分)

            //プロキシ設定
            if (Networking.ProxyType != ProxyType.IE)
            {
                webReq.Proxy = Networking.Proxy;
            }

            webReq.Method = method;
            if (method == "POST" || method == "PUT")
            {
                webReq.ContentType = "application/x-www-form-urlencoded";
                //POST/PUTメソッドの場合は、ボディデータとしてクエリ構成して書き込み
                using (StreamWriter writer = new StreamWriter(webReq.GetRequestStream()))
                {
                    writer.Write(MyCommon.BuildQueryString(param));
                }
            }
            //cookie設定
            if (this.UseCookie)
            {
                webReq.CookieContainer = this.cookieContainer;
            }
            //タイムアウト設定
            webReq.Timeout = this.InstanceTimeout ?? (int)Networking.DefaultTimeout.TotalMilliseconds;

            webReq.UserAgent = Networking.GetUserAgentString();

            // KeepAlive無効なサーバー(Twitter等)に使用すると、タイムアウト後にWebExceptionが発生する場合あり
            webReq.KeepAlive = false;

            return(webReq);
        }
Exemple #2
0
        ///<summary>
        ///HttpWebRequestオブジェクトを取得する。multipartでのバイナリアップロード用。
        ///</summary>
        ///<remarks>
        ///methodにはPOST/PUTのみ指定可能
        ///</remarks>
        ///<param name="method">HTTP通信メソッド(POST/PUT)</param>
        ///<param name="requestUri">通信先URI</param>
        ///<param name="param">form-dataで指定する名前と文字列のディクショナリ</param>
        ///<param name="binaryFileInfo">form-dataで指定する名前とバイナリファイル情報のリスト</param>
        ///<returns>引数で指定された内容を反映したHttpWebRequestオブジェクト</returns>
        protected HttpWebRequest CreateRequest(string method,
                                               Uri requestUri,
                                               Dictionary <string, string> param,
                                               List <KeyValuePair <String, FileInfo> > binaryFileInfo)
        {
            Networking.CheckInitialized();

            //methodはPOST,PUTのみ許可
            UriBuilder ub = new UriBuilder(requestUri.AbsoluteUri);

            if (method == "GET" || method == "DELETE" || method == "HEAD")
            {
                throw new ArgumentException("Method must be POST or PUT");
            }
            if ((param == null || param.Count == 0) && (binaryFileInfo == null || binaryFileInfo.Count == 0))
            {
                throw new ArgumentException("Data is empty");
            }

            HttpWebRequest webReq = (HttpWebRequest)WebRequest.Create(ub.Uri);

            //プロキシ設定
            if (Networking.ProxyType != ProxyType.IE)
            {
                webReq.Proxy = Networking.Proxy;
            }

            webReq.Method = method;
            if (method == "POST" || method == "PUT")
            {
                string boundary = System.Environment.TickCount.ToString();
                webReq.ContentType = "multipart/form-data; boundary=" + boundary;
                using (Stream reqStream = webReq.GetRequestStream())
                {
                    //POST送信する文字データを作成
                    if (param != null)
                    {
                        string postData = "";
                        foreach (KeyValuePair <string, string> kvp in param)
                        {
                            postData += "--" + boundary + "\r\n" +
                                        "Content-Disposition: form-data; name=\"" + kvp.Key + "\"" +
                                        "\r\n\r\n" + kvp.Value + "\r\n";
                        }
                        byte[] postBytes = Encoding.UTF8.GetBytes(postData);
                        reqStream.Write(postBytes, 0, postBytes.Length);
                    }
                    //POST送信するバイナリデータを作成
                    if (binaryFileInfo != null)
                    {
                        foreach (KeyValuePair <string, FileInfo> kvp in binaryFileInfo)
                        {
                            string postData = "";
                            byte[] crlfByte = Encoding.UTF8.GetBytes("\r\n");
                            //コンテンツタイプの指定
                            string mime = "";
                            switch (kvp.Value.Extension.ToLower())
                            {
                            case ".jpg":
                            case ".jpeg":
                            case ".jpe":
                                mime = "image/jpeg";
                                break;

                            case ".gif":
                                mime = "image/gif";
                                break;

                            case ".png":
                                mime = "image/png";
                                break;

                            case ".tiff":
                            case ".tif":
                                mime = "image/tiff";
                                break;

                            case ".bmp":
                                mime = "image/x-bmp";
                                break;

                            case ".avi":
                                mime = "video/avi";
                                break;

                            case ".wmv":
                                mime = "video/x-ms-wmv";
                                break;

                            case ".flv":
                                mime = "video/x-flv";
                                break;

                            case ".m4v":
                                mime = "video/x-m4v";
                                break;

                            case ".mov":
                                mime = "video/quicktime";
                                break;

                            case ".mp4":
                                mime = "video/3gpp";
                                break;

                            case ".rm":
                                mime = "application/vnd.rn-realmedia";
                                break;

                            case ".mpeg":
                            case ".mpg":
                                mime = "video/mpeg";
                                break;

                            case ".3gp":
                                mime = "movie/3gp";
                                break;

                            case ".3g2":
                                mime = "video/3gpp2";
                                break;

                            default:
                                mime = "application/octet-stream\r\nContent-Transfer-Encoding: binary";
                                break;
                            }
                            postData = "--" + boundary + "\r\n" +
                                       "Content-Disposition: form-data; name=\"" + kvp.Key + "\"; filename=\"" +
                                       kvp.Value.Name + "\"\r\n" +
                                       "Content-Type: " + mime + "\r\n\r\n";
                            byte[] postBytes = Encoding.UTF8.GetBytes(postData);
                            reqStream.Write(postBytes, 0, postBytes.Length);
                            //ファイルを読み出してHTTPのストリームに書き込み
                            using (FileStream fs = new FileStream(kvp.Value.FullName, FileMode.Open, FileAccess.Read))
                            {
                                int    readSize  = 0;
                                byte[] readBytes = new byte[0x1000];
                                while (true)
                                {
                                    readSize = fs.Read(readBytes, 0, readBytes.Length);
                                    if (readSize == 0)
                                    {
                                        break;
                                    }
                                    reqStream.Write(readBytes, 0, readSize);
                                }
                            }
                            reqStream.Write(crlfByte, 0, crlfByte.Length);
                        }
                    }
                    //終端
                    byte[] endBytes = Encoding.UTF8.GetBytes("--" + boundary + "--\r\n");
                    reqStream.Write(endBytes, 0, endBytes.Length);
                }
            }
            //cookie設定
            if (this.UseCookie)
            {
                webReq.CookieContainer = this.cookieContainer;
            }
            //タイムアウト設定
            webReq.Timeout = this.InstanceTimeout ?? (int)Networking.DefaultTimeout.TotalMilliseconds;

            // KeepAlive無効なサーバー(Twitter等)に使用すると、タイムアウト後にWebExceptionが発生する場合あり
            webReq.KeepAlive = false;

            return(webReq);
        }