简体   繁体   English

idHTTP.Post错误HTTP / 1.1 401

[英]idHTTP.Post Error HTTP/1.1 401

I am trying to access the idHTTP Delphi in a json server without success. 我试图访问json服务器中的idHTTP Delphi失败。 I've tried all the alternatives and always got the same error: "HTTP / 1.1 401 Unauthorized". 我尝试了所有替代方法,并始终遇到相同的错误:“ HTTP / 1.1 401未经授权”。

JSON format for testing: 用于测试的JSON格式:

{"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”:{“ method”:“ POST”,“ header”:“ access_token:55b3ce85b47629eeee778c0f0c9be450f1b1bc84cc377975f2d3d0d3808a4636”,“ content”:“ name=TEST&email=teste@uol.com&phone=1147329+909=909 55&province = Test&notificationDisabled = True&city = Sao + Paulo&state = SP&country = Brasil&postalCode = 05567210&cpfCnpj = 11111111111&personType = FISICA“}}

Url for testing: 测试网址:

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

Procedure for testing: 测试步骤:

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;

The same format sent in PHP works perfectly, but with idHTTP returns the error: "HTTP / 1.1 401 Unauthorized". 用PHP发送的相同格式可以很好地工作,但是使用idHTTP返回错误:“ HTTP / 1.1 401 Unauthorized”。

PHP works perfectly 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;

?>

I am trying to access the idHTTP Delphi in a json server without success. 我试图访问json服务器中的idHTTP Delphi失败。

You are not posting the JSON data correctly. 您没有正确发布JSON数据。 You cannot use a TStringList , as that version of TIdHTTP.Post() is meant for posting HTML webforms, which you are not posting. 您不能使用TStringList ,因为该版本的TIdHTTP.Post()用于发布未发布的HTML TIdHTTP.Post() You need to post the JSON data using a TStream instead, eg: 您需要使用TStream来发布JSON数据,例如:

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;

I've tried all the alternatives and always got the same error: "HTTP / 1.1 401 Unauthorized". 我尝试了所有替代方法,并始终遇到相同的错误:“ HTTP / 1.1 401未经授权”。

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. 但是,在这种情况下,服务器的响应中不存在提供挑战信息的WWW-Authenticate标头,这明显违反了HTTP协议规范。

The same format sent in PHP works perfectly 用PHP发送的相同格式效果很好

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


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 POST ing an HTML webform containing name=value pairs in application/x-www-form-urlencoded format. 更新 :根据你的PHP代码,我现在可以看到你的Delphi代码试图POST JSON格式的字符串,但你的PHP代码是不是POST荷兰国际集团包含HTML的网页表单name=value对在application/x-www-form-urlencoded格式。 There is no JSON involved in the request at all. 该请求中根本不涉及JSON。 Only the response is using JSON. 仅响应使用JSON。

Looking back at it now, the PHP code is acting on simply arrays, not on real JSON. 现在回头看,PHP代码仅作用于数组,而不作用于真实的JSON。 I think you got confused between the two, because the representation of the array data looks like JSON but it is actually not. 我认为您对两者感到困惑,因为数组数据的表示形式看起来像JSON,但实际上不是。 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. 如果您阅读PHP文档,则http_build_query()仅返回代表HTTP url查询字符串的字符串,然后stream_context_create()基于HTTP上下文选项数组创建流,其中将查询字符串设置为content选项,然后file_get_contents()将基于这些选项发送请求-在这种情况下为HTTP POST请求,带有access_token标头和查询字符串作为消息正文。 Since no Content-Type header is being specified, it defaults to application/x-www-form-urlencoded . 由于未指定Content-Type标头,因此默认为application/x-www-form-urlencoded

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. POSTapplication/x-www-form-urlencoded与要求TIdHTTP ,你实际上是在正确的轨道上使用TStringListTIdHTTP.Post()但你填充TStringList有一种错误的数据,而你不发送包含您的身份验证凭据的access_token标头。

The following Delphi code works when I test it: 当我对其进行测试时,以下Delphi代码可以运行:

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;

Response received: 收到回复:

{"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 {“对象”:“客户”,“ id”:“ cus_B5HmHFQSMZKD”,“名称”:“ TEST”,“电子邮件”:“ teste@uol.com”,“公司”:null,“电话”:“ 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,” 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":tru _B5HmHFQSMZKD“,” enabled“: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”:“ notification”,“ id”:“ not_LX1vanmAsBy9”,“ customer” :“ 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“:tru e,"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}]}} e,“ event”:“ PAYMENT_CREATED”,“ scheduleOffset”:0,“已删除”:false},{“ object”:“ notification”,“ id”:“ not_b6NUt9qYZrM2”,“ customer”:“ cus_B5HmHFQSMZKD”,“启用“:true,” emailEnabledForProvider“:false,” smsEnabledForProvider“:false,” emailEnabledForCustomer“:true,” smsEnabledForCustomer“:true,” event“:” PAYMENT_UPDATED“,” scheduleOffset“:0,” deleted“:false},{ “对象”:“通知”,“ id”:“ not_Z4e4SHdXsJaA”,“客户”:“ cus_B5HmHFQSMZKD”,“启用”:true,“ emailEnabledForProvider”:false,“ smsEnabledForProvider”:false,“ emailEnabledForCustomer”:true,“ smsEnabledForCustomer “:true,”事件“:” SEND_LINHA_DIGITAVEL“,” scheduleOffset“:0,”已删除“:false}]}}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM