// Get

HttpWebRequest httpWebRequest = WebRequest.CreateHttp(url);
httpWebRequest.Method = HttpMethod.Get.Method;

httpWebRequest.Headers = new WebHeaderCollection();
httpWebRequest.Headers["header"] = header;


    using (var response = await httpWebRequest.GetResponseAsync()) {

        using (Stream stream = response.GetResponseStream()) {

            using (StreamReader reader = new StreamReader(stream)) {

                // Read the content.
                result = reader.ReadToEnd();
            }
        }
    }


 

 

// Post

 

try {

    HttpWebRequest httpWebRequest = WebRequest.CreateHttp(url);
    httpWebRequest.Method = HttpMethod.Post.Method;

    using (var requestStream = await httpWebRequest.GetRequestStreamAsync()) {

        byte[] buffer = Encoding.UTF8.GetBytes(str);
        await requestStream.WriteAsync(buffer, 0, buffer.Length);
    }

    using (var response = await httpWebRequest.GetResponseAsync()) {

        using (Stream stream = response.GetResponseStream()) {

            using (StreamReader reader = new StreamReader(stream)) {

                // Read the content.
                result = reader.ReadToEnd();
            }
        }
     }

}
catch (WebException ex)

{

    var response = ex.Response as HttpWebResponse;

    Debug.WriteLine(ex.Status);
}

 

參考資料:

http://jjnnykimo.pixnet.net/blog/post/25277457-c%23,-%E4%BD%BF%E7%94%A8-httpwebrequest-%E5%90%91%E7%B6%B2%E7%AB%99%E6%8F%90%E4%BA%A4%E8%B3%87%E6%96%99

 

http://coding.anyun.tw/2012/02/22/using-httpwebrequest-post-data/

arrow
arrow
    全站熱搜

    小賢 發表在 痞客邦 留言(0) 人氣()