0

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

package com.example.database;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicHeader;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.protocol.HTTP;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.os.Looper;
import android.util.Log;
import android.widget.Toast;

public class post extends Activity{

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    postData();
}


public void postData() {
    // Create a new HttpClient and Post Header
    HttpClient httpclient = new DefaultHttpClient();

    HttpPost httppost = new HttpPost("http://192.168.83.1/test.php");

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

        // Execute HTTP Post Request
        ResponseHandler<String> responseHandler=new BasicResponseHandler();

        String responseBody = httpclient.execute(httppost, responseHandler);
        Log.d("test", responseBody); 
       // Toast.makeText(getApplicationContext(), responseBody, Toast.LENGTH_LONG).show();

    } catch (ClientProtocolException e) {
        // TODO Auto-generated catch block
    } catch (IOException e) {
        // TODO Auto-generated catch block
    }
} 

文件test.php的内容是:

 <?php

echo"works";

?>

Log.d("test", responseBody); 标签不会出现在 LogCat 上。但是,如果我将其向上移动几行(在 responseBody 之前)并放置一段静态文本,它确实有效

HTTPRequest 有问题吗?怎么可能解决

谢谢 !

4

1 回答 1

6

删除 BasicResponseHandler 后尝试。它应该工作。并签入 Menifest 以获得 perticuler 许可

HttpResponse response = httpclient.execute(httppost);
String responseBody = EntityUtils.toString(response.getEntity()); 
于 2013-03-22T12:05:06.213 回答