从android向python发送HTTPS GET请求不起作用

时间:2017-01-31 20:25:18

标签: java android json https getjson

我试图在Android应用(客户端)和我的笔记本电脑(服务器)之间建立https连接。 我的https服务器以python脚本(带有letsencrypt证书)运行,只要我尝试用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);

}

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

1 个答案:

答案 0 :(得分:0)

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

相关问题