Android HttpPost不起作用

时间:2013-03-06 17:18:12

标签: php android json get

我正在尝试创建一个使用WAMP服务器将数据发送到远程数据库的应用程序。我面临的问题是没有人出现:没有数据被发送并且没有显示logcat错误,我也无法插入Toast来查看应用程序是否进入代码的特定部分,因为Eclipse在运行时将其显示为错误模式。

所以,这里是.java代码:

public class AggiungiProdotto extends Activity 
{
    private static String indirizzo ="http://10.0.2.2/tesina/Aggiungi_Ordinazione";

@Override
public void onCreate(Bundle savedInstanceState) 
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.aggiungi_prodotto);
    new AggiungoOrdinazione().execute();

}

private class AggiungoOrdinazione extends AsyncTask<String, Void, String>
{

    @Override
    protected void onPreExecute() 
    {
        super.onPreExecute();
    }

    @Override
    protected String doInBackground(String... arg0) 
    {
        InputStream is = null;
        String result = "";
        JSONObject jsonResult = null;
        TextView tv;

        Intent intent = getIntent();
        String Nome = new String();

        String Tavolo = intent.getStringExtra("Tavolo");
        Nome = "ciao";

        HttpPost httppost = new HttpPost(indirizzo);  

        HttpParams httpParams = new BasicHttpParams();

        int timeOutConnection = 5000;
        HttpConnectionParams.setConnectionTimeout(httpParams, timeOutConnection);
        int timeoutSocket = 5000;
        HttpConnectionParams.setSoTimeout(httpParams, timeoutSocket);
        HttpClient httpclient = new DefaultHttpClient(httpParams);

        List<NameValuePair> Comanda = new ArrayList<NameValuePair>();
        Comanda.add(new BasicNameValuePair("Nome", Nome ));
        Comanda.add(new BasicNameValuePair("Tavolo", Tavolo));


        try 
        {
            httppost.setEntity(new UrlEncodedFormEntity(Comanda));
            HttpResponse response = httpclient.execute(httppost);
            HttpEntity entity = response.getEntity();
            is = entity.getContent();

            BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));

            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
            is.close();
            result = sb.toString();
            jsonResult = new JSONObject(result);



        }
        catch (UnsupportedEncodingException e) 
        {
            e.printStackTrace();
        } 
        catch (ClientProtocolException e)
        {
            e.printStackTrace();
        } 
        catch (IOException e) 
        {
            e.printStackTrace();
        } 
        catch (JSONException e) 
        {
            e.printStackTrace();
        }   

        return null;
    }

}

protected void onPostExecute()
{

}

}

然后,这里是与插入数据到db:

相关的.PHP代码
<?php


// Dichiaro una array nel quale inserirò la risposta in JSON
$response = array();

/* La funzione isset controlla se all'interno della variabile esiste un dato diverso da null.
$_POST è una funzione che inserisce i dati passati attraverso un metodo POST alla variabile seguente. */

if (isset($_POST['Nome']) && isset($_POST['Tavolo'])) 
{

    $Nome = $_POST['Nome'];
    $Tavolo = $_POST['Tavolo'];

    // Includo la classe per la connessione al database
    require_once __DIR__ . '/connessione_db.php';

    // Da file incluso posso istanziare un oggetto della clase
    $db = new DB_CONNECT();

    // Query in mySQL Per creare una riga i cui campi hanno i valori passati dall'applicazione.
    $result = mysql_query("INSERT INTO pizze(Nome, Tavolo) VALUES('$Nome', '$Tavolo')");

    // Controllo se la riga è stata inserita oppure no.
    if ($result) 
    {

        $response["Stato"] = 1;
        $response["Messaggio"] = "Dati inseriti!";

       // echo in PHP che mi converte il risultato in JSON e la mette nella variabile response.
        echo json_encode($response);
    }
    else 
    {

        $response["success"] = 0;
        $response["message"] = "Dati non inseriti!";

        // Converto anche qui.
        echo json_encode($response);
    }
} else 
{
    $response["success"] = 0;
    $response["message"] = "Campo richiesto mancante!";

    // Converto.
    echo json_encode($response);
}
?>
你能帮我解决什么问题吗?是我正确的方式还是我错过了什么? 谢谢。

2 个答案:

答案 0 :(得分:1)

Maby这段代码可以提供帮助。

获取

InputStream is = null;
    String result = "";
    JSONObject jsonResult = null;

    HttpGet httppost = new HttpGet(url);    
    HttpParams httpParams = new BasicHttpParams();
    int timeOutConnection = 5000;
    HttpConnectionParams.setConnectionTimeout(httpParams, timeOutConnection);
    int timeoutSocket = 5000;
    HttpConnectionParams.setSoTimeout(httpParams, timeoutSocket);
    HttpClient httpclient = new DefaultHttpClient(httpParams);



    HttpResponse response = httpclient.execute(httppost);
    HttpEntity entity = response.getEntity();
    is = entity.getContent();

    BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));     

    StringBuilder sb = new StringBuilder();

    String line = null;
    while ((line = reader.readLine()) != null) {
        sb.append(line + "\n");
    }
    is.close();
    result = sb.toString();
    jsonResult = new JSONObject(result);

发表

        InputStream is = null;
    String result = "";
    JSONObject jsonResult = null;

    HttpPost httppost = new HttpPost(url);  
    //httppost.addHeader("content-type", "application/json");
    //httppost.addHeader("User-Agent", userAgent);
    HttpParams httpParams = new BasicHttpParams();

    int timeOutConnection = 5000;
    HttpConnectionParams.setConnectionTimeout(httpParams, timeOutConnection);
    int timeoutSocket = 5000;
    HttpConnectionParams.setSoTimeout(httpParams, timeoutSocket);
    HttpClient httpclient = new DefaultHttpClient(httpParams);


    httppost.setEntity(new UrlEncodedFormEntity(params));   

    HttpResponse response = httpclient.execute(httppost);
    HttpEntity entity = response.getEntity();
    is = entity.getContent();

    BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));

    StringBuilder sb = new StringBuilder();
    String line = null;
    while ((line = reader.readLine()) != null) {
        sb.append(line + "\n");
    }
    is.close();
    result = sb.toString();
    jsonResult = new JSONObject(result);

<强>更新

尝试将代码包装在此

new Thread(new Runnable() {
            @Override
            public void run() {
                //To change body of implemented methods use File | Settings | File Templates.
            }
        }).start();

但我强烈建议学习使用Asynctask,它使它更容易和更稳定。 关于如何使用它们的网上有很多很好的例子

使用此代码作为参考,并根据您的需要进行修改。 我相信这是有效的,因为我们始终使用这种代码的和平。

修改

下面我用Asynctask的子类

写了一个非常简单的活动
public class AsyncTaskExample extends Activity {

private String url;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    url = "http://google.com";

    new WebCall().execute();
}

class WebCall extends AsyncTask<String, Void, String> {

    @Override
    protected String doInBackground(String... params) {

        InputStream is = null;
        String result = "";
        JSONObject jsonResult = null;

        HttpPost httppost = new HttpPost(url);
        //httppost.addHeader("content-type", "application/json");
        //httppost.addHeader("User-Agent", userAgent);
        HttpParams httpParams = new BasicHttpParams();

        int timeOutConnection = 5000;
        HttpConnectionParams.setConnectionTimeout(httpParams, timeOutConnection);
        int timeoutSocket = 5000;
        HttpConnectionParams.setSoTimeout(httpParams, timeoutSocket);
        HttpClient httpclient = new DefaultHttpClient(httpParams);


        httppost.setEntity(new UrlEncodedFormEntity(params));

        HttpResponse response = httpclient.execute(httppost);
        HttpEntity entity = response.getEntity();
        is = entity.getContent();

        BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));

        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }
        is.close();
        result = sb.toString();
        jsonResult = new JSONObject(result);
        return null;
    }

    @Override
    protected void onPostExecute(String s) {
        super.onPostExecute(s);
        // this method gets called when doInBackground is ready with processing.

        // onPostExecute is also returend on the UIThread. and doInbackground is not.
        // so you cant setText or something else what involves UI components in the doInbackground.
    }
}

}

由你来做其余的事情;)

希望它有所帮助,

亲切的问候

答案 1 :(得分:0)

请使用此代码

List<NameValuePair> Parametri = new ArrayList<NameValuePair>(2);

瞬间

List<NameValuePair> Parametri = new ArrayList<NameValuePair>();

由于