ปัญหาที่พบบ่อยๆกับ WebRequest, WebResponse

ในโลกของ .NET คลาสที่ใช้บ่อยๆเวลาจะทำ Client/Server อยู่ใน namespace System.Net – ทีนี้เนื่องจากต้องมีการรับ/ส่งข้อมูลระหว่างกัน ทำให้อาจเจอปัญหาประเภทเข็มขัดสั้น ดังต่อไปนี้

1. Unable to connect to the remote server

Exception นี้จะเจอตอนพยายามจะ get response จากอีกฝั่ง แต่ไม่มีสัญญาณตอบรับจากเลขหมายที่ท่านเรียก…

Exception1

Checkpoints

  • ใส่ proxy ให้กับ request หรือยัง?
    HttpWebRequest request = WebRequest.Create("http://targetUrl" as HttpWebRequest;
    request.Proxy = WebRequest.DefaultWebProxy;
    
  • ค่า proxy ถูกหรือเปล่า? ถ้าเราใช้ proxy แบบข้างต้น ค่าที่ได้จะมาจาก OS ซึ่งไปเอาจาก Internet Explorer อีกที

2. The remote server returned an error: (401) Unauthorized

เจอเมื่อพยายามจะ get response เช่นเดียวกันกับปัญหาข้างบน

Exception2

Checkpoints

  • ตรวจสอบว่าใส่ Credential ให้กับ request หรือยัง?
    HttpWebRequest request = WebRequest.Create("http://targetUrl" as HttpWebRequest;
    request.Credentials = new NetworkCredential(“UserName”, “Password”);
    

3. The request was aborted: The request was canceled.

เจอเมื่อพยายาม close StreamWriter สังเกตว่า InnerException บอกว่าข้อมูลยังไม่ได้เขียนจึงปิดไม่ได้

Exception4

Checkpoints

  • ลอง Flush Stream ดู (StreamWriter.Flush())
  • ตั้งเวลา TimeOut ให้กับ request
    HttpWebRequest request = WebRequest.Create("http://targetUrl") as HttpWebRequest;
    request.Timeout = System.Threading.Timeout.Infinite;
    

4. Bytes to be written to the stream exceed the Content-Length bytes size specified.

บางครั้งเป็นเหตุการณ์ต่อเนื่องจากปัญหาที่แล้วครับ – ที่ request ไม่สำเร็จเพราะ content-length ของจริงกับที่เราบอกไปขนาดไม่เท่ากัน

Exception3

Checkpoints

  • ทำตาม checkpoints ข้อสาม
  • เช็ค Encoding ของ StreamWriter – ลองเปลี่ยนเป็น ASCII ดู

ปล. ช่วงนี้ออกนอกบ้านไม่ปลอดภัย ปิดไฟใส่กลอน เข้ามุ้งนอนแต่หัววัน ^-^
ปล.2. ขอบคุณทุกท่านที่มาลงชื่อรออ่านเรื่องของนายสมชาย โปรแกรมนี้เขียนเป็น case study ของตอนต่อไป รอชม ไวไว มาม่า กุ๊งกิ๊ง ครับผม

One Comment

  1. baLLe
    Posted April 14, 2009 at 12:59 pm | #

    โอ๊วว มีการเตรียมตัว เยี่ยมเลยครับ :)

Post a Comment

Your email is never published nor shared. Required fields are marked *

*
*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>