使用安卓发送 HTTP Post 请求

2022-09-04 01:07:44

我一直试图从SO和其他网站上的大量例子中学习,但我不明白为什么我一起破解的例子不起作用。我正在构建一个小型的概念验证应用程序,该应用程序可识别语音并将其(文本)作为POST请求发送到节点.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...");

答案 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 Networking Library 发布您的数据。官方文件在这里

我个人将Android Asynchronous Http Client用于几个REST客户端项目。

其他值得探索的工具是改造


答案 2

推荐