Thursday, 12 September 2013

Android - How to use HttpURLConnection to send POST request to server

I'm developing an Android app, with which the user can log in and do their task. To log in, it has to connect to the server. I've searched the internet, but most of the examples are about using GET method, not POST. So after I solved my problem, I write this post for those looking for a similar solution.
1. write this in your manifest.xml:
    <uses-permission android:name="android.permission.INTERNET" />
2. server side:
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
String name = request.getParameter("name");
PrintWriter out = response.getWriter();
out.println("Hello "+name);
}
3. Android side, instead of using the main thread, you need to execute the connection in the background. First, implement your own thread:
private class BKTask extends AsyncTask<String, Void, String> {
private String name="";
@Override
protected String doInBackground(String... urls) {
String output = null;
for (String url : urls) {
output = getOutputFromUrl(url);
}
return output;
}

private String getOutputFromUrl(String url) {
StringBuffer output = new StringBuffer("");
try {
InputStream stream = getHttpConnection(url);
BufferedReader buffer = new BufferedReader(
new InputStreamReader(stream));
String s = "";
while ((s = buffer.readLine()) != null)
output.append(s);
} catch (IOException e1) {
e1.printStackTrace();
}
return output.toString();
}

// Makes HttpURLConnection and returns InputStream
private InputStream getHttpConnection(String urlString)
throws IOException {
InputStream stream = null;
URL url = new URL(urlString);
URLConnection connection = url.openConnection();

try {
HttpURLConnection httpConnection = (HttpURLConnection) connection;
httpConnection.setRequestMethod("POST");
httpConnection.setDoOutput(true);
httpConnection.connect();
//post

OutputStreamWriter writer = new OutputStreamWriter(httpConnection.getOutputStream());
String urlParameters = "name="+name;
writer.write(urlParameters);
writer.flush();

if (httpConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
stream = httpConnection.getInputStream();
}
writer.close();
} catch (Exception ex) {
ex.printStackTrace();
}
return stream;
}

@Override
protected void onPostExecute(String output) {

msg.setText(output);
}
}
4. how to use this thread? See the following code. I use a button to submit the request, so this is my code which is called when the button is clicked:
public void submit(View v){
BKTask task = new BKTask();
task.name = name.getText().toString();
task.execute(new String[] { URL });
}

That's all. If any questions, please leave me a msg:)