2010-08-19 3 views
0

Я пытаюсь написать php-скрипт для отправки HTTP-запроса на URL-адрес. Кажется, он не проходит, потому что сервер не получает его. Может ли кто-нибудь помочь?php socket http post не работает

<?php 
function postXMLToURL ($server, $path, $xmlDocument) { 
    $xmlSource = $xmlDocument; 
    $contentLength = strlen($xmlSource); 
    //$fp = fsockopen($server, 80); 
    $fp = fsockopen($server,8080); 
    fwrite($fp, "POST $path HTTP/1.0\r\n"); 
    fwrite($fp, "Host: $server\r\n"); 
    fwrite($fp, "Content-Type: application/xml\r\n"); 
    fwrite($fp, "Content-Length: $contentLength\r\n"); 
    fwrite($fp, "Connection: close\r\n"); 
    fwrite($fp, "\r\n"); // all headers sent 
    fwrite($fp, $xmlSource); 
    $result = ''; 
    while (!feof($fp)) { 
     $result .= fgets($fp, 128); 
    }  
    return $result; 
} 

function getBody ($httpResponse) { 
    $lines = preg_split('/(\r\n|\r|\n)/', $httpResponse); 
    $responseBody = ''; 
    $lineCount = count($lines); 
    for ($i = 0; $i < $lineCount; $i++) { 
     if ($lines[$i] == '') { 
      break; 
     } 
    } 
    for ($j = $i + 1; $j < $lineCount; $j++) { 
     $responseBody .= $lines[$j] . "\n"; 
    } 
    return $responseBody; 
} 

$xmlDocument = new DomDocument($final_xml); //final_xml is my xml in a string 

$result = postXMLtoURL("localhost", "/resources", $xmlDocument); 
$responseBody = getBody($result); 

$resultDocument = new DOMDocument(); 
$resultDocument->loadXML($responseBody); 

header('Content-Type: application/xml'); 
echo $resultDocument->saveXML(); 
} 
?> 
+3

Есть ли причина, по которой вы используете сокеты, а не cURL? http://php.net/manual/en/book.curl.php –

+0

Попробуйте отправить все заголовки через один вызов 'fwrite' ... – ircmaxell

+0

Используемый мной сервер не имеет cURL. Есть ли большая разница между этим и использованием сокетов? Я попытался отправить все заголовки одним вызовом fwrite, без изменений. – John

ответ

0

Вам нужно научиться помогать себе.

В коде отсутствует обнаружение ошибок - вы должны хотя бы проверить, что fp действителен после вызова fsockopen, так как предпочтение должно быть выполнено с ошибкой LOT more.

Кроме того, возьмите что-нибудь вроде wirehark и посмотрите, какие пакеты генерирует ваш код.

C.

0

Вы можете использовать stream_context_create(); Как только я написал php-класс, вы wecome для его использования.

<?php 

class HTTPRequest 
{ 
    protected $url; 

    protected $method;  

    protected $headers; 

    protected $data = ""; 

    protected $useragent = "Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0)"; 


    public function __construct(){} 


    public function setHeaders($headers) 
    { 
     if(is_array($headers)) 
     { 
      $this->headers = $headers; 
      return true;    
     } 
     return false; 

    } 

    public function get($request) 
    { 
     if(!$this->headers) 
     { 
      throw new Exception("Please set Headers"); 
     } 
     $this->url   = $request; 
     $this->method  = "GET"; 
     return $this->send(); 
    } 

    public function put($request,$xml) 
    { 
     if(!$this->header) 
     { 
      throw new Exception("Please set Headers"); 
     } 

     $this->url   = $request; 
     $this->method  = "PUT"; 
     $this->data  = $xml; 

     return $this->send(); 

    } 


    public function post($request,$xml) 
    { 
     if(!$this->headers) 
     { 
      throw new Exception("Please set Headers"); 
     } 

     $this->url   = $request; 
     $this->method  = "POST"; 
     $this->data  = $xml; 

     return $this->send(); 
    } 


    public function delete($request) 
    { 
     if(!$this->headers) 
     { 
      throw new Exception("Please set Headers"); 
     } 

     $this->url   = $request; 
     $this->method  = "DELETE"; 
     return $this->send(); 

    } 



    public function setUserAgent($useragent) 
    { 
     $this->useragent = $useragent; 
    } 

    protected function send() 
    { 

     $params = array('http' => array 
             (
             'method'  => $this->method, 
             'content' => $this->data, 
             'user_agent' => $this->useragent 
             ) 
         ); 
     $headers = ""; 

     if (!empty($this->headers) && is_array($this->headers)) 
     { 
      foreach ($this->headers as $header) 
      { 
       $headers .= $header."\n"; 
      } 
     } 

     $params['http']['header'] = $headers; 

     $context = stream_context_create($params); 

     $fp   = fopen($this->url, 'r', false, $context); 

     if (!$fp) 
     { 
      throw new Exception("Problem with ".$this->url); 
     } 

     $response = stream_get_contents($fp); 

     if ($response === false) 
     { 
      throw new Exception("Problem reading data from ".$this->url); 
     } 

     return $response; 
    } 
} 
?> 
Смежные вопросы