Dev API

Post here is you are having problems with any of the tutorials.
Post Reply
RealTuty
Posts: 11
Joined: Thu Dec 15, 2011 4:29 am

Dev API

Post by RealTuty »

Ok so now i have a problem with the dev api tut here is my code
<?php

class url_shortener {
		
	const API_URL = 'http://localhost:8888/r2/api/a.php';
	
	private static function send_post_data($data) {
		
		$url 		= parse_url(self::API_URL);
		$boundary 	= md5(microtime(true));
		
		$post = '';
		
		foreach ($data as $name => $value) {
			$post .= "--{$boundary}\r\n";
			$post .= "Content-Disposition: form-data; name=\"{$name}\"\r\n\r\n";
			$post .= $value . "\r\n";
		}
		
		$post .= "--{$boundary}--\r\n";
		
		if (isset($url['query'])) {
			$head = "POST = {$url['path']}?{$url['query']} HTTP/1.0\r\n";
		} else {
			$head = "POST = {$url['path']} HTTP/1.0\r\n";
		}
		
		$head .= "Host: {$url['host']}\r\n";
		$head .= "Content-Type: multipart/form-data; boundary=\"{$boundary}\"\r\n";
		$head .= "Content-Length: " . strlen($post) . "\r\n";
		$head .= "Connection: close\r\n\r\n";
		
		$socket = fsockopen($url['host'], ((isset($url['port'])) ? $url['port'] : 80));
		
		fwrite($socket, "{$head}{$post}");
		
		echo end(explode("\r\n\r\n", stream_get_contents($socket)));
	}
	
	// gets the url for the key
	public static function lookup($key) {
		self::send_post_data(array(
			'lookup'	=> $key,
		));
	}
	
	// shortens a new url
	public static function shorten($url) {
		
	}
		
}

?>
the error im getting is

and error code 400
Bad Request

Your browser sent a request that this server could not understand.
:mad:
User avatar
jacek
Site Admin
Posts: 3262
Joined: Thu May 05, 2011 1:45 pm
Location: UK
Contact:

Re: Dev API

Post by jacek »

You must have made a mess of the HTTP request somehow, I cant see it right away but try putting
echo "{$head}{$post}";
above the fwrite() line, that might show up what is wrong. If it's not obvious from that can you post the result of that here for me to take a look :)
Image
RealTuty
Posts: 11
Joined: Thu Dec 15, 2011 4:29 am

Re: Dev API

Post by RealTuty »

Ok so i put
echo "{$head}{$post}";
above the frwite()

and got this
POST = /r2/api/a.php HTTP/1.0 Host: localhost Content-Type: multipart/form-data; boundary="8376698c1a6bf3046e88ba60fbb2cff0" Content-Length: 126 Connection: close --8376698c1a6bf3046e88ba60fbb2cff0 Content-Disposition: form-data; name="lookup" d --8376698c1a6bf3046e88ba60fbb2cff0--
User avatar
jacek
Site Admin
Posts: 3262
Joined: Thu May 05, 2011 1:45 pm
Location: UK
Contact:

Re: Dev API

Post by jacek »

Ah, can you view the page source in your browser and post that with the line breaks intact ?
Image
Post Reply