2012-07-06 36 views
2

这里是我的Android代码发送请求:无法从PHP获得httpPost PARAMS,但可以得到HTTPGET

// defaultHttpClient 
DefaultHttpClient httpClient = new DefaultHttpClient(); 
HttpPost httpPost = new HttpPost(serverUrl); 
List<NameValuePair> params = new ArrayList<NameValuePair>(); 
params.add(new BasicNameValuePair("abc", "abc2")); 
httpPost.setEntity(new UrlEncodedFormEntity(params)); 
HttpResponse httpResponse = httpClient.execute(httpPost); 
HttpEntity httpEntity = httpResponse.getEntity(); 
InputStream is = null; 
is = httpEntity.getContent(); 
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"), 8); 
StringBuilder sb = new StringBuilder(); 
String line = null; 
while ((line = reader.readLine()) != null) { 
    sb.append(line + "\n"); 
} 
is.close(); 
String json = ""; 
json = sb.toString(); 
Log.d("JSON", "JSON is:" + json); 

,这里是我的PHP代码,以获得请求:

<?php 

echo $_POST['abc']; 

?> 

当我运行应用程序,字符串json什么也没有。我希望得到JSON is:abc2
然后我改变了一些代码,在Android部分:

HttpPost httpPost = new HttpPost(serverUrl); 

变化:

HttpPost httpPost = new HttpPost(serverUrl + "?abc=abc3"); 

在PHP部分:

<?php 

echo $_GET['abc']; 

?> 

这一次,在logcat中的字符串jsonJSON is:abc3。它是正确的!!
我已经尝试了很多时间,但似乎不能用params发送HttpPost请求。
任何人都可以帮助我找出与我的代码错误?

回答

0

试试这个代码

HttpParams httpParameters = new BasicHttpParams(); 
HttpConnectionParams.setConnectionTimeout(httpParameters, 5000); 
HttpConnectionParams.setSoTimeout(httpParameters, 5000); 

DefaultHttpClient httpclient = new DefaultHttpClient(httpParameters); 
HttpPost httppost = new HttpPost(serverUrl); 

try { 
    // Add your data 
    List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2); 
    nameValuePairs.add(new BasicNameValuePair("abc", "abc2")); 
    httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); 

    // Execute HTTP Post Request 
    HttpResponse response = httpclient.execute(httppost); 
    nameValuePairs.clear(); 
    nameValuePairs = null; 

    HttpEntity httpEntity = response.getEntity(); 
    response = null; 
    Log.e("Server Response",EntityUtils.toString(httpEntity)); 
} catch (IOException e) { 
    Log.e("IOException", " IOException "); 
    e.printStackTrace(); 
} catch (Exception e){ 
    Log.e("Exception", " Exception "); 
    e.printStackTrace(); 
} finally { 
    httpParameters = null; 
    httppost = null; 
}