Java 使用 Android 发送 HTTP Post 请求

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31552242/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 11:14:16  来源:igfitidea点击:

Sending HTTP Post Request with Android

javaandroidnode.jshttppost

提问by Kienan Knight-Boehm

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.

我一直在尝试从 SO 和其他网站上的大量示例中学习,但我不明白为什么我一起破解的示例不起作用。我正在构建一个小型的概念验证应用程序,它可以识别语音并将其(文本)作为 POST 请求发送到 node.js 服务器。我已经确认语音识别可以工作并且服务器正在接收来自常规浏览器访问的连接,所以我相信问题出在应用程序本身。我错过了一些小而愚蠢的东西吗?没有抛出任何错误,但服务器永远无法识别连接。在此先感谢您的任何建议或帮助。

Relevant Java (main activity and the necessary AsyncTask):

相关 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";
        }
    }
}

Server JS:

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

采纳答案by zzas11

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

您可以使用 Apache Commons 中的 Http 客户端。例如:

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.

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

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

我个人在少数 REST 客户端项目中使用Android 异步 Http 客户端。

Other tool that good to explore is Retrofit.

其他值得探索的工具是Retrofit