且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何将Android应用连接到Web服务器

更新时间:2022-02-14 09:11:46

进行android与远程服务器的连接非常有趣,非常焦虑.下面的链接将帮助您最大程度地满足您的需求.

It's very interesting to do the connections of the android to the remote server, very anxiety. Below link will help you max for your need.

Android与Php Mysql连接

使用servlet的Android连接

如果您想使用HttpUrlConnection从android设备连接服务器,请遵循以下代码.

And If you wanna connect the server from the android device by using HttpUrlConnection then follow the below code.

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调用部分应该看起来像

And Json calling part should look like,

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