【问题标题】:Android HttpPost does not workAndroid HttpPost 不起作用
【发布时间】:2013-03-06 17:18:11
【问题描述】:

我正在尝试创建一个使用 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()
{

}

}

那么这里是与将数据插入数据库相关的.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);
}
?>

你能帮我解决什么问题吗?我做的方式是正确的还是我错过了什么? 谢谢。

【问题讨论】:

  • LogCat 说没有错误。
  • 你是否在清单文件中添加了互联网权限??
  • 是的,“”。
  • 我认为您需要将 http 代码放入 asyncTask 中,但奇怪的是 logCat 说没有错误...
  • 我没有说什么。因此,您说要放置一个带有 String doInBackground 的 AsyncTask 并插入该指令?也许像这样? androidhive.info/2012/05/how-to-connect-android-with-php-mysql

标签: php android json get


【解决方案1】:

也许这段代码可以提供帮助。

获取

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.
    }
}

}

剩下的由你来做 ;)

希望对你有帮助,

亲切的问候

【讨论】:

  • 嗨,谢谢你的回复,但我有一些问题: - 我可以在没有 AsyncTask 的情况下实现这些示例还是需要它们? - 就像我看到的,我只需要插入我的 url 和我的 ArrayList,你称之为 params,对吧?
  • 不,您必须基于线程/异步任务执行此操作。否则你会得到一个 networkOnMainThreadException 或类似的东西
  • 所以它就像我在示例中所做的那样正确,对吧?感谢您的耐心等待。
  • 尝试在这之间包装你的代码: new Thread(new Runnable() { @Override public void run() { //要更改已实现方法的主体,请使用 File | Settings | File Templates. } }) .start();
  • 看到了,所以使用获取/发布示例到您的线程示例根据我的需要进行修改,对吧?谢谢。
【解决方案2】:

请使用此代码

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

瞬间

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

谢谢

【讨论】:

  • 2 引用我的 List 的最大大小或每个索引可以有多少项?
猜你喜欢
  • 2023-03-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-02-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多