使用Android发送HTTP发布请求 [英] Sending HTTP Post Request with Android

查看:174
本文介绍了使用Android发送HTTP发布请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在尝试从SO和其他网站上的大量示例中学习,但我无法弄清楚为什么我一起攻击的例子不起作用。我正在构建一个小概念验证应用程序来识别语音并将其作为POST请求发送给node.js服务器。我已经确认语音识别工作,服务器正在接收来自常规浏览器访问的连接,因此我开始相信问题出在应用程序本身。我错过了一些小而愚蠢的东西吗?没有错误被抛出,但服务器永远不会识别连接。提前感谢您的任何建议或帮助。

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.

相关Java(主要活动和必要的AsyncTask):

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

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


推荐答案

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

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

    }
  }
}

更新

您可以使用Volley Android Networking Library发布您的数据。官方文档为此处

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

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

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

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

Other tool that good to explore is Retrofit.

这篇关于使用Android发送HTTP发布请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆