NameValuePair已弃用

时间:2015-03-23 21:27:59

标签: android httpurlconnection

因为Android 22 NameValuePair已被弃用。

documentation向我发送了一篇关于openConnection的文章,但这就是我所做的。那么如何正确地替换它?

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

5 个答案:

答案 0 :(得分:10)

您可以使用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();
}

答案 1 :(得分:5)

你可以使用

HashMap<String,Object>

并传递HashMap b / w方法。

答案 2 :(得分:2)

尝试使用此代码,我在我的应用程序上使用

 
public String post(JSONObject object) throws Exception {

HttpURLConnection conexao = null; if (Build.VERSION.SDK_INT < Build.VERSION_CODES.FROYO) { System.setProperty("http.keepAlive", "false"); } try { URL url = new URL(URL_WEB_SERVICE_POST); conexao = (HttpURLConnection) url.openConnection(); conexao.setConnectTimeout(20000); conexao.setReadTimeout(15000); conexao.setRequestMethod("POST"); conexao.setDoInput(true); conexao.setDoOutput(true); Uri.Builder builder = new Uri.Builder() .appendQueryParameter("parametros", object.toString()); String query = builder.build().getEncodedQuery(); conexao.setFixedLengthStreamingMode(query.getBytes().length); OutputStream os = conexao.getOutputStream(); BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8")); writer.write(query); writer.flush(); writer.close(); os.close(); conexao.connect(); int responseCode = conexao.getResponseCode(); Log.v(Debug.TAG + " reponseCode", String.valueOf(responseCode)); if(responseCode == HttpURLConnection.HTTP_OK){ StringBuilder sb = new StringBuilder(); try{ BufferedReader br = new BufferedReader(new InputStreamReader(conexao.getInputStream())); String linha; while ((linha = br.readLine())!= null){ sb.append(linha); } return sb.toString(); }catch (Exception e){ e.printStackTrace(); } }else{ if(responseCode == HttpURLConnection.HTTP_CLIENT_TIMEOUT){ throw new Exception("Tempo maximo na comunição atingido: "+ conexao.getErrorStream()); } } } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); throw new Exception("Falha de comunicação, verifique sua conexão com a internet"); }finally { conexao.disconnect(); } return null; }

答案 3 :(得分:0)

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

答案 4 :(得分:0)

使用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();
}