我正在尝试将curl请求转换为c#请求,但它无法正常工作
卷曲请求
curl -X GET "http://www1.bloomingdales.com/shop/search?keyword=lace%2Btop"
上面的curl请求正常
C#request
public lib_check ()
{
string url_1 = "http://www1.bloomingdales.com/shop/search/Pageindex%2CProductsperpage/1%2C180?keyword=women%20tank%20top";
Console.Write (url+"request started");
var request = (HttpWebRequest)WebRequest.Create(url_1);
request.Method = WebRequestMethods.Http.Get;
var response = request.GetResponse();
using (var reader = new StreamReader(response.GetResponseStream()))
{
var json = reader.ReadToEnd ();
console.write( json);
}
}
但是上面的c#请求会抛出403禁止错误
如何修复c#请求并使请求工作以获得200响应?
答案 0 :(得分:0)
我猜它之所以被禁止,是因为你没有构建网站所期望的必要标题。您需要构建这些标头,并且可以在chrome中的开发人员工具中进行检查。请参阅下面的代码。
public T getUnique(){
T distinct = null;
int count = 0; // FIXME: move this initialization inside the i loop
for (int i=0; i<vals.length; i++){
distinct = vals[i];
for (int j = 0; j<vals.length; j++){
if (vals[j] == vals[i]){ // FIXME: use .equals() not ==
count++;
}
if (count == 1){ // FIXME: move this check outside the j loop
return distinct;
}
}
}
if (distinct == null){ //FIXME: no check needed, just throw it
throw new IllegalArgumentException();
}
return distinct; //FIXME: no valid return can reach this point
}
查看服务器所需的标头数量;尝试在开发工具处于活动状态时首先在浏览器中请求网址。
更新:如果由于超时问题而无法正常工作,最好以异步方式处理它。
string url_1 = @"http://www1.bloomingdales.com/shop/search/Pageindex%2CProductsperpage/1%2C180?keyword=women%20tank%20top";
var request = (HttpWebRequest)WebRequest.Create(url_1);
request.Method = "GET";
request.Accept = "text/html";
request.UserAgent = ".NET Framework Test Client"; // Some server prevent script like this so they validate some user-agents
request.MaximumAutomaticRedirections = int.MaxValue;
request.Timeout = 50000;
var response = request.GetResponse();
using (var reader = new StreamReader(response.GetResponseStream()))
{
var json = reader.ReadToEnd();
Console.Write(json);
}
我注意到结果不是json而是页面。可能是因为它不是API。根据需要调整代码,但裸骨已经存在。