gpt4 book ai didi

java - 如何将 Android 应用程序连接到 Web 服务器

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:34:50 31 4
gpt4 key购买 nike

我正在为我的高级设计项目设计 Android 应用程序。该应用程序需要能够连接到 Web 服务器。 Web 服务器只是个人计算机上本地托管的 Apache Web 服务器。该应用程序需要将临时软件更新下载到手机/应用程序。

在设计的这一点上,我已经构建了登录页面和主页。我遇到的问题是如何从应用程序连接到 Web 服务器。我的教授还要求从登录页面输入正确的用户名和密码,这些凭据也将访问 Web 服务器。我也在质疑这是否可能。任何建议都会收到。

谢谢 - 如果此问题需要更多信息或不够清楚无法回答,请告诉我。

最佳答案

做android到远程服务器的连接很有意思,很焦虑。下面的链接将帮助您最大限度地满足您的需求。

Android Connect with Php Mysql

Android Connection using servlets

如果您想使用 HttpUrlConnection 从 Android 设备连接服务器,请按照以下代码操作。

private static JSONObject get(Context ctx, String sUrl) {
HttpURLConnection connection = null;

try {

URL url = new URL(sUrl);
connection = (HttpURLConnection) url.openConnection();
connection.setRequestProperty("Content-Type", "application/json");
connection.setRequestProperty("Accept", "application/json");
connection.setRequestProperty("Authorization",
"Basic " + encodedAuthentication);
connection.setRequestProperty("Accept-Charset", "utf-8,*");
Log.d("Get-Request", url.toString());
try {
BufferedReader bufferedReader = new BufferedReader(
new InputStreamReader(connection.getInputStream()));
StringBuilder stringBuilder = new StringBuilder();
String line;
while ((line = bufferedReader.readLine()) != null) {
stringBuilder.append(line).append("\n");
}
bufferedReader.close();
Log.d("Get-Response", stringBuilder.toString());
return new JSONObject(stringBuilder.toString());
} finally {
connection.disconnect();
}
} catch (Exception e) {
Log.e("ERROR", e.getMessage(), e);
return null;
}
}

private static String buildSanitizedRequest(String url,
Map<String, String> mapOfStrings) {

Uri.Builder uriBuilder = new Uri.Builder();
uriBuilder.encodedPath(url);
if (mapOfStrings != null) {
for (Map.Entry<String, String> entry : mapOfStrings.entrySet()) {
Log.d("buildSanitizedRequest", "key: " + entry.getKey()
+ " value: " + entry.getValue());
uriBuilder.appendQueryParameter(entry.getKey(),
entry.getValue());
}
}
String uriString;
try {
uriString = uriBuilder.build().toString(); // May throw an
// UnsupportedOperationException
} catch (Exception e) {
Log.e("Exception", "Exception" + e);
}

return uriBuilder.build().toString();

}

Json 调用部分应该是这样的,

public static JSONObject exampleGetMethod(Context ctx, String sUrl, String username, String password) throws JSONException, IOException {
Map<String, String> request = new HashMap<String, String>();
request.put("username", username);
request.put("password",password);

sUrl = sUrl + "yourApiName";
return get(ctx, buildSanitizedRequest(sUrl, request));
}

关于java - 如何将 Android 应用程序连接到 Web 服务器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41051686/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com