0

代码如下,当我点击页面时:

http://ryan.local.testmode.com/timecrunch/bctimepost.ashx?project=2593059&person=2831215&date=04/16/2009&hours=2.5&case=555

它只是有点挂起,加载条永远缓慢移动,直到我停下来,我忘了做点什么吗?我不知道哪行代码用于实际“提交”请求......

注意:用户名/密码和 [公司名称] 是共享代码的占位符,并在我的运行代码中包含正确的值

using System;
using System.Web;
using System.Xml;
using System.Net;
using System.IO;

public class bctimepost : IHttpHandler {

    public void ProcessRequest(HttpContext context)
    {

        string project_id = context.Request.QueryString["project"];
        string person_id = context.Request.QueryString["person"];
        string post_date = context.Request.QueryString["date"];
        string post_hours = context.Request.QueryString["hours"];
        string case_num = context.Request.QueryString["case"];

        HttpWebRequest objRequest = (HttpWebRequest)WebRequest.Create("https://[company name].updatelog.com/projects/" + project_id + "/time_entries.xml");

        objRequest.Method = "POST";
        objRequest.ContentType = "application/xml";
        objRequest.Accept = "application/xml";

        string creds = "username:password";
        byte[] encData_byte = new byte[creds.Length];
        encData_byte = System.Text.Encoding.UTF8.GetBytes(creds);
        string encodedData = Convert.ToBase64String(encData_byte);

        objRequest.Headers.Add("Authorization", "Basic " + encodedData);

        XmlWriterSettings settings = new XmlWriterSettings();
        settings.Indent = true;
        settings.IndentChars = ("    ");

        using (XmlWriter writer = XmlWriter.Create(objRequest.GetRequestStream(), settings))
        {
            writer.WriteStartElement("time-entry");
            writer.WriteElementString("person-id", person_id);
            writer.WriteElementString("date", post_date);
            writer.WriteElementString("hours", post_hours);
            writer.WriteElementString("description", "Worked on Case #" + case_num);
            writer.WriteEndElement();
        }

        HttpWebResponse myHttpWebResponse = (HttpWebResponse)objRequest.GetResponse();

        context.Response.Write(myHttpWebResponse.StatusCode);

    }




    public bool IsReusable {
        get {
            return false;
        }
    }

}
4

2 回答 2

3

我认为是 XmlWriter 不会自动关闭 GetRequestStream() 返回的流。添加:

settings.CloseOutput = true;

在创建 XmlWriter 之前看看是否有帮助。

于 2009-04-17T19:43:55.623 回答
0

作为旁注,您应该能够替换它:

string creds = "username:password";
byte[] encData_byte = new byte[creds.Length];
encData_byte = System.Text.Encoding.UTF8.GetBytes(creds);
string encodedData = Convert.ToBase64String(encData_byte);

objRequest.Headers.Add("Authorization", "Basic " + encodedData);

和:

objRequest.Credentials = new NetworkCredential("username", "password");
于 2009-04-17T20:28:01.040 回答