我正在使用Microsoft的HttpClient
向第三方RESTful服务发出请求。除了这个例子之外,它完美无缺(并且非常容易实现)。以下是提供商对错误期间发生的情况的细分:
“POST到组资源的工作方式是,当它完成时,它会将HTTP 302重定向到组实例资源。似乎正在发生什么是您的HTTP客户端正在向POST发送正确的身份验证信息,这会创建组资源,但是当它处理HTTP 302请求的GET时,它不会发送正确的凭据并且正在获取401响应。你能检查你的客户端库并确保它在重定向上正确发送HTTP身份验证参数吗?“
这是我的POST代码:
HttpClient http = new HttpClient(BASE_URL);
http.TransportSettings.Credentials = new NetworkCredential(ACCOUNT_SID,
ACCOUNT_TOKEN);
HttpResponseMessage httpResponse = http.Post(groupUri, "application/xml",
HttpContent.Create(xml.ToString()));
result = httpResponse.Content.ReadAsString();
这让我想到了我的问题;如何使用HttpClient
类获取要在此GET重定向上发送的身份验证参数?
答案 0 :(得分:1)
我遇到了类似的问题,最后我添加了一个带有 WebBrowser控件的表单。
无需拨打form.Show()
我可以告诉他导航到URL,点击按钮等等。以下是控制该表单的类:
public class Nav
{
FormNav formNav = new FormNav();
public string Source
{
get
{
mshtml.HTMLDocument doc = (mshtml.HTMLDocument)formNav.webBrowser.Document.DomDocument;
return doc.documentElement.innerHTML;
}
}
public void GoTo(string Url)
{
formNav.webBrowser.Navigate(Url);
Wait();
}
public void Fill(string Field, string Value)
{
formNav.webBrowser.Document.GetElementById(Field).InnerText = Value;
}
public void Click(string Element)
{
formNav.webBrowser.Document.GetElementById(Element).InvokeMember("click");
Wait();
Application.DoEvents();
}
public void Wait()
{
const int TIMEOUT = 30;
formNav.Ready = false;
DateTime start = DateTime.Now;
TimeSpan span;
do
{
Application.DoEvents();
span = DateTime.Now.Subtract(start);
} while (!formNav.Ready && span.Seconds < TIMEOUT);
}
public void Dispose()
{
formNav.Dispose();
}
}
这是表单的代码(需要一些额外的代码来禁用单击声音)。
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;
public partial class FormNav : Form
{
private const int FEATURE_DISABLE_NAVIGATION_SOUNDS = 21;
private const int SET_FEATURE_ON_THREAD = 0x00000001;
private const int SET_FEATURE_ON_PROCESS = 0x00000002;
private const int SET_FEATURE_IN_REGISTRY = 0x00000004;
private const int SET_FEATURE_ON_THREAD_LOCALMACHINE = 0x00000008;
private const int SET_FEATURE_ON_THREAD_INTRANET = 0x00000010;
private const int SET_FEATURE_ON_THREAD_TRUSTED = 0x00000020;
private const int SET_FEATURE_ON_THREAD_INTERNET = 0x00000040;
private const int SET_FEATURE_ON_THREAD_RESTRICTED = 0x00000080;
[DllImport("urlmon.dll")]
[PreserveSig]
[return: MarshalAs(UnmanagedType.Error)]
static extern int CoInternetSetFeatureEnabled(
int FeactureEntry,
[MarshalAs(UnmanagedType.U4)] int dwFlags,
bool fEnable);
public bool Ready;
public FormNav()
{
InitializeComponent();
Ready = true;
int feature = FEATURE_DISABLE_NAVIGATION_SOUNDS;
CoInternetSetFeatureEnabled(feature, SET_FEATURE_ON_PROCESS, true);
}
private void webBrowser_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
Ready = true;
}
}
如果需要源代码,则应添加 Microsoft Html对象 COM库。