java 使用 HttpURLConnection 传递参数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29375083/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 15:08:38  来源:igfitidea点击:

Passing Parameters with HttpURLConnection

javaandroidparametershttpurlconnectionbasicnamevaluepair

提问by TheLettuceMaster

With the old Apache stuff deprecated in API 22, I am finally getting around to updating my network stuff.

随着 API 22 中旧的 Apache 内容被弃用,我终于开始更新我的网络内容。

Using openConnection()seems pretty straight forward. However, I have not seen any good example to send parameters with it.

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

How would I update this code?

我将如何更新此代码?

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

Now that NameValuePairand BasicNameValuePairare also deprecated.

现在,NameValuePairBasicNameValuePair也已弃用。

EDIT: My server side phpcode doesn't expect JSON parameters and I can't all of the sudden switch due to existing users -- so a non-JSON answer is recommended.

编辑:我的服务器端php代码不需要 JSON 参数,而且由于现有用户,我不能突然切换 - 因此建议使用非 JSON 答案。

EDIT2: I just need to Target Android 4.1+ at the moment.

EDIT2:我现在只需要定位 Android 4.1+。

回答by TheLettuceMaster

I fixed it like this:

我是这样修复的:

       HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setDoOutput(true);
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

Here is parameter stuff:

这是参数的东西:

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