[英]Android Post UTF-8 HttpURLConnection
I am currently developing an application that needs to interact with the server but i'm having a problem with receiving the data via POST. 我目前正在开发一个需要与服务器交互的应用程序,但我遇到了通过POST接收数据的问题。 I'm using Django and then what i'm receiving from the simple view is:
我正在使用Django,然后我从简单的视图中收到的是:
<QueryDict: {u'c\r\nlogin': [u'woo']}>
It should be {'login': 'woooow'} . 它应该是{'login':'woooow'} 。
The view is just: 视图只是:
def getDataByPost(request):
print '\n\n\n'
print request.POST
return HttpResponse('')
and what i did at the src file on sdk: 我在sdk上的src文件中做了什么:
URL url = new URL("http://192.168.0.148:8000/data_by_post");
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setDoInput(true);
urlConnection.setDoOutput(true);
urlConnection.setChunkedStreamingMode(0);
String parametros = "login=woooow";
urlConnection.setRequestMethod("POST");
urlConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
urlConnection.setRequestProperty("charset","utf-8");
urlConnection.setRequestProperty("Content-Length", "" + Integer.toString(parametros.getBytes().length));
OutputStream os = urlConnection.getOutputStream();
BufferedWriter writer = new BufferedWriter( new OutputStreamWriter(os, "UTF-8"));
writer.write(parametros);
writer.close();
os.close();
I changed the Content-Length to see if that was a problem and then the problem concerning thw value of login was fixed but it was by hard coding (which is not cool). 我更改了Content-Length以查看这是否是一个问题然后关于登录值的问题是固定的,但它是通过硬编码(这不是很酷)。
ps.: everything except the QueryDict is working well. ps:除了QueryDict之外的所有东西都运行良好。
What could i do to solve this? 我该怎么做才能解决这个问题? Am i encoding something wrong at my java code?
我的java代码编码错了吗? thanks!
谢谢!
Just got my problem solved with a few modifications concearning the parameters and also changed some other things. 刚刚通过一些修改解决了我的问题,并且还改变了一些其他的东西。
Having parameters
set as: parameters
设置为:
String parameters = "parameter1=" + URLEncoder.encode("SOMETHING","UTF-8");
then, under an AsyncTask: 然后,在AsyncTask下:
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setRequestMethod("POST");
//not using the .setRequestProperty to the length, but this, solves the problem that i've mentioned
conn.setFixedLengthStreamingMode(params.getBytes().length);
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
PrintWriter out = new PrintWriter(conn.getOutputStream());
out.print(params);
out.close();
String response = "";
Scanner inStream = new Scanner(conn.getInputStream());
while (inStream.hasNextLine()) {
response += (inStream.nextLine());
}
Then, with this, i got the result from django server: 然后,有了这个,我得到了django服务器的结果:
<QueryDict: {u'parameter1': [u'SOMETHING']}>
which is what i was wanting. 这就是我想要的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.