【问题标题】:Sending HTTPS GET request from android to python is not working将 HTTPS GET 请求从 android 发送到 python 不起作用
【发布时间】:2017-01-31 20:25:17
【问题描述】:

我正在尝试在 Android 应用程序(客户端)和我的笔记本电脑(服务器)之间建立 https 连接。 我的 https 服务器作为 python 脚本运行(带有 letencrypt 证书),只要我尝试将它与 chrome 或其他 python 脚本连接,它就可以正常工作。

现在我想在我的 android 应用中实现客户端。因此我将权限添加到AndroidManifest.xml:

<uses-permission android:name="android.permission.INTERNET"/>

并将以下几行添加到我的MainActivity.java(基于HttpURLConnection Reference on Android Developers!:

public void onButtonClicked(String message) {

    try {
        URL url = new URL("https://foo.bar.com/");
        HttpsURLConnection urlConnection = (HttpsURLConnection) url.openConnection();
        urlConnection.setRequestMethod("GET");
        OutputStream output = new BufferedOutputStream(urlConnection.getOutputStream());

    } catch (IOException e) {
        e.printStackTrace();
    }

    mSecondFragment.updateMessage(message);

}

目前我只想建立与我的 https 服务器的连接并发送一个简单的 GET 请求而不接收任何数据。但我的目标是解析一个额外的键值对以及将由服务器处理的GET 请求:

"https://foo.bar.com?a=1"

我试图让它尽可能简单(这就是我想使用java.net.HttpURLConnection 的原因),但我认为问题并不像我预期的那么简单。

也许有人遇到了同样的问题,可以帮助我解决这个问题:)

编辑(感谢@atomicrat2552 和@petey):

我添加了一个将请求作为 AsyncTask 处理的附加类:

public class NetworkConnection extends AsyncTask<String, Void, NetworkConnection.Result> {

    static class Result {
        public String mResultValue;
        public Exception mException;
        public Result(String resultValue) {
            mResultValue = resultValue;
        }
        public Result(Exception exception){
            mException = exception;
        }
    }

    protected NetworkConnection.Result doInBackground(String... urls) {
        Result result = null;
        HttpsURLConnection urlConnection = null;

        try {
            URL url = new URL(urls[0]);
            urlConnection = (HttpsURLConnection) url.openConnection();
            urlConnection.setRequestMethod("GET");
            //urlConnection.connect();
            result = new Result("Done");
        }catch(Exception e) {
            result = new Result(e);
        } finally {
            if (urlConnection != null) {
                urlConnection.disconnect();
            }
        }
        return result;
    }
}

这导致MainActivity.java中的一个简化的onButtonClick方法:

NetworkConnection nwConn = new NetworkConnection();

public void onButtonClicked(String message) {

    nwConn.execute("https://foo.bar.com");
    mSecondFragment.updateMessage(message);

}

我再次尝试简化代码,以便获得一个可以在以后扩展的小型工作代码。 该应用程序不再崩溃,但我的服务器仍然没有显示任何请求。如果我在手机上使用浏览器,一切正常。任何想法?

【问题讨论】:

标签: java android json https getjson


【解决方案1】:

我在这里看到的最常见的缺陷是网络代码无法在 UI 线程上运行,因此您必须使用某种后台工作程序来执行网络调用。开发者网站上有 a basic guide 说明如何执行此操作。

【讨论】:

  • 谢谢!我添加了我认为运行基本 GET 请求所必需的部分代码。 (我比较了@petey 提到的代码)。该应用程序现在运行顺利,但我的服务器仍然没有收到任何请求。如果我在手机上使用浏览器,一切似乎都很好。我将编辑我最初的问题并添加结果代码。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-05-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多