How to send post parameter which can be read by php - java

I have some connection to url:
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
How I can send post parameter to this url that php function: http://www.php.net/manual/en/reserved.variables.request.php can read it ? I try to according this question: Java - sending HTTP parameters via POST method easily but with no success. It just display empty array
php code:
print_r($_REQUEST,1)
java code:
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setInstanceFollowRedirects(false);
connection.setRequestMethod("POST");
connection.setRequestProperty("category_name", categoryName);
connection.setRequestProperty("complete", complete);
DataOutputStream wr = new DataOutputStream(connection.getOutputStream());
connection.getResponseCode();
wr.flush();
wr.close();
connection.disconnect();

You forgot to set the Content-Type header, and you need to write the category_name and complete values as a string to the stream.
Quoting the code from the post you mentioned:
String urlParameters = "param1=a&param2=b&param3=c";
String request = "http://example.com/index.php";
URL url = new URL(request);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setInstanceFollowRedirects(false);
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.setRequestProperty("charset", "utf-8");
connection.setRequestProperty("Content-Length", "" + Integer.toString(urlParameters.getBytes().length));
connection.setUseCaches (false);
DataOutputStream wr = new DataOutputStream(connection.getOutputStream ());
wr.writeBytes(urlParameters);
wr.flush();
wr.close();
connection.disconnect();
As you can see, he sets the headers (Content-Type, Charset and Content-Length) and then writes the POST data to the stream.
The POST data is just like the GET format: key-value pairs seperated by &, and the key and value are seperated by =.
As the Content-Type is set to www-form-urlencoded, you need to 'url encode' the key and value values. You can do this using the URLEncoder.encode method.
The urlParameters for your POST data would be:
String urlParameters = "category_name=" + URLEncoder.encode(categoryName) + "&complete=" + URLEncoder.encode(complete);

Related

HTTPURLConnection write command works only with read

I am writing a file into AWS S3 bucket using HTTPURLConnection. This connection's outputstream-write command works only if it is followed by getInputStream or getResponseCode. Please help me to understand this. Is it required to read responseCode?
URL endpointUrl = new URL("muURL");
HttpURLConnection connection = (HttpURLConnection) endpointUrl.openConnection();
connection.setRequestMethod("PUT");
connection.setRequestProperty("Authorization", authorization);
connection.setRequestProperty("x-amz-content-sha256", hashPayload);
connection.setRequestProperty("X-Amz-Date", myDate);
connection.setRequestProperty("Content-Type","application/octet-stream");
connection.setRequestProperty("Content-Length",contentLen);
//connection.setRequestProperty("Accept","*/*");
connection.setUseCaches(false);
//connection.setDoInput(true);
connection.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(connection.getOutputStream());
wr.writeBytes(payload);
StringBuilder builder = new StringBuilder();
// If I comment this line which gets responseCode , then file is not written in S3.
builder.append(connection.getResponseCode());
wr.flush();
wr.close();
connection.disconnect();
I am expecting this code to work without getResponseCode line.

Send sentence using setRequestProperty

I am sending image and some text from my Android app to PHP server and I am using this code to do it:
...
URL url = new URL("http://example.com/upload.php");
httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setDoInput(true);
httpURLConnection.setDoOutput(true);
httpURLConnection.setUseCaches(false);
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setRequestProperty("Connection", "Keep-Alive");
httpURLConnection.setRequestProperty("ENCTYPE", "multipart/form-data");
httpURLConnection.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
httpURLConnection.setRequestProperty("File", imagePath);
httpURLConnection.setRequestProperty ("Text", someText);
...
This works when someText variable is a word, but when it's a sentence with spaces between words it doesn't work.
Why is that? And is there a way to make it work?

Could not post parameters to Server

I am trying to pass parameters to a PHP Server using POST method in java but the response string I get is an error message on the line where the server tries to access option parameter at line:
Undefined index at line $option = $_POST["option"];
My code is as follows:
HttpURLConnection con = (HttpURLConnection)(new URL("http://--server-ip--")).openConnection();
con.setRequestMethod("POST");
con.setRequestProperty("User-Agent", "Mozilla/5.0");
con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
String urlParameters = "option=1&type=1&coord=-33.867,151.206";
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(urlParameters);
wr.flush();
wr.close();
con.connect();
Can anybody point out the mistake?

HttpURLConnection doing a get request even after setDoOutput(true), setRequestMethod("POST") setRequestProperty("Content

Here is the code:
String Surl = "http://mysite.com/somefile";
String charset = "UTF-8";
query = String.format("param1=%s&param2=%s",
URLEncoder.encode("param1", charset),
URLEncoder.encode("param2", charset));
HttpURLConnection urlConnection = (HttpURLConnection) new URL(Surl + "?" + query).openConnection();
urlConnection.setRequestMethod("POST");
urlConnection.setDoOutput(true);
urlConnection.setUseCaches(false);
urlConnection.setAllowUserInteraction(false);
urlConnection.setRequestProperty("Accept-Charset", charset);
urlConnection.setRequestProperty("User-Agent","<em>Android</em>");
urlConnection.setRequestProperty("Content-Type","application/x-www-form-urlencoded;charset=" + charset);
urlConnection.connect();
The above still does a GET request. I am using PHP on the server and am able to access the query's 'name=value' params through the $_GET variable and not the $_POST variable
Tested on 2.3.7(device).
What am I missing ?
When you send parameters in the url they are put in the GET variable. You should be posting the parameters in the POST body of the request to achieve what you are looking for. You should add the following just before the connect() call and remove the "?" + query from the url.
urlConnection.setRequestProperty("Content-Length", String.valueOf(query.getBytes().length));
urlConnection.setFixedLengthStreamingMode(query.getBytes().length);
OutputStream output = new BufferedOutputStream(urlConnection.getOutputStream());
output.write(query.getBytes());
output.flush();
output.close();

How to set content-length in android?

I want to get content size by request.getContentLength() in server client JSP page.
But request.getContentLength() always return -1, i do not why?
Android snippet code:
URL uri = new URL(actionUrl);
HttpURLConnection conn = (HttpURLConnection) uri.openConnection();
//conn.setChunkedStreamingMode(100);
conn.setConnectTimeout(setTimeOut>0?setTimeOut:timeoutConnection);
conn.setReadTimeout(setTimeOut>0?setTimeOut:timeoutConnection);
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setUseCaches(false);
conn.setRequestMethod("POST");
conn.setRequestProperty("Connection", "keep-alive");
//conn.setRequestProperty("content-length", "10");
//conn.addRequestProperty("content-length", "20");
conn.setFixedLengthStreamingMode(30);
conn.setRequestProperty("Charsert", ENCODING);
conn.setRequestProperty("Content-Type", "multipart/form-data"
+ ";boundary=" + java.util.UUID.randomUUID().toString());
conn.connect();
You are using conn.setChunkedStreamingMode(100) that will effectively enable the chunked transfer encoding in chunks of 100 bytes when the content-lenght is unknown in advance.
Use conn.setFixedLengthStreamingMode(int len) if you know in advance the length of the content you are going to send in the body of the request.

Categories