NameValuePair已被弃用

9

自从Android 22版本,NameValuePair已废弃。

文档引导我去一篇关于openConnection的文章,但那正是我所做的。那么应该如何正确地替换它呢?

我知道我还可以使用它,并且必须构建一个字符串,只是想知道如何在方法之间传递数据。


1
我认为这是谷歌方面的文档错误。因为重定向目标与目的不匹配 :| - Amit K. Saha
您IP地址为143.198.54.68,由于运营成本限制,当前对于免费用户的使用频率限制为每个IP每72小时10次对话,如需解除限制,请点击左下角设置图标按钮(手机用户先点击左上角菜单按钮)。 - Artjom B.
你为什么要关心那些你一无所知的旧项目呢?是的,因为它已经过时了,所以需要进行替换。 - Gunnar Bernstein
5个回答

11
你可以使用ContentValues代替NameValuePair列表。
创建:
ContentValues values = new ContentValues();
values.put("key1", "value1");
values.put("key2", 123);

使用方法:

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

这只是一个包装器,用于保存实际值的HashMap<String, Object>。和其他答案建议的一样,可以直接使用它。 - MH.
当您创建一个http连接时,例如new UrlEncodedFormEntity(values, HTTP.UTF_8);它期望的是NameValuePair而不是ContentValues。 - Dantalian
@Dantalian UrlEncodedFormEntity是apache包中的一部分,与NameValuePair一起使用。整个包现在已经被弃用,不应该再使用它。 - Peter Knut
为什么安卓要废弃所有很酷的东西呢?开个玩笑,我会重新实现我的废弃代码,并愉快地收获好处! - Josh

5

You could just use a

HashMap<String,Object>

并在方法之间传递HashMap。

2

试用这段代码,我在我的应用程序中使用过并且有效。

 
public String post(JSONObject object) throws Exception {


我的应用程序不在Play上,不幸的是我需要支持旧设备。公司里有很多用户仍然使用旧设备。 - AndersonCanteiro

1
我建议使用Volley,这是一个HTTP库,可以让Android应用程序的网络通信更加轻松,最重要的是更快。

1
使用Java的HttpUrlConnection和Map/Hashmap,如果您不想使用Apache库作为遗留代码。
/**
 *
 * @param postUrl
 * @param postParams
 * @return response in string
 */
public static String makeServiceCall(final String postUrl, final Map<String, String> postParams) {
    Log.e("URL#",postUrl);
    StringBuilder responseBuilder  = new StringBuilder();
    HttpURLConnection conn = null;
    try {
        final URL mUrl = new URL(postUrl);
        conn = (HttpURLConnection) mUrl.openConnection();
        conn.setDoInput(true);
        conn.setDoOutput(true);
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        conn.setRequestProperty("charset", "utf-8");
        conn.setRequestProperty("User-Agent", "Mozilla/5.0 (Linux; U; Android-4.0.3; en-us; Galaxy Nexus Build/IML74K) AppleWebKit/535.7 (KHTML, like Gecko) CrMo/16.0.912.75 Mobile Safari/535.7");
        conn.connect();
        conn.setReadTimeout(180000);
        conn.setConnectTimeout(180000);
        final OutputStream os = conn.getOutputStream();
        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
        writer.write(getQuery(postParams));
        writer.flush();
        writer.close();
        os.close();
        final int responseCode = conn.getResponseCode();
        if (responseCode == HttpsURLConnection.HTTP_OK) {
            String line;
            BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            while ((line = br.readLine()) != null) {
                responseBuilder.append(line);
            }
        } else {
            responseBuilder.append("");
        }
    } catch (MalformedURLException e) {
        e.printStackTrace();
        responseBuilder.append(e.getMessage());
        return responseBuilder.toString();
    } catch (IOException e) {
        e.printStackTrace();
        responseBuilder.append(e.getMessage());
        return responseBuilder.toString();
    } finally {
        if (null != conn) {
            conn.disconnect();
        }
    }
    System.gc();
    return responseBuilder.toString();
}


/**
 * @Param: map , takes in value in key val format
 */
private static String getQuery(final Map<String, String> mPostItems) throws UnsupportedEncodingException {
    final StringBuilder result = new StringBuilder();
    boolean first = true;
    final Set<String> mKeys = mPostItems.keySet();
    for (String key : mKeys) {
        if (first)
            first = false;
        else
            result.append("&");

        result.append(URLEncoder.encode(key, "UTF-8"));
        result.append("=");
        result.append(URLEncoder.encode(mPostItems.get(key), "UTF-8"));
        Log.e("Key#",key+"#"+mPostItems.get(key));
    }
    return result.toString();
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接