C#でHTTPリクエスト時にフリーズする

このQ&Aのポイント
  • C#でGUIを作成して、WEBサーバー上のPHPで作った簡易APIにPOSTしてサーバー側にデータを溜め込み、GUIのチャットをつくっています。しかし、連続ポストすると3の倍数の回数目のPOSTのみフリーズしてしまいます。問題を解消して問題なく連続POSTができるようにしたいです。
  • 質問者はC#でGUIを作成しており、GUI上のフォームからテキストを入力してサーバー側のPHPへPOSTしログとしてためることができました。しかし、連続ポスト時に3の倍数の回数目のPOSTのみフリーズしてしまう問題が発生しています。どのようにすれば問題を解消できるでしょうか?
  • C#でGUIのチャットアプリを作成していますが、連続ポスト時に3の倍数の回数目のPOSTのみフリーズしてしまいます。フリーズが発生している間はPOSTが完了するまでに時間がかかるため、問題を解消して問題なく連続POSTができるようにしたいです。ソースコードは提供されています。
回答を見る
  • ベストアンサー

C#でHTTPリクエスト時にフリーズします。

C#でGUIを作成して、WEBサーバー上のPHPで作った簡易APIにPOSTしてサーバー側に データを溜め込みそれをC#のGUI側で随時表示という、いわばGUIのチャットをつくっています。まず、GUIをつくりGUI上のフォームからテキストを入力してサーバー側のPHPへPOSTしログとしてためることはできましたが、どうもGUI側で連続ポスト・・・大体い1~2秒に一度ポストすると、三度目のポストでGUIがフリーズしています。ただしアプリが落ちるわけでなく、POST完了にずいぶん時間がかかっているらしく一分ぐらいするとPOSTが完了してフリーズも直ります。このパターンが続きます。 つまり、3の倍数の回数目のPOSTのみフリーズするのです。なんとか、これを解消して 問題なく連続POSTができるようにしたいのです。お力添え願います。ソースは以下になります。 using System; using System.IO; using System.Windows.Forms; using System.Drawing; using System.Web; using System.Net; using System.Text; public class MainClass{ public static void Main(string [] args){ NewForm formObj = new NewForm(500,500); formObj.SetTitle("チャットアプリサンプル"); Application.EnableVisualStyles(); Application.Run(formObj); } } public class NewForm : Form{ //Formに付加するコントロールオブジェクト public Label labelObj =new Label(); public Button buttonObj =new Button(); public TextBox boxObj =new TextBox(); public TextBox responseBox =new TextBox(); public UserRequest user; public NewForm( int localWidth,int localHeight){ this.Width = localWidth; this.Height = localHeight; this.boxObj.Width = localWidth/2; this.boxObj.Height = localHeight/2; this.boxObj.Multiline =true; this.boxObj.Location = new Point(50,200); this.responseBox.Width =300; this.responseBox.Height =150; this.responseBox.Multiline =true; this.Controls.Add(this.responseBox); this.buttonObj.Text ="サーバーへ送信"; this.buttonObj.Width =150; this.buttonObj.Height =50; this.buttonObj.Location =new Point(350,10); this.buttonObj.Click += new EventHandler(this.ClickMethod); this.Controls.Add(this.boxObj); this.Controls.Add(this.buttonObj); this.user = new UserRequest("http://localhost/csharp.php"); } public void SetTitle(String titleText){ this.Text = titleText; } public void ClickMethod(Object sender , EventArgs e){ this.user.SetUrlPath("http://localhost/csharp.php"); this.user.SetPostData(this.boxObj.Text,"POST"); this.user.SendData(); this.boxObj.Text = ""; this.user.DeleteStream(); } } //通信用クラスの定義 public class UserRequest{ //HTTPリクエストオブジェクト private HttpWebRequest http; //通信先のURL private string path = ""; //通信先URLへとPOSTするpostdata private string postData =""; //通信のメソッドタイプ private string method ="POST"; //contenttypeの指定 private string ct = "application/x-www-form-urlencoded"; //送信データの文字列のurlエンコードを行う。 private Encoding encode = Encoding.GetEncoding("UTF-8"); //postデータをバイト型配列に private byte [] postDataBytes; //実際にpostデータを送受信するためのStreamを用意しておく private Stream reqStream; private Stream resStream; /* この辺は、迷っています。独自クラスのUserRequestというクラスのコンストラクタで HttpWebRequestのオブジェクトをつくってやるか それとも、オブジェクト作成のためだけのメソッドを定義してやるか・・・。 public UserRequest(string httpPath){ //this.path = httpPath; //httpオブジェクトの作成 //this.http =(HttpWebRequest) WebRequest .Create(this.path); } public void SetUrlPath (string setUrlpathData){ this.path = setUrlpathData; this.http =(HttpWebRequest) WebRequest .Create(this.path); } */ //postDataのセット public void SetPostData (string postDataParam,string methodType){ //ポストデータをUrlエンコードしアスキー文字にまとめる。 this.postData = "messageData=" + HttpUtility.UrlEncode(postDataParam,this.encode); //postDataをバイト配列型に格納する。 this.postDataBytes = Encoding.ASCII.GetBytes(this.postData); this.method = methodType; //HTTPオブジェクトにそれぞれの値を設定する。 this.http.ContentType = this.ct; this.http.Method = this.method; this.http.ContentLength = this.postDataBytes.Length; } public void SendData (){ try{ using(this.reqStream = http.GetRequestStream()){ this.reqStream.Write(this.postDataBytes,0,this.postDataBytes.Length); this.reqStream.Close(); } }catch(Exception e){ MessageBox.Show(e.ToString()); } } public void DeleteStream(){ this.http = null; this.reqStream = null; } } PHPとかjsは仕事でつかっているのですが C#見たく、完全なOOPを扱うのは初めてなので うまいユーザー定義のクラスではないかもしれません。

質問者が選んだベストアンサー

  • ベストアンサー
回答No.2

UIスレッドで時間のかかる処理を行うことをやってはいけません。 時間がかかるならば非同期処理を行う必要があります。 ・.NET 4.5~の場合 async/awaitを使うのが簡単でしょう。 コンパイラが頑張ってステートマシンを作ってくれて,処理のほとんどをUIスレッドで処理を実行してくれます。 # かつ,Networkアクセスは非同期 http://msdn.microsoft.com/ja-jp/library/hh156513 http://msdn.microsoft.com/ja-jp/library/system.net.webrequest.getresponseasync ・.NET 2.0~の場合 本来なら,以下の.NET 1.0~の場合と同じ方法がよいのですが, UI弄るのが面倒なので,BackgroundWorkerを使うのが簡単です。 # .NET 4.0だとRxという解もあるけれども省略。 http://msdn.microsoft.com/ja-jp/library/system.componentmodel.backgroundworker ・.NET 1.0~の場合 WebRequest.BeginGetResponseとWebRequest.EndGetResponseを使ったパターンを使うことになります。 UI弄るのは面倒ですが,Control.Invokeを使ってUIスレッドで実行するように書く必要があります。 http://msdn.microsoft.com/ja-jp/library/system.net.httpwebrequest.begingetresponse http://msdn.microsoft.com/ja-jp/library/zyzhdc6b

1000vicki
質問者

お礼

GUIとは別に、WEBサーバー側へ データをPOSTする処理だけThreadクラスを用いて別スレッドとして処理しました。 >UI弄るのは面倒ですが,Control.Invokeを使ってUIスレッドで実行するように書く必要があります。 というのは、メインスレッド上のフォーム要素に別スレッドから何かしらメインスレッド上のフォームにアクセスする場合に用いれるものですね。 面倒なときは、別スレッドで実行するデリゲートの中身をまるっとControls.Invoke()で ラップしてやるといいんですね。 本来はInvokeRequiredで ちゃんと条件わけしてやるのがよいのでしょうけど「・・・。

その他の回答 (1)

回答No.1

Webサーバー等にリクエストを出した時には, たいていレスポンスが返ってくるまで,時間がかかってくるものだと思うから ある程度のフリーズは,やむを得ないと思いますし, 高速にリクエストを出し続けたら,サーバー側が耐えられなくなるんじゃないですかね. とにかく連続して出したいなら, マルチスレッドにするか, もしかしたら, HttpWebRequestのProxy プロパティをnullに設定すると, 多少改善するかも.

関連するQ&A

  • C#のGraphicsクラスについて(GDI+)

    以下のようにgraphicsクラスをつかった画像の描画をおこないました。 Graphics gr = Graphics.FromImage(mapObj); というふうにからのリソースからGraphicsオブジェクトをつくる方法です。 using System; using System.IO; using System.Windows.Forms; using System.Drawing; using System.Web; using System.Net; using System.Text; using System.Threading; using System.ComponentModel; public class MainClass{ public static void Main(string [] args){ NewForm formObj = new NewForm(); formObj.RenderMethod(); Application .Run(formObj); } } public class NewForm : Form{ public NewForm(){ this.Width = 500; this.Height = 500; } public void RenderMethod(){ Bitmap mapObj = new Bitmap(500,500); Graphics gr = Graphics.FromImage(mapObj); Image imageObj = Image.FromFile("C:\\test.jpg"); gr .DrawImage(imageObj, 0,0,150,150); this.BackgroundImage = mapObj; } } このほかに、フォームコントロールの thisl.CreateGraphics()という メソッドを使っても画像を描画できるとききました。 あるサンプルをみると public class NewForm : Form{ public NewForm(){ this.Width = 500; this.Height = 500; } public void RenderMethod(){ Graphics gr = this.CreateGraphics(); Image imageObj = Image.FromFile("C:\\test.jpg"); gr .DrawImage(imageObj, 0,0,150,150); } } とこのようにthis.CreateGraphics()をつかっていましたが 実際にはこれが描画されないのです。 Graphics gr = Graphics.FromImage(mapObj); というGraphicsクラスの静的メソッドを使う方法ではなく コントロールのCreateGraphicsメソッドをつかって描画するにはどうしたらよいのですか? 識者のかた、ご教授ください。

  • C#のtextBox1への書込に関する質問

    C#(VS2013)のtextBox1への書込に関する質問です。 『textBox1.Text=str;』による、textBox1の書き込みは、『button1_Click』 の中から、直接『//write_textBox1("aaa"); 』を実行すれば出来ます。 しかし、Class1のtestを介して、『write_textBox1("bbb");』を実行した場合には textBox1に表示が出来ません。 尚、Consoleには、何れの場合にも表示出来ます。 Q1)Class1のtestを介して、textBox1への表示は可能ですか? =========== using System; using System.Windows.Forms; namespace TT_SendMessage { public partial class Form1:Form { public Form1() { InitializeComponent(); } public void write_textBox1(string str){ textBox1.Text=str; Console.WriteLine("VVVVVVVVVVVVVv"); } private void button1_Click(object sender,EventArgs e) { Class1 obj=new Class1(); obj.test(); //write_textBox1("aaa"); //<---この場合は、表示が出来る } }// public partial class Form1:Form { class Class1 { public void test() { bbb(); } public void bbb() { Form1 obj=new Form1(); obj.write_textBox1("bbb"); } }//class Class1 { } =============== 以上、宜しくお願いします。

  • 他クラスからForm1内コントロルの操作方法を教えて(C#プログラミン

    他クラスからForm1内コントロルの操作方法を教えて(C#プログラミング) Form1で定義してあるtextBox1のText値を他クラスから操作したいのですが、そのコーディング要領が判らず困っております。どなたか教えてくださいませんか? 我流で下記の様なソース(要点のみ記述、他は省略)を作ってみましたが、コンパイルエラー「'object' に 'textBox1' の定義が含まれておらず、型 'object' の最初の引数を受け付ける拡張メソッドが見つかりませんでした。using ディレクティブまたはアセンブリ参照が不足しています。」がでます。 このエラーメッセージの意味を理解できず、何故Form1オブジェクトが伝わらないのか判らず、どこをどう直せばよいのか途方に呉れております。 以下我流C#ソースの抜粋 delegate void SetTextCallback(string text); public class Form1 {   通常のForm内コントロールの定義 Object formobj = this;   AAAclass aaa = new AAAclass (formobj);   この後Aclass内の基幹メソッドを走らせる } public class AAAclass { private Object formObject = null; public AAAclass(Object formobj) { formObject = formobj;    様々な初期化処理 } private void textDisplay(string text) { if (formObject.textBox1.InvokeRequired){  //この行の"textBox1"部分がエラー SetTextCallback d = new SetTextCallback(textDisplay); formObject.Invoke(d, new object[] { text }); //この行の"Invoke"部分がエラー } else { formObject.textBox1.Text = text;  //この行の"textBox1"部分がエラー } } この後、複数のスレッドを定義し、走らせている   それらのスレッドで上記の共通テキスト表示メソッドを利用している }

  • 【C#】FindWindowExの使い方を教えてください

    はじめまして Visual Studio 2005を使用しています。 C#.NETは、いじり初めて1週間の超初心者です。 C#.NETでのFindWindowExの使い方を教えてください。 まずはじめに、vb.netで作ったアプリAの"Form1"があり、その中にテキストボックス"TextBox1"があります。 "TextBox1"のテキスト(キャプション?)には同じく"TextBox1"と入力されています。 そこで、C#側のアプリBでVBのアプリAの"Form1"のハンドルをFindWindowで取得します。 ここまでは出来ました。 次に、FindWindowExを使って"TextBox1"のハンドルを取得したいのですが、どうしてもうまく取得できません(0が返ってきます) 以下、C#のソースです。 (textBox1のMultilineはTrueです) ================================================================== using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using System.Runtime.InteropServices; namespace WindowsApplication1 { public partial class Form1 : Form { [DllImport("user32.dll")] static extern IntPtr FindWindow(string lpClassName, string lpWindowName); [DllImport("user32.dll")] static extern IntPtr FindWindowEx(IntPtr hWnd, IntPtr hwndChildAfter, string lpszClass, string lpszWindow); public IntPtr hWnd = (IntPtr)0; public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { IntPtr hWnd; IntPtr hWndTest; string sClassName = null; string sWindowText = "AppA"; // アプリAのウインドウハンドルを取得 hWnd = FindWindow(sClassName, sWindowText); textBox1.Text = "ウインドウのハンドル " + hWnd + "\r\n"; // アプリAのウインドウ内のTextBox1のハンドルを取得 hWndTest = hWnd; sClassName = null; sWindowText = "TextBox1"; hWnd = FindWindowEx(hWndTest, IntPtr.Zero, sClassName, sWindowText); textBox1.Text += "テキストボックスのハンドル " + hWnd; } } } ================================================================== Spy++で覗くとテキストボックスにもハンドルが割り与えられているので取得できるはずだと思っているのですが、どうしてもいまくいきません。 どうか、よろしくご享受願います。 ちなみに、アプリAのテキストボックスのクラス名が”WindowsForms10.EDIT.app.0.378734a”となっているのですが、これはどの環境でビルド(コンパイル)しても不変なのでしょうか? 不変だとしたら、クラス名を使えば悩まずに取得できると思うのですが・・・(実験済み)

  • C#でFormオブジェクトのイベントについて

    C#において Formオブジェクトに付加したコントロールのMouseWheelイベントについて質問です。 ある特定のコントロールにMouseWheelイベントを付加してホイールボタンの動きをつけたのですが、どうも特定のコントロールだけでなく、Formオブジェクト全体にWheelのイベントが付加されてしまっているようです。以下のコードがそれです。 using System; using System.Windows.Forms; using System.IO; using System.Drawing; //実行クラス public class MainClass{ //実行メソッド public static void Main(string [] args){ NewForm formObj =new NewForm(); formObj.SetLabel(); Application.EnableVisualStyles(); Application.Run(formObj); } } //テスト用Form拡張クラス public class NewForm :Form{ public Label labelObj; public NewForm(){ this.Width = 600; this.Height = 600; this.Text ="wheel test"; } public void SetLabel(){ this.labelObj =new Label(); this.labelObj.Width=200; this.labelObj.Height =50; this.labelObj.Location = new Point(10,10); this.labelObj.Text ="ホイールのテスト"; this.labelObj.BackColor =Color.Red; this.Controls.Add(this.labelObj); //delegate this.labelObj.MouseEnter += new EventHandler(this.EnterMethod); this.labelObj.MouseWheel += new MouseEventHandler(this.WheelMethod); } //コントロールに追加したラベルにフォーカスした時のメソッド public void EnterMethod(Object sender,EventArgs e){ this.labelObj.Focus(); } public void WheelMethod(Object sender,MouseEventArgs e){ MessageBox.Show(e.Delta.ToString()); } } 上記のコードだと、どうしても横幅200縦50のラベルコントロールの外側でもそのWheelイベントが 発生してしまうようです。 これを回避するために無理やり以下のようにソースを改変しました。 public void WheelMethod(Object sender,MouseEventArgs e){ //ディスプレイ基準ではなく、Formオブジェクト基準の座標の取得 Point tempObj = this.labelObj.PointToClient(Cursor.Position); int tempX = tempObj.X; int tempY =tempObj.Y; if ( (tempX > 0) && (tempX < this.labelObj.Width) && (tempY > 0) && (tempY < this.labelObj.Height) ){ MessageBox.Show(tempObj.X.ToString()); MessageBox.Show(tempObj.Y.ToString()); MessageBox.Show(e.Delta.ToString()); } } マウスカーソルの位置が、特定のラベルの範囲内でのみ動くようにしたのですが これのやりかたがベターというかC#上では定石なのでしょうか? そもそも、なぜラベルコントロールに対してMouseWheelイベントをつけているのに ラベルのある座標以外で、Wheelイベントが発生してしまうのでしょうか? よろしくご教授ください。 ちなみにC#の質問ってこのASPの項目でもいいんですかね? C,C++とは色が違うし、 そのほかのプログラミングのほうがよいのでしょうか?

  • C#

    form2で入力した文字を form1で表示させたいのですが、上手くいきません。プログラムの(文字制限の為)一部だけ のせます。アドバイス よろしくお願いします。 まず、form1 public class Form1 : System.Windows.Forms.Form { private System.Windows.Forms.MainMenu mainMenu1; private System.Windows.Forms.MenuItem menuItem1; private System.Windows.Forms.MenuItem menuItem2; private System.Windows.Forms.Label label1; private Form2 form2; /// <summary> /// 必要なデザイナ変数です。 /// </summary> private System.ComponentModel.Container components = null; public Form1() { // // Windows フォーム デザイナ サポートに必要です。 // InitializeComponent(); form2= new Form2(); label1.Text=string.Format("{0}",form2.s); // // TODO: InitializeComponent 呼び出しの後に、コンストラクタ コードを追加してください。 // } static void Main() { Application.Run(new Form1()); } private void menuItem2_Click(object sender, System.EventArgs e) { if (form2.ShowDialog(this) == DialogResult.OK) this.Refresh(); } } 次にform2です private void button1_Click(object sender, System.EventArgs e) { string s; s=(string)textBox1.Text; } public string s { get { return s; } }

  • 他クラスからForm1にアクセス

    Class1からForm1のtextBox1にアクセスする件、oboroxxさんの明快な回答を 参考にしまして、何とか下記の様にコードの実装が出来ました。 初めての事ですから、コメント頂けますと、大変有難いです。 追加質問: Q1) button1_Clickの中に、『Class1 obj=new Class1();』があります。 ここで、newで作られました、objはGCの対象になりますか? いや、そうではなく、button1_Clickが終了すると、objは消滅しますか? お手数ですが、宜しくお願いします。 ============================ using System; using System.Windows.Forms; namespace TT_SendMessage { public partial class Form1:Form { public Form1() { InitializeComponent(); } public void write_textBox1(string str){ textBox1.Text=str; //<---OK Console.WriteLine("VVVVVVVVVVVVVv"); } private void button1_Click(object sender,EventArgs e) { Class1 obj=new Class1(); obj.fm1_pr=this; obj.bbb(); //write_textBox1("aaa"); //<---OK } }// public partial class Form1:Form { //================ class Class1 { private Form1 fm1=new Form1(); public Form1 fm1_pr { set { this.fm1=value;} get { return this.fm1;} }//Form1 fm1 public void bbb() { fm1.write_textBox1("bbb");//non_static } }//class Class1 { //================ } 以上、宜しくお願いします。

  • C#のGraphicsクラスについてです。

    C#のGraphicsクラスを用いて画像をフェードインで表示させよとしています。 まず以下のコードをごらんください。 ただ、フェードインで画像は表示されるものの、フォームの操作が一切できなくなってしまいます。 そのためマルチスレッドにしようとしたのですが using System; using System.IO; using System.Windows.Forms; using System.Drawing; using System.Web; using System.Net; using System.Text; using System.Threading; using System.Drawing.Drawing2D; using System.Drawing.Imaging; using System.Diagnostics; public class MainClass{ public static void Main(string [] args){ NewForm formObj = new NewForm(); Application .Run(formObj); } } public class NewForm : Form { //インスタンス変数の宣言 public Graphics g ; public Bitmap mapObj ; public Image imageObj; public ImageAttributes ia; public ColorMatrix cm; public Thread th ; public ParameterizedThreadStart ts; public PaintEventArgs e; public Rectangle rec; public int flag = 0; public delegate void TestDelegate(); public TestDelegate deleObj; public NewForm(){ Button buttonObj = new Button(); buttonObj.Width=100; buttonObj.Height = 30; //フェードさせるためのイベント発行用ボタンの設置 buttonObj.Click += new EventHandler(this.SetMethod); this.Controls.Add(buttonObj); } public void SetMethod(object sender , EventArgs e){ this.Paint += new PaintEventHandler(this.ThreadMethod); //フォームコントロールの再描画を促す this.Invalidate(); } public void ThreadMethod(object sender ,PaintEventArgs eventObj){ this.ts = new ParameterizedThreadStart(this.ThreadRenderMethod); this.th = new Thread(this.ts); this.th.Start(eventObj); MessageBox.Show("ThreadMethod実行後"); MessageBox.Show(InvokeRequired.ToString()); this.th.Join(); } public void ThreadRenderMethod(object paintObj){ MessageBox.Show(InvokeRequired.ToString()); this.deleObj =delegate(){ //無現ループしてしまうので、再描画イベント後イベントハンドラーを削除 this.Paint -= new PaintEventHandler(this.ThreadMethod); PaintEventArgs e = (PaintEventArgs)paintObj; try{ Console.WriteLine("paint メソッド発生"); this. g = e.Graphics; this.mapObj = new Bitmap(this.Width,this.Height); this.imageObj = Image.FromFile("C:\\c#\\test.jpg"); //this.g = Graphics.FromImage(this.mapObj); this.cm = new ColorMatrix(); this.cm.Matrix00 = 1; this.cm.Matrix11 = 1; this.cm.Matrix22 = 1; this.cm.Matrix33 = 0.0F; this.cm.Matrix44 = 1; this.ia = new ImageAttributes(); this.ia.SetColorMatrix(this.cm); this.rec = new Rectangle(0, 0, this.Width, this.Height); this.g.DrawImage(this.imageObj,rec,0,0,this.imageObj.Width,imageObj.Height,GraphicsUnit.Pixel,this.ia); this.BackgroundImage = mapObj; for(double i = 0.0; i <= 1.0; i = i + 0.001){ this.cm.Matrix33 = (float) i; this.ia.SetColorMatrix(this.cm); this.g.DrawImage(this.imageObj,rec,0,0,this.imageObj.Width,imageObj.Height,GraphicsUnit.Pixel,this.ia); this.BackgroundImage = this.mapObj; Thread.Sleep(100); } //this.imageObj.Dispose(); //this.g.Dispose(); }catch(Exception ex){ Console.WriteLine(ex.ToString()); } Console.WriteLine("paint end"); }; this.deleObj(); //this.Invoke(this.deleObj); this.BackgroundImage = Image.FromFile("C:\\c#\\test.jpg"); } } 上記コードでも、フェードは動作するものの、やはりフォームの操作ができなくなります。 どう対処したらよいでしょうか? 識者の方、よろしくご教授ください お願いいたします

  • twitterAPIについて

    twitterAPIについて です。 今Visual Studio 2008でC#.NETでtwitterのタイムラインを読み込んでみようと思っています。 xmlを読み込むまではできましたが、 そのxmlを抽出する方法が全く分かりません。 このさきどうすればいいのでしょうか? ユーザー1:ツイート ユーザー2:ツイート といった感じにTextBoxに並べるのが目標です。 文字列をxmlに変換する方法があるのでしょうか? 一応ソースコードを載せて起きます。(using部分、例外処理などは除く) private void XmlLoad() { HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create("http://twitter.com/statuses/home_timeline.xml"); request.Credentials = new NetworkCredential(IDtext.Text, passText.Text); request.ContentType = "application/x-www-form-urlencoded"; request.Method = "POST"; request.Timeout = 10000; System.Net.ServicePointManager.Expect100Continue = false; WebResponse response = request.GetResponse(); Encoding enc = Encoding.GetEncoding(932); StreamReader reader = new StreamReader(response.GetResponseStream(), enc); string result = reader.ReadToEnd(); result = System.Web.HttpUtility.HtmlDecode(result); resultText.Text = result; reader.Close(); response.Close(); } private void OK_Click(object sender, EventArgs e) { XmlLoad(); } オブジェクト(TextBoxなど)は、 IDText(TextBox) passText(TextBox) OK(Button) resultText(TextBox) です! わかる方お願いします。 質問があれば答えます。

  • POSTリクエストの投げ方

    ASP.NET(c sharp)、.netフレームワーク2.0環境です。 認証(ベーシック認証)付きのREST APIを使いたいのですが、 リクエストの投げ方が理解できず困っています。 URLを指定してリクエストを投げると動くものなのですが…。 使い方としては、 ・POSTリクエストを使用 ・"item"をキーにして、対象になるURLの配列を指定 とのことです。 { "item" : [ "http://www.yahoo.co.jp/test1.jpg", "http://www.google.co.jp/test2.jpg" ] } ↑サンプルとして載っていました 以下の通り作ってみましたが、うまく動きません。 URLの配列指定がうまく出来ていないのではないかと思うのですが、 方法を教えていただけないでしょうか。 宜しくお願いします。 //HttpWebRequestの作成 WebRequest webreq = WebRequest.Create("https://api.test.com"); webreq.Method = "POST"; //認証の設定 webreq.Credentials = new System.Net.NetworkCredential("test@test.com", "testpass"); //POSTするデータ string postData = "item=http://www.yahoo.co.jp/test1.jpg"; byte[] byteArray = Encoding.UTF8.GetBytes(postData); webreq.ContentType = "application/json"; webreq.ContentLength = byteArray.Length; Stream dataStream = webreq.GetRequestStream(); dataStream.Write(byteArray, 0, byteArray.Length); WebResponse response = webreq.GetResponse(); dataStream = response.GetResponseStream(); StreamReader reader = new StreamReader(dataStream); string responseFromServer = reader.ReadToEnd(); reader.Close(); dataStream.Close(); response.Close();

専門家に質問してみよう