I'm developing an android app that needs to interface with a server. To test that my HTTP post stuff is working, I am using posttestserver.com. Alas, while the messages I send are received, the Post parameters I tried to send along are not received. I have the internet permission enabled in my Manifest (something I saw come up a lot in other questions) but still, I can't get the data to go through. My code is:
public String uploadData(String dataLine) throws MalformedURLException {
URL url = new URL(urlName);
HttpURLConnection urlConnection;
String text = "";
BufferedReader reader = null;
try {
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setDoOutput(true);
urlConnection.setDoInput(true);
urlConnection.setChunkedStreamingMode(0);
urlConnection.setRequestMethod("POST");
urlConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
Uri.Builder builder = new Uri.Builder()
.appendQueryParameter("key", key)
.appendQueryParameter("data", dataLine);
String query = builder.build().getEncodedQuery();
OutputStream os = urlConnection.getOutputStream();
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os, "UTF-8"));
writer.write(query);
writer.flush();
writer.close();
os.close();
urlConnection.connect();
reader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = null;
// Read Server Response
while((line = reader.readLine()) != null)
{
// Append server response in string
sb.append(line + "\n");
}
reader.close();
text = sb.toString();
} catch (IOException e) {
e.printStackTrace();
}
return text;
}
I was originally building the Post data with something like
String POST = "key="+URLEncoder.encode(key, "UTF-8");
but in a different thread, I saw this method. (How to add parameters to HttpURLConnection using POST)
http://posttestserver.com/data/2015/07/27/14.39.441876894412 this is one of the POST requests that didn't bring the parameters along.