1

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. I'm using Django and then what i'm receiving from the simple view is:

<QueryDict: {u'c\r\nlogin': [u'woo']}>

It should be {'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:

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).

ps.: everything except the QueryDict is working well.

What could i do to solve this? Am i encoding something wrong at my java code? thanks!

Ciro Costa
  • 2,455
  • 22
  • 25

1 Answers1

4

Just got my problem solved with a few modifications concearning the parameters and also changed some other things.

Having parameters set as:

String parameters = "parameter1=" + URLEncoder.encode("SOMETHING","UTF-8");

then, under an 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:

<QueryDict: {u'parameter1': [u'SOMETHING']}>

which is what i was wanting.

Ciro Costa
  • 2,455
  • 22
  • 25