idHTTP.Post错误HTTP/1.1 401 [英] idHTTP.Post Error HTTP/1.1 401

查看:110
本文介绍了idHTTP.Post错误HTTP/1.1 401的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在json服务器中访问idHTTP Delphi失败.我尝试了所有替代方法,并始终遇到相同的错误:"HTTP/1.1 401未经授权".

I am trying to access the idHTTP Delphi in a json server without success. I've tried all the alternatives and always got the same error: "HTTP / 1.1 401 Unauthorized".

用于测试的JSON格式:

JSON format for testing:

{"http":{"method":"POST","header":"access_token:55b3ce85b47629eeee778c0f0c9be450f1b1bc84cc377975f2d3d0d3808a4636","content":"name = TEST& email = teste @ phone = 001&mobile; 21111992329909& address = Rua + Jose + Ricardo& addressNumber = 55& provin = Test& notificationDisabled = True& city = Sao + Paulo& state = SP& country =巴西& postalCode = 05567210& cpfCnpj = 11111111111S&ICA;"}}

{"http":{"method":"POST","header":"access_token:55b3ce85b47629eeee778c0f0c9be450f1b1bc84cc377975f2d3d0d3808a4636", "content":"name=TEST&email=teste@uol.com&phone=1147001211&mobilePhone=11992329909&address=Rua+Jose+Ricardo &addressNumber=55&province=Test&notificationDisabled=True&city=Sao+Paulo&state=SP&country=Brasil&postalCode=05567210 &cpfCnpj=11111111111&personType=FISICA"}}

测试网址:

http://homolog.asaas.com/api/v2/customers

测试步骤:

procedure TForm4.Button2Click(Sender: TObject);
var
 sResponse: string;
 EnvStr : TStringList;
begin
 EnvStr := TStringList.Create;
 EnvStr.AddStrings(Memo.Lines);
 try
  idHTTP.Request.ContentType := 'application/json';
  idHTTP.Request.Method:='POST';
  idHTTP.Request.AcceptCharSet := 'utf-8';
  try
   sResponse := idHTTP.Post(EditURL.Text,EnvStr);
  except
   on E: Exception do
    ShowMessage('Error on request: '#13#10 + e.Message);
  end;
 finally
  MemoRet.Lines.Clear;
  MemoRet.Lines.add(sResponse);
 end;
end;

用PHP发送的相同格式可以很好地工作,但是使用idHTTP会返回错误:"HTTP/1.1 401未经授权".

The same format sent in PHP works perfectly, but with idHTTP returns the error: "HTTP / 1.1 401 Unauthorized".

PHP完美运行

<?php
 $api_url = "http://homolog.asaas.com/api/v2";   
 $api_key = "55b3ce85b47629eeee778c0f0c9be450f1b1bc84cc377975f2d3d0d3808a4636";
 $url_cus = $api_url."/customers";
 $param = array(
'name' => utf8_encode('Test'),
'email' => 'test@uol.com.br',
'phone' => '1147001211',
'mobilePhone' => '11992329909',
'address' => utf8_encode('Rua Jose Ricardo'),
'addressNumber' => '55',
'province' => 'Test',
'notificationDisabled' => 'True',
'city' => 'Sao Paulo',
'state' =>'SP',
'country' => 'Brasil',
'postalCode' => '05567210',
'cpfCnpj' => '11111111111',
'personType' => 'FISICA'
  );
 $req = http_build_query($param);
 $ctx = stream_context_create(
 array(
       "http" => array(
       "method" => "POST",
       "header" => "access_token: $api_key",
       "content" => $req
        )
      )
     );

 $res = file_get_contents($url_cus, true, $ctx);

 //PHP Object
 $obj = json_decode($res);

 //get id of register 
 $id=utf8_decode("$obj->id");

 // return result
 // return $id;

?>

推荐答案

我试图访问json服务器中的idHTTP Delphi失败.

I am trying to access the idHTTP Delphi in a json server without success.

您没有正确发布JSON数据.您不能使用 TStringList ,因为该版本的 TIdHTTP.Post()是用于发布HTML Webforms的,而不是您要发布的Webform.您需要改为使用 TStream 发布JSON数据,例如:

You are not posting the JSON data correctly. You cannot use a TStringList, as that version of TIdHTTP.Post() is meant for posting HTML webforms, which you are not posting. You need to post the JSON data using a TStream instead, eg:

procedure TForm4.Button2Click(Sender: TObject);
var
 sResponse: string;
 EnvStr : TStringStream;
begin
 EnvStr := TStringStream.Create(Memo.Text, TEncoding.UTF8);
 try
  idHTTP.Request.ContentType := 'application/json';
  try
   sResponse := idHTTP.Post(EditURL.Text, EnvStr);
  except
    on E: Exception do
      ShowMessage('Error on request: '#13#10 + e.Message);
  end;
finally
  EnvStr.Free;
  MemoRet.Text := sResponse;
end;

我尝试了所有替代方法,并始终遇到相同的错误:"HTTP/1.1 401未经授权".

I've tried all the alternatives and always got the same error: "HTTP / 1.1 401 Unauthorized".

通常,这表示服务器正在询问您未提供的身份验证凭据.但是,在这种情况下,服务器的响应中没有提供任何 WWW-Authenticate 标头来提供质询信息,这明显违反了HTTP协议规范.

Usually that means the server is asking for authentication credentials, which you are not providing. However, in this situation, there is no WWW-Authenticate header present in the server's response to provide challenge information, which is in clear violation of the HTTP protocol spec.

用PHP发送的相同格式效果很好

The same format sent in PHP works perfectly

然后,您需要使用数据包嗅探器(例如Wireshark)来捕获由PHP和 TIdHTTP 生成的HTTP请求,然后对它们进行比较以查找任何差异,然后可以将其编码为TIdHTTP (根据需要).

Then you need to use a packet sniffer, such as Wireshark, to capture the HTTP requests being generated by PHP and TIdHTTP and then compare them for any differences that you can then code into TIdHTTP as needed.

更新:根据您的PHP代码,我现在可以看到您的Delphi代码正在尝试 POST JSON格式的字符串,但是您的PHP代码却是 POST 生成一个HTML Web表单,其中包含 application/x-www-form-urlencoded 格式的 name = value 对.该请求中根本不涉及JSON.仅响应使用JSON.

Update: based on your PHP code, I can now see that your Delphi code is trying to POST a JSON formatted string, but your PHP code is instead POSTing an HTML webform containing name=value pairs in application/x-www-form-urlencoded format. There is no JSON involved in the request at all. Only the response is using JSON.

现在回头看一下,PHP代码仅作用于数组,而不作用于实际的JSON.我认为您对两者感到困惑,因为数组数据的表示形式看起来像JSON,但实际上不是.如果您阅读PHP文档,请 http_build_query()仅返回代表HTTP网址查询字符串的字符串,然后 stream_context_create() 正在基于

Looking back at it now, the PHP code is acting on simply arrays, not on real JSON. I think you got confused between the two, because the representation of the array data looks like JSON but it is actually not. If you read the PHP documentation, http_build_query() simply returns a string representing an HTTP url query string, and then stream_context_create() is creating a stream based on an array of HTTP context options, where the query string is set as the content option, and then file_get_contents() is sending a request based on those options - in this case an HTTP POST request with an access_token header and the query string as the message body. Since no Content-Type header is being specified, it defaults to application/x-www-form-urlencoded.

要通过 TIdHTTP application/x-www-form-urlencoded 请求进行 POST ,实际上,通过使用使用 TIdHTTP.Post() TStringList ,但是您使用错误的数据类型填充了 TStringList > access_token 标头,其中包含您的身份验证凭据.

To POST an application/x-www-form-urlencoded request with TIdHTTP, you were actually on the right track by using a TStringList with TIdHTTP.Post(), but you were populating the TStringList with the wrong kind of data, and you were not sending the access_token header containing your authentication credentials.

下面的Delphi代码在我测试时有效:

The following Delphi code works when I test it:

procedure TForm4.Button2Click(Sender: TObject);
var
  sResponse: string;
  EnvStr : TStringList;
begin
  EnvStr := TStringList.Create;
  try
    EnvStr.Add('name=TEST');
    EnvStr.Add('email=teste@uol.com');
    EnvStr.Add('phone=1147001211');
    EnvStr.Add('mobilePhone=11992329909');
    EnvStr.Add('address=Rua Jose Ricardo ');
    EnvStr.Add('addressNumber=55');
    EnvStr.Add('province=Test');
    EnvStr.Add('notificationDisabled=True');
    EnvStr.Add('city=Sao Paulo');
    EnvStr.Add('state=SP');
    EnvStr.Add('country=Brasil');
    EnvStr.Add('postalCode=05567210 ');
    EnvStr.Add('cpfCnpj=11111111111');
    EnvStr.Add('personType=FISICA');

    Http.Request.CustomHeaders.Values['access_token'] := '55b3ce85b47629eeee778c0f0c9be450f1b1bc84cc377975f2d3d0d3808a4636';
    try
      sResponse := idHTTP.Post(EditURL.Text, EnvStr);
    except
      on E: Exception do
        ShowMessage('Error on request: '#13#10 + e.Message);
    end;
  finally
    EnvStr.Free;
    MemoRet.Text := sResponse;
  end;
end;

已收到回复:

{对象":客户","id":"cus_B5HmHFQSMZKD",名称":"TEST",电子邮件":"teste@uol.com",公司":空,电话":"1147001211","mobilePhone":"11992329909","address":"Rua Jose Ricardo","addressNumber":"55","complement":null,"province":"Test","postalCode":"05567210," cpfCnpj:" 11111111111," personType:" FISICA,"已删除:false," notificationDisabled:true," city:null," state:" null," country:"巴西," foreignCustomer:false,"订阅:{" object:" list," hasMore:false," limit:100," offset:0," data:[]},"支付":{"object":"list","hasMore":false,"limit":100,"offset":0,"data":[]},"notifications":{"object":"list","hasMore:false," limit:100," offset:0," data:[{" object:" notification," id:" not_oZV4SlDvdjHf," customer:" cus_B5HmHFQSMZKD," enabled":true,"emailEnabledForProvider":true,"smsEnabledForProvider":false,"emailEnabledForCustomer":true,"smsEnabledForCustomer":true,"event":"PAYMENT_RECEIVED","scheduleOffset":0,"deleted":false},{对象":通知","id":"not_xNHXDZb4QHqP",客户":"cus_B5HmHFQSMZKD,"已启用:true," emailEnabledForProvider:true," smsEnabledForProvider:false," emailEnabledForCustomer:true," smsEnabledForCustomer:true," event:" PAYMENT_OVERDUE," scheduleOffset:0,"已删除":false},{"object":"notification","id":"not_yt4BTyQsaRM1","customer":"cus_B5HmHFQSMZKD","enabled":true,"emailEnabledForProvider":false,"smsEnabledForProvider":false,"emailEnabledForCustomer":true,"smsEnabledForCustomer":true,事件":"PAYMENT_DUEDATE_WARNING","scheduleOffset":10,已删除":false},{"object":通知","id":"not_LX1vanmAsBy9",客户":"cus_B5HmHFQSMZKD",启用":true,"emailEnabledForProvider":false,"smsEnabledForProvider":false,"emailEnabledForCustomer":true,"smsEnabledForCustomer":true,事件":"PAYMENT_DUEDATE_WARNING","scheduleOffset":0,已删除:false},{" object:"通知," id:" not_AyYUHDExa5Zk,"客户:" cus_B5HmHFQSMZKD," enabled:true," emailEnabledForProvider:false," smsEnabledForProvider:false,"emailEnabledForCustomer:true," smsEnabledForCustomer:true,事件":"PAYMENT_CREATED","scheduleOffset":0,已删除":false},{对象":通知","id":"not_b6NUt9qYZrM2",客户":"cus_B5HmHFQSMZKD",已启用:true," emailEnabledForProvider:false," smsEnabledForProvider:false," emailEnabledForCustomer:true," smsEnabledForCustomer:true,"事件:" PAYMENT_UPDATED," scheduleOffset:0,"已删除:false},{对象":通知","id":"not_Z4e4SHdXsJaA",客户":"cus_B5HmHFQSMZKD",启用":true,"emailEnabledForProvider":false,"smsEnabledForProvider":false,"emailEnabledForCustomer":true,"smsEnabledForCustomer:true,"事件:" SEND_LINHA_DIGITAVEL," scheduleOffset:0,"已删除:false}]}}

{"object":"customer","id":"cus_B5HmHFQSMZKD","name":"TEST","email":"teste@uol.com","company":null,"phone":"1147001211","mobilePhone":"11992329909","address":"Rua Jose Ricardo","addressNumber":"55","complement":null,"province":"Test","postalCode":"05567210","cpfCnpj":"11111111111","personType":"FISICA","deleted":false,"notificationDisabled":true,"city":null,"state":"null","country":"Brasil","foreignCustomer":false,"subscriptions":{"object":"list","hasMore":false,"limit":100,"offset":0,"data":[]},"payments":{"object":"list","hasMore":false,"limit":100,"offset":0,"data":[]},"notifications":{"object":"list","hasMore":false,"limit":100,"offset":0,"data":[{"object":"notification","id":"not_oZV4SlDvdjHf","customer":"cus_B5HmHFQSMZKD","enabled":true,"emailEnabledForProvider":true,"smsEnabledForProvider":false,"emailEnabledForCustomer":true,"smsEnabledForCustomer":true,"event":"PAYMENT_RECEIVED","scheduleOffset":0,"deleted":false},{"object":"notification","id":"not_xNHXDZb4QHqP","customer":"cus_B5HmHFQSMZKD","enabled":true,"emailEnabledForProvider":true,"smsEnabledForProvider":false,"emailEnabledForCustomer":true,"smsEnabledForCustomer":true,"event":"PAYMENT_OVERDUE","scheduleOffset":0,"deleted":false},{"object":"notification","id":"not_yt4BTyQsaRM1","customer":"cus_B5HmHFQSMZKD","enabled":true,"emailEnabledForProvider":false,"smsEnabledForProvider":false,"emailEnabledForCustomer":true,"smsEnabledForCustomer":true,"event":"PAYMENT_DUEDATE_WARNING","scheduleOffset":10,"deleted":false},{"object":"notification","id":"not_LX1vanmAsBy9","customer":"cus_B5HmHFQSMZKD","enabled":true,"emailEnabledForProvider":false,"smsEnabledForProvider":false,"emailEnabledForCustomer":true,"smsEnabledForCustomer":true,"event":"PAYMENT_DUEDATE_WARNING","scheduleOffset":0,"deleted":false},{"object":"notification","id":"not_AyYUHDExa5Zk","customer":"cus_B5HmHFQSMZKD","enabled":true,"emailEnabledForProvider":false,"smsEnabledForProvider":false,"emailEnabledForCustomer":true,"smsEnabledForCustomer":true,"event":"PAYMENT_CREATED","scheduleOffset":0,"deleted":false},{"object":"notification","id":"not_b6NUt9qYZrM2","customer":"cus_B5HmHFQSMZKD","enabled":true,"emailEnabledForProvider":false,"smsEnabledForProvider":false,"emailEnabledForCustomer":true,"smsEnabledForCustomer":true,"event":"PAYMENT_UPDATED","scheduleOffset":0,"deleted":false},{"object":"notification","id":"not_Z4e4SHdXsJaA","customer":"cus_B5HmHFQSMZKD","enabled":true,"emailEnabledForProvider":false,"smsEnabledForProvider":false,"emailEnabledForCustomer":true,"smsEnabledForCustomer":true,"event":"SEND_LINHA_DIGITAVEL","scheduleOffset":0,"deleted":false}]}}

这篇关于idHTTP.Post错误HTTP/1.1 401的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆