0

I have a code that sends a request with post parameters. However, when I check on server, the post array is empty. I've tried everything I found in internet, but nothing helped.What is an wrong here?

 String url = "http://exifeed.com/api.php"; URL obj = new URL(url); HttpURLConnection con = (HttpURLConnection) obj.openConnection(); StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build(); StrictMode.setThreadPolicy(policy); con.setRequestMethod("POST"); String urlParameters = "ApiKey=xxx"; // Send post request con.setDoOutput(true); OutputStream os = con.getOutputStream(); BufferedWriter writer = new BufferedWriter( new OutputStreamWriter(os, "UTF-8")); writer.write(urlParameters); writer.flush(); writer.close(); os.close(); con.connect(); int responseCode = con.getResponseCode(); System.out.println("\nSending 'POST' request to URL : " + url); System.out.println("Post parameters : " + urlParameters); System.out.println("Response Code : " + responseCode); BufferedReader in = new BufferedReader( new InputStreamReader(con.getInputStream())); String inputLine; StringBuilder response = new StringBuilder(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); //print result System.out.println(StringEscapeUtils.unescapeJava(response.toString())); 

Code on server

print_r($_GET); print_r($_POST); exit; 

The output result is

Array()Array()

P.S. I added www. before domain name and it suddenly worked. I guess it was because I had redirect in .htaccess file on server. Thanks everyone anyway.

1
  • because you don't give a content type, you need to use file_get_contents('php://input'); to access the content of the post body. Commented Oct 27, 2016 at 13:57

2 Answers 2

1

Maybe you're missing the Content-Type header. Refer to this answer. You can set a header this way:

HttpURLConnection con = (HttpURLConnection) obj.openConnection(); con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); 
Sign up to request clarification or add additional context in comments.

1 Comment

I tried setting Content-Type parameter, but it didn't help.
0

sorry man i can't reply on prev post ..

i tried this locally using post-man:

PHP Script :

......... POST request : with parameters : tag : register name : murad email : [email protected] password : 123

....... and this is the output: Array ( [tag] => register [name] => murad [email] => [email protected] [password] => 123 ) Array ( ) ......

please check the php version u have coz print_r as the doc say for : (PHP 4, PHP 5, PHP 7)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.