使用HttpURLConnection传递参数

5

由于API 22中旧的Apache内容已经弃用,因此我终于开始更新我的网络内容。

使用openConnection()似乎很简单。但是,我没有看到任何好的示例来发送参数。

我该如何更新这段代码?

        ArrayList<NameValuePair> param = new ArrayList<NameValuePair>();
        param.add(new BasicNameValuePair("user_id",String.valueOf(userId)));
        httpPost.setEntity(new UrlEncodedFormEntity(param));

现在NameValuePairBasicNameValuePair也被弃用了。
编辑:我的服务器端php代码不接受JSON参数,由于现有用户,我不能突然进行切换--因此建议提供非JSON答案。
编辑2:目前我只需要针对Android 4.1+。

如果您想保持minSdk版本,也许使用已弃用的方法并不是问题。 - Ioane Sharvadze
目前我只需要针对Android 4.1+进行开发,如果有一个适用于所有版本且不使用过时的东西的解决方案,那就是我想要的。另外,我有强迫症,不喜欢代码中出现告诉我某些内容已经过时的线条。 - TheLettuceMaster
您可以使用注释,如@SuppressLint@TargetApi(22)来使用更新的库,并使用@suppresswarnings来清除警告。我认为这不会是一个坏决定。 - Ioane Sharvadze
我知道,我知道,我也不喜欢这些。 :D 通常情况下,某些东西被弃用是有原因的,所以我会尽可能更新。而在这种情况下,Google建议进行这个更改已经有3年了。 - TheLettuceMaster
1
我也讨厌这样的代码技巧,但有时候不可避免。希望你能找到答案,祝你好运! - Ioane Sharvadze
1个回答

7
我这样修复了它:
       HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setDoOutput(true);
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

以下是参数相关内容:

        String charset = "UTF-8";
        String s = "unit_type=" + URLEncoder.encode(MainActivity.distance_units, charset);
        s += "&long=" + URLEncoder.encode(String.valueOf(MainActivity.mLongitude), charset);
        s += "&lat=" + URLEncoder.encode(String.valueOf(MainActivity.mLatitude), charset);
        s += "&user_id=" + URLEncoder.encode(String.valueOf(MyndQuest.userId), charset);

        conn.setFixedLengthStreamingMode(s.getBytes().length);
        PrintWriter out = new PrintWriter(conn.getOutputStream());
        out.print(s);
        out.close();

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