I've been toying around with making a basic Android app to interface with a website, and one of the things I need to do is standard HTTP requests, GETs and POSTs and such. I had been using the AndroidHttpClient APIs, which were a bit verbose, but basically reasonable, and look kinda like this:
HttpPost loginRequest = new HttpPost(siteAddress);
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(3);
nameValuePairs.add(new BasicNameValuePair("ACCESS_CODE", accessCode));
nameValuePairs.add(new BasicNameValuePair("Login", "Login"));
nameValuePairs.add(new BasicNameValuePair("GO", "YES"));
loginRequest.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse loginResponse = client.execute(loginRequest, clientContext);
if (loginResponse.getStatusLine().getStatusCode() != 200) return false;
String responseString = EntityUtils.toString(loginResponse.getEntity());
Then I updated to API22, and apparently, the whole AndroidHttpClient API is deprecated. Seems I'm supposed to be using HttpUrlConnection instead, according to a blog post from 4 years ago. Googling around some, I find that sending a standard HTTP POST with HttpUrlConnection would look something like
URL url = new URL("http://yoururl.com");
HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
conn.setReadTimeout(10000);
conn.setConnectTimeout(15000);
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("firstParam", paramValue1));
params.add(new BasicNameValuePair("secondParam", paramValue2));
params.add(new BasicNameValuePair("thirdParam", paramValue3));
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os, "UTF-8"));
writer.write(getQuery(params));
writer.flush();
writer.close();
os.close();
conn.connect();
Where you define your own getQuery something like:
private String getQuery(List<NameValuePair> params) throws UnsupportedEncodingException
{
StringBuilder result = new StringBuilder();
boolean first = true;
for (NameValuePair pair : params)
{
if (first)
first = false;
else
result.append("&");
result.append(URLEncoder.encode(pair.getName(), "UTF-8"));
result.append("=");
result.append(URLEncoder.encode(pair.getValue(), "UTF-8"));
}
return result.toString();
}
According to a highly upvoted SO response:
Apparently, now I need to either write my own form encoder, or pull in a third-party library to do it for me. Because it's not like an average Android app developer would ever need to do something like send a POST request or anything.