Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sending HTTP Post Request with Android

I've been trying to learn from tons of examples on SO and other sites, but I can't figure out why the example I've hacked together isn't working. I'm building a small proof-of-concept app that recognizes speech and sends it (the text) as a POST request to a node.js server. The speech recognition I have confirmed to work and the server is receiving connections from a regular browser visit, so I'm led to believe that the issue is in the app itself. Am I missing something small and stupid? No errors are being thrown but the server is never recognizing a connection. Thanks in advance for any advice or help.

Relevant Java (main activity and the necessary AsyncTask):

protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == 1001) {
        if (resultCode == RESULT_OK) {
            ArrayList<String> textMatchList = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
            if (!textMatchList.isEmpty()) {
                String topMatch = textMatchList.get(0);
                PostTask pt = new PostTask();
                pt.execute(topMatch);
            }
        }
    }
}

private class PostTask extends AsyncTask<String, String, String> {
    @Override
    protected String doInBackground(String... data) {
        try {
            URL url = new URL("http://<ip address>:3000");
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setReadTimeout(10000);
            conn.setConnectTimeout(15000);
            conn.setRequestMethod("POST");
            conn.setDoOutput(true);
            ContentValues values = new ContentValues();
            values.put("data", data[0]);
            OutputStream os = conn.getOutputStream();
            BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
            StringBuilder sb = new StringBuilder();
            sb.append(URLEncoder.encode("data", "UTF-8"));
            sb.append("=");
            sb.append(URLEncoder.encode(data[0], "UTF-8"));
            writer.write(sb.toString());
            writer.flush();
            writer.close();
            os.close();
            conn.connect();
            return "Text sent: " + data[0];
        } catch (IOException e) {
            e.printStackTrace();
            return "LOL NOPE";
        }
    }
}

Server JS:

var http = require('http');
const PORT=3000;

function handleRequest(request, response){
    response.end('It Works!! Path Hit: ' + request.url);
    console.log("Request got.");
}

var server = http.createServer(handleRequest);
server.listen(PORT, '0.0.0.0');
console.log("Listening on 3000...");
like image 420
Kienan Knight-Boehm Avatar asked Jul 22 '15 01:07

Kienan Knight-Boehm


People also ask

How do I request post on Android?

build(); Request request = new Request. Builder() . url("https://yourdomain.org/callback.php") // The URL to send the data to .

What is get and post method in Android?

GET and POST Two common methods for the request-response between a server and client are: GET- It requests the data from a specified resource. POST- It submits the processed data to a specified resource.

How send and receive data from server in Android?

Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main. xml. Step 3 − Add the following code to res/layout/MainActivity.


1 Answers

You can use Http Client from Apache Commons. For example:

private class PostTask extends AsyncTask<String, String, String> {
  @Override
  protected String doInBackground(String... data) {
    // Create a new HttpClient and Post Header
    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost("http://<ip address>:3000");

    try {
      //add data
      List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
      nameValuePairs.add(new BasicNameValuePair("data", data[0]));
      httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
      //execute http post
      HttpResponse response = httpclient.execute(httppost);

    } catch (ClientProtocolException e) {

    } catch (IOException e) {

    }
  }
}

UPDATE

You can use Volley Android Networking Library to post your data. Official document is here.

I personally use Android Asynchronous Http Client for few REST Client projects.

Other tool that good to explore is Retrofit.

like image 165
zzas11 Avatar answered Oct 01 '22 17:10

zzas11