一尘不染

使用Android发送HTTP发布请求

node.js

我一直在尝试从SO和其他站点上的大量示例中学习,但是我无法弄清楚为什么我一起学习的示例无法正常工作。我正在构建一个小型的概念验证应用程序,该应用程序可以识别语音并将其(文本)作为POST请求发送到node.js服务器。我确认了语音识别功能,并且服务器正在通过常规浏览器访问获得连接,因此我被认为是问题出在应用程序本身。我想念一些小而愚蠢的东西吗?没有引发任何错误,但是服务器从不识别连接。在此先感谢您的任何建议或帮助。

相关的Java(主要活动和必要的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";
        }
    }
}

服务器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...");

阅读 207

收藏
2020-07-07

共1个答案

一尘不染

您可以使用来自Apache Commons的Http Client。例如:

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) {

    }
  }
}

更新

您可以使用Volley
Android网络库发布数据。正式文件在这里

我个人将Android Asynchronous Http Client用于少数REST Client项目。

值得探索的其他工具是Retrofit

2020-07-07