使用 HttpWebRequest 轻松实现站外提交

来源:互联网 发布:迷宫的十字路口 知乎 编辑:程序博客网 时间:2024/06/06 21:19

HttpWebRequest post=(HttpWebRequest)WebRequest.Create(targetUrl);
        post.Method = "post";
        post.ContentType = "application/x-www-form-urlencoded; charset=utf-8";
        String postData = "";
        if(url!=null)
            postData += "url=" + HttpUtility.UrlEncode(url);
        if (blog_name != null)
            postData += "&blog_name=" + HttpUtility.UrlEncode(blog_name);
        if (title != null)
            postData += "&title=" + HttpUtility.UrlEncode(title);
        else
            postData += "&title=" + HttpUtility.UrlEncode(url);
        if (excerpt != null)
            postData += "&excerpt=" + HttpUtility.UrlEncode(excerpt);
        UTF8Encoding encoding = new UTF8Encoding();
        byte[] buff = encoding.GetBytes(postData);
        post.ContentLength = buff.Length;
        Stream stream = post.GetRequestStream();
        stream.Write(buff,0,buff.Length);
        stream.Flush();
        stream.Close(); 

        post.BeginGetResponse(null,null);
        HttpWebResponse rep = (HttpWebResponse)post.GetResponse();
        Stream repStream = rep.GetResponseStream();
        Encoding enc = Encoding.GetEncoding(rep.CharacterSet);
        StreamReader reader = new StreamReader(repStream,enc);
        String content = reader.ReadToEnd();

原创粉丝点击