#クライアントアプリからのHttpRequest

C#クライアントアプリからのHttpRequest(POST、バイナリー)


using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Net;
using System.Security.Cryptography.X509Certificates;
using System.Net.Security;
using xxxx.Common.AppError;
using xxxx.Common.AppLog;
using xxxx.Common.AppInfo;

namespace xxxx.Common.AppServer
{
  ///


  /// サーバーAPIリクエストクラス
  ///

  public class ServerApiRequest
  {
    #region 変数

    ///


    /// ログオブジェクト
    ///

    private AbstractAppLog appLog = null;

    #endregion

    #region コンストラクタ
    ///


    /// コンストラクタ
    ///

    public ServerApiRequest()
    {
      //ログオブジェクト
      AppLogManager alm = new AppLogManager();
      this.appLog = alm.Create();
    }
    #endregion

    #region サーバ証明書検証コールバック
    ///


    /// サーバ証明書検証コールバック
    ///

    /// 送信元オブジェクト
    /// X509Certificateオブジェクト
    /// X509Chain オブジェクト
    /// SSL (Secure Socket Layer) のポリシー エラー
    /// trueを返す
    private bool OnRemoteCertificateValidationCallback(
      Object sender,
      X509Certificate certificate,
      X509Chain chain,
      SslPolicyErrors sslPolicyErrors)
    {
      // 信用したことにする
      return true;
    }
    #endregion

    #region サーバーAPI処理リクエスト
    ///


    /// サーバーAPIリクエスト
    ///

    /// アプリケーション名
    /// プロトコル
    /// ホスト
    /// ポート番号
    /// リクエストURL
    /// サーバーAPI処理パラメータ
    /// サーバーAPI処理レスポンス
    /// エラーステータス
    public ErrorStatus RequestApi(AppComposition.AppName argAppName, string argProtocol,
      string argHost, string argPortNo, string argRequestUrl,
      byte argParamArray, out byte argResponseArray)
    {
      Stream reqStream = null;
      BufferedStream binStream = null;
      Stream rspStream = null;
      argResponseArray = null;
      ErrorStatus errStatus = new ErrorStatus();

      try
      {
        //URL
        string url = string.Format("{0}://{1}:{2}{3}", argProtocol,argHost, argPortNo, argRequestUrl);

        //SSL証明書のエラーを回避
        ServicePointManager.ServerCertificateValidationCallback =
          new RemoteCertificateValidationCallback(OnRemoteCertificateValidationCallback);

        //WebRequestの作成
        HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);

        //メソッドにPOSTを指定
        req.Method = "POST";

        //ContentTypeを設定
        req.ContentType = "multipart/form-data";

        //POST送信するデータの長さを指定
        req.ContentLength = argParamArray.Length;

        //要求がタイムアウトするまでのミリ秒単位の待機時間(この指定が無い場合デフォルトで100秒)
        req.Timeout = 1000 * 300;

        //データをPOST送信するためのStreamを取得
        reqStream = req.GetRequestStream();

        //送信するデータを書き込む
        reqStream.Write(argParamArray, 0, argParamArray.Length);

        //サーバーからの応答を受信するためのWebResponseを取得
        HttpWebResponse rsp = (System.Net.HttpWebResponse)req.GetResponse();

        //レスポンスをチェック
        if (HttpStatusCode.OK == rsp.StatusCode)
        {
          //応答データを受信するためのStreamを取得
          rspStream = rsp.GetResponseStream();

          //受信データをバイト配列へ変換
          int ret;
          List byteList = new List();
          binStream = new BufferedStream(rspStream);

          while (true)
          {
            ret = binStream.ReadByte();
            if (-1 != ret)
            {
              byteList.Add((byte)ret);
            }
            else
            {
              break;
            }
          }

          argResponseArray = new byte[byteList.Count];

          for (int i = 0; i < byteList.Count; i++)
          {
            argResponseArray[i] = byteList[i];
          }
        }
        else
        {
          //ERROR:エラー処理:サーバーレスポンスエラー
          errStatus.ErrorCode = ErrorInformation.ErrorCode.ServerErrorResponseError;

          this.appLog.Write(argAppName, AppLogInformation.LogLevel.FATAL,
            errStatus.ErrorCode, "サーバーレスポンスエラー" + Environment.NewLine + Environment.StackTrace);
        }
      }
      catch (System.Net.WebException ex)
      {
        //ERROR:サーバーAPIリクエスト処理
        //HTTPプロトコルエラーかどうか調べる
        if (ex.Status == System.Net.WebExceptionStatus.ProtocolError)
        {
          //サーバからの応答が有る場合

          //HttpWebResponseを取得
          System.Net.HttpWebResponse errres = (System.Net.HttpWebResponse)ex.Response;

          //応答したURI
          //string uri = errres.ResponseUri.ToString();

          //応答ステータスコード
          //string scode = string.Format("{0}:{1}", errres.StatusCode, errres.StatusDescription);

          //エラー処理
          switch (errres.StatusCode)
          {
            case HttpStatusCode.InternalServerError:
              //ERROR:500:InternalServerError:サーバエラー、パラメータが間違っている場合など
              errStatus.ErrorCode = ErrorInformation.ErrorCode.ServerErrorInternalServerError;
              
              this.appLog.Write(argAppName, AppLogInformation.LogLevel.FATAL,
                errStatus.ErrorCode, ex.ToString() + Environment.NewLine + ex.StackTrace);

              break;
            case HttpStatusCode.Forbidden:
              //ERROR:403:Forbidden:認証失敗の場合
              errStatus.ErrorCode = ErrorInformation.ErrorCode.ServerErrorForbidden;
              
              this.appLog.Write(argAppName, AppLogInformation.LogLevel.FATAL,
                errStatus.ErrorCode, ex.ToString() + Environment.NewLine + ex.StackTrace);
              
              break;
            default:
              //ERROR:403、500以外のネットワークエラーの場合
              errStatus.ErrorCode = ErrorInformation.ErrorCode.ServerErrorOther;

              this.appLog.Write(argAppName, AppLogInformation.LogLevel.FATAL,
                errStatus.ErrorCode, ex.ToString() + Environment.NewLine + ex.StackTrace);
              
              break;
          }
        }
        else
        {
          //ERROR:エラー処理:通信エラー
          errStatus.ErrorCode = ErrorInformation.ErrorCode.NetworkError;
          
          this.appLog.Write(argAppName, AppLogInformation.LogLevel.FATAL,
            errStatus.ErrorCode, ex.ToString() + Environment.NewLine + ex.StackTrace);
        }
      }
      finally
      {
        if (null != reqStream)
        {
          reqStream.Close();
        }

        if (null != rspStream)
        {
          rspStream.Close();
        }

        if (null != binStream)
        {
          binStream.Close();
        }
      }

      return errStatus;
    }
    #endregion
  }
}