2013-05-17 127 views
1

真的有這個問題的問題。 下面的代碼假設發送到POST值(用戶名,密碼)到服務器,並且服務器應該只響應GET和POST的var_dump。Android HTTP發送不發送帖子

PHP代碼:

var_dump($_POST); 
var_dump($_GET); 

ANDROID CODE:

InputStream is = null; 

//http post 
try{ 
     HttpClient httpClient = new DefaultHttpClient(); 
     HttpPost httpPost = new HttpPost(url + "?test=test"); 
     httpPost.setHeader("Content-Type", "application/json"); 
     httpPost.setHeader("Accept", "application/json"); 

     // place them in an array list 
     ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(); 
     nameValuePairs.add(new BasicNameValuePair("username", "1123")); 
     nameValuePairs.add(new BasicNameValuePair("password", "123123")); 

     // add array list to http post 
     httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); 

     HttpResponse response = httpClient.execute(httpPost); 
     HttpEntity entity = response.getEntity(); 
     is = entity.getContent(); 

     Log.i("Network", "POST URL: " + url); 
     Log.i("Network", "POST ARGS: " + jsonObj.toString()); 

    } catch(Exception e){ 

     Log.e("Network", "POST Error in http connection " + e.toString()); 

    } 

但我得到的是:

array(0) { 
} 
array(1) { 
    ["test"]=> string(4) "test" 
} 

我已經測試了服務器與捲曲:捲曲-F「用戶名= test'http://xx.xx.xx.xx/test.php 它給了我正確的回報:

array(1) { 
    ["username"]=> string(9) "test" 
} 
array(0) { 
} 

那麼我在做什麼錯在android的帖子?

+0

你的數據顯然不是json。 'httpPost.setHeader(「Content-Type」,「application/json」)有什麼意義?''? – njzk2

回答

1

您不應將您的Content-Type標頭設置爲application/json。您可以不設置Content-Type標題或將其手動設置爲application/x-www-form-urlencoded

+0

啊,好吧,那有效。無論如何,我可以用ArrayList替代: StringEntity post_entity = new StringEntity(jsonObj.toString(),HTTP.UTF_8); httpPost.setEntity(post_entity); –

+0

,它不再是'NameValuePairs'的'POST'。所以請接受它,如果這是正確的答案。 –

+0

是的,這是NameValuePairs的正確答案,只是想知道你是否有'StringEntity(jsonObj.toString(),HTTP.UTF_8)'的解決方案;'通過任何改變? –