System.InvalidOperationException: Request format is invalid: multipart/form-data; boundary Error When Calling .Net Web Service From PHP



TODO:

Have you ever tried to use php/curl to call a .Net Webservice and received the following:

System.InvalidOperationException: 

Request format is invalid: multipart/form-data;

boundary=----------------------------7d78134d9ec2.
 at System.Web.Services.Protocols.HttpServerProtocol.ReadParameters()
 at System.Web.Services.Protocols.WebServiceHandler.CoreProcessRequest()

 

SOLUTION:

 

<?php
	$ch = curl_init();
	curl_setopt($ch, CURLOPT_HEADER, 0);
	curl_setopt($ch, CURLOPT_VERBOSE, 0);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
	curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/4.0 (compatible;)");
	curl_setopt($ch, CURLOPT_POST, true);
	curl_setopt($ch, CURLOPT_URL,'http://my.webservice.com/MyService.asmx/MyMethod' );
	$post_array = array(
			"Param1"=>'xyz',
			"Param2"=>'abc',
			"Param3"=>'123'
	);

	//url-ify the data
	foreach($post_array as $key=>$value) 
	{ 
		$post_array_string .= $key.'='.$value.'&'; 
	}
	$post_array_string = rtrim($post_array_string,'&');
	//set the url, number of POST vars, POST data
	curl_setopt($ch,CURLOPT_POST,count($post_array ));
	curl_setopt($ch,CURLOPT_POSTFIELDS,$post_array_string);
	$response = curl_exec($ch);
	print_r($response);
?>

 

NOTES:

This happens when you have parameters in your web method.  If you have no parameters, you can just access the Form["Param1"] to get to the data and do not need this foreach code at the end.



Comments (6) -

Nate
Nate
12/6/2011 1:09:10 PM #

Thank you, that fixed my problem!  It never occurred to me to put the params in as a string, since CURLOPT_POSTFIELDS usually takes an associative array just fine.  FYI, check out php.net/manual/en/function.http-build-query.php.  It generates a url-encoded query string from an associative array Smile

Anoop NP
Anoop NP
4/24/2012 2:18:28 AM #

Thank you very much it fixed my problem of sending files to my web service ....Smile

salah
salah
9/12/2013 2:47:22 AM #

thanks alot...
it really helped me...i was pulling my hair on this issue from many hours

Donnie Wishard
Donnie Wishard
9/12/2013 7:04:38 AM #

Glad it worked for you!

Ivan Lewis
Ivan Lewis
9/12/2013 12:14:00 PM #

how to add $xmlstring = '<xml></xml>'; as file here?

Robin
Robin
8/26/2014 8:17:08 PM #

You champion, thank you so much for sharing this, really appreciated.

Pingbacks and trackbacks (1)+

Add comment

  Country flag

biuquote
  • Comment
  • Preview
Loading