不推荐使用 openConnection 的 NameValuePair

NameValuePair deprecated for openConnection

我一直在关注关于如何从 android 应用程序将数据插入数据库的在线教程,并且除了这个小部分之外一切正常

List<NameValuePair> params = new ArrayList<>();
params.add(new BasicNameValuePair("username", username));
params.add(new BasicNameValuePair("password", password));

NameValuePair 和 BasicNameValuePair 已被弃用,取而代之的是 openConnection()。我怎样才能与之建立新的价值关联? http://developer.android.com/reference/java/net/URL.html#openConnection()

有谁知道如何使用 openConnection 创建名称值对?我到处找。

您可以使用ContentValues,例如:

ContentValues values = new ContentValues();
values.put("username", name);
values.put("password", password);
database.insert(Table_name, null, values);

你可以在 21 中更改你的 android Api,右键单击,属性 android,单击 api 21 对我有用

您可以使用 httpmime.jar 文件代替它,这样比 NameValuePair 效果更好。您可以从这里下载,Download

MultipartEntity multi = new MultipartEntity();
multi.addPart("name", new StringBody("Raj"));
multi.addPart("Id", new StringBody("011"));

将这个 jar 添加到您的项目中,然后使用它。

替代 NameValuePair。您还可以从中获取名称和值,如下所述。这里的关键是一个名字。

创建:

ContentValues values = new ContentValues();
values.put("key1", "value1");
values.put("key2", "value2");

获取键和值:

for (Map.Entry<String, Object> entry : values.valueSet()) {
    String key = entry.getKey(); // name
    String value = entry.getValue().toString(); // value
}

我刚 运行 遇到了同样的问题。 org.apache.http 中弃用的 类 已在 API 23.

删除

我最终使用了 android.util.Pair。它运行完美,代码也更短:

List<Pair<String, String>> params = new ArrayList<>();
params.add(new Pair<>("username", username));
params.add(new Pair<>("password", password));

如果您真的想在您的应用程序中使用 NameValuePair,您可以将 useLibrary 'org.apache.http.legacy' 添加到您的 gradle:

buildtypes{
    //------------
    //----------
}

useLibrary 'org.apache.http.legacy'

您可以根据自己的喜好使用 contentvalues 或 hashmap。

我使用了内容值

ContentValues contentValues = new ContentValues();
contentValues.put("key1","value1");
contentValues.put("key2","value2");

如果您发布的数据是表单数据,那么这里是您如何将其转换为表单数据的方法

 public String getFormData(ContentValues contentValues) throws UnsupportedEncodingException {

    StringBuilder sb = new StringBuilder();
    boolean first = true;
    for (Map.Entry<String, Object> entry : contentValues.valueSet()) {
        if (first)
            first = false;
        else
            sb.append("&");

        sb.append(URLEncoder.encode(entry.getKey(), "UTF-8"));
        sb.append("=");
        sb.append(URLEncoder.encode(entry.getValue().toString(), "UTF-8"));
    }
    return sb.toString();
}