2013-07-27 105 views
1

我目前正在開發一個需要與服務器交互的應用程序,但我在通過POST接收數據時遇到問題。我使用Django,然後就是我從簡單的觀點是接受:Android發佈UTF-8 HttpURLConnection

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

應該 {「登錄」:「woooow」}

的觀點就是:

def getDataByPost(request): 
    print '\n\n\n' 
    print request.POST  
    return HttpResponse('') 

和我做了什麼,在上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(); 

我改變了內容長度,看看這是一個問題,然後關於登錄價值的問題是固定的,但它是通過硬編碼(這不是很酷)。

ps .:除了QueryDict以外的所有東西都運行良好。

我能做些什麼來解決這個問題?我在我的java代碼中編碼錯了嗎? 謝謝!

+0

嘗試刪除'Content-Type'並告訴我們會發生什麼情況:D –

+0

它返回了相同的結果:( –

回答

4

剛剛得到了我的問題解決了幾個修改瞭解參數,還改變了一些其他的東西。

parameters設置爲:

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

然後,一個的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()); 
} 

然後,有了這個,我得到了來自Django的服務器結果:

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

這是我想要的。

+1

我知道這是一箇舊帖子,但您應該添加inStream.close()以防止資源泄漏。 – Mgamerz

相關問題