【发布时间】: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);
}
我再次尝试简化代码,以便获得一个可以在以后扩展的小型工作代码。 该应用程序不再崩溃,但我的服务器仍然没有显示任何请求。如果我在手机上使用浏览器,一切正常。任何想法?
【问题讨论】:
-
您遇到异常了吗?日志猫?
-
你是不是忘了给urlConnection.connect()打电话?
-
不,不需要连接,他得到了 NOMTException。 也许有人遇到了同样的问题是的,无数人,搜索你的例外
标签: java android json https getjson