2

这是我发送请求的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 请求。
任何人都可以帮助我找出我的代码有什么问题?

4

1 回答 1

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;
}
于 2012-07-06T04:45:57.553 回答