无法获取httpPost参数,但可以从php获取httpGet

时间:2012-07-06 03:11:22

标签: android

这是我发送请求的android代码:

// 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。这是对的!!
我已经尝试了很多时间,但似乎无法发送带有参数的HttpPost请求 任何人都可以帮我找出我的代码有什么错误吗?

1 个答案:

答案 0 :(得分: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;
}