PostRequest

From no name for this wiki
Jump to: navigation, search

Wie macht man mit .net 4 einen HTTP Postrequest?

Kleiner Wrapper:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Security;
using System.Net;
using System.IO;
 
 
 
public class PostReqest
{
 
    private IDictionary<string, string> parameters = new Dictionary<string, string>();
 
    public IDictionary<string, string> Parameters
    {
        get
        {
            return this.parameters;
        }
    }
 
 
    public string GetResponse(String url)
    {
        StringBuilder sb = new StringBuilder();
        IList<string> keys = new List<string>(parameters.Keys);
        for (int i = 0; i < keys.Count; i++)
        {
            string key = keys[i];
            string value = parameters[key];
 
            sb.Append(Uri.EscapeDataString(key));
            sb.Append("=");
            sb.Append(Uri.EscapeDataString(value));
 
            if (i != keys.Count - 1)
            {
                sb.Append("&");
            }
 
        }
        string txt = sb.ToString();
        byte[] data = UTF8Encoding.UTF8.GetBytes(txt);
 
        WebRequest myRequest = WebRequest.Create(url);
        myRequest.Method = "POST";
        myRequest.ContentType = "application/x-www-form-urlencoded";
        myRequest.ContentLength = data.Length;
        Stream newStream = myRequest.GetRequestStream();
 
        // Send the data.
        newStream.Write(data, 0, data.Length);
        newStream.Close();
 
        WebResponse webResp = myRequest.GetResponse();
 
        Stream receiveStream = webResp.GetResponseStream();
 
        // Pipes the stream to a higher level stream reader with the required encoding format. 
        StreamReader readStream = new StreamReader(receiveStream, Encoding.UTF8);
        string resptext = readStream.ReadToEnd();
 
        return resptext;
    }
}

Angewandt:

PostReqest pr = new PostReqest();
pr.Parameters.Add("param1", "http://aff.aff.de");
pr.Parameters.Add("param2", "http://aff.aff.de");
string txt = pr.GetResponse("http://www.claude-glauser.ch/php/printparameters.php");