传递参数与HttpURLConnection类 [英] Passing Parameters with HttpURLConnection
问题描述
随着API 22 pcated老阿帕奇东西德$ P $,我终于得到周围更新我的网络的东西。
With the old Apache stuff deprecated in API 22, I am finally getting around to updating my network stuff.
使用的openConnection()
似乎pretty直线前进。不过,我还没有看到任何很好的例子,与发送的参数。
Using openConnection()
seems pretty straight forward. However, I have not seen any good example to send parameters with it.
我怎么会更新这个code?
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));
现在的NameValuePair </ code>和
BasicNameValuePair </ code>也在德precated。
Now that NameValuePair
and BasicNameValuePair
are also deprecated.
编辑:我的服务器端 PHP
code不希望JSON参数,我不能所有的突然切换,由于现有用户的 - 所以建议非JSON的答案。
My server side php
code 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.
EDIT2:我只需要在一瞬间目标于Android 4.1
I just need to Target Android 4.1+ at the moment.
推荐答案
我固定它是这样的:
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();
这篇关于传递参数与HttpURLConnection类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!