2010-03-29 12 views
23

Attualmente sto cercando di inviare alcuni dati da e un'applicazione Android a un server php (entrambi sono controllati da me).Android JSON HttpClient per inviare dati al server PHP con HttpResponse

C'è un sacco di dati raccolti su un modulo nell'app, questo è scritto nel database. Tutto funziona.

Nel mio codice principale, prima di tutto creare un JSONObject (ho tagliato verso il basso qui per questo esempio):

JSONObject j = new JSONObject(); 
j.put("engineer", "me"); 
j.put("date", "today"); 
j.put("fuel", "full"); 
j.put("car", "mine"); 
j.put("distance", "miles"); 

Poi ho passare l'oggetto sopra per l'invio, e ricevere la risposta:

String url = "http://www.server.com/thisfile.php"; 
HttpResponse re = HTTPPoster.doPost(url, j); 
String temp = EntityUtils.toString(re.getEntity()); 
if (temp.compareTo("SUCCESS")==0) 
{ 
    Toast.makeText(this, "Sending complete!", Toast.LENGTH_LONG).show(); 
} 

la classe HTTPPoster:

public static HttpResponse doPost(String url, JSONObject c) throws ClientProtocolException, IOException 
{ 
    HttpClient httpclient = new DefaultHttpClient(); 
    HttpPost request = new HttpPost(url); 
    HttpEntity entity; 
    StringEntity s = new StringEntity(c.toString()); 
    s.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json")); 
    entity = s; 
    request.setEntity(entity); 
    HttpResponse response; 
    response = httpclient.execute(request); 
    return response; 
} 

Questo ottiene una risposta, ma il server restituisce un 40 3 - Risposta vietata.

Ho provato a cambiare la funzione doPost un po '(in realtà è un po' meglio, come ho detto ho molto da inviare, in pratica 3 dello stesso modulo con dati diversi - quindi creo 3 JSONObjects, uno per ogni modulo voce - le voci provengono dal DB anziché dall'esempio statico che sto usando).

In primo luogo ho cambiato la chiamata per un po ':

String url = "http://www.myserver.com/ServiceMatalan.php"; 
Map<String, String> kvPairs = new HashMap<String, String>(); 
kvPairs.put("vehicle", j.toString()); 
// Normally I would pass two more JSONObjects..... 
HttpResponse re = HTTPPoster.doPost(url, kvPairs); 
String temp = EntityUtils.toString(re.getEntity()); 
if (temp.compareTo("SUCCESS")==0) 
{ 
    Toast.makeText(this, "Sending complete!", Toast.LENGTH_LONG).show(); 
} 

Ok, quindi le modifiche alla funzione di doPost:

public static HttpResponse doPost(String url, Map<String, String> kvPairs) throws ClientProtocolException, IOException 
{ 
    HttpClient httpclient = new DefaultHttpClient(); 
    HttpPost httppost = new HttpPost(url); 
    if (kvPairs != null && kvPairs.isEmpty() == false) 
    { 
     List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(kvPairs.size()); 
     String k, v; 
     Iterator<String> itKeys = kvPairs.keySet().iterator(); 
     while (itKeys.hasNext()) 
     { 
      k = itKeys.next(); 
      v = kvPairs.get(k); 
      nameValuePairs.add(new BasicNameValuePair(k, v)); 
     }    
     httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); 
    } 
    HttpResponse response; 
    response = httpclient.execute(httppost); 
    return response; 
} 

Ok Quindi questo restituisce una risposta 200

int statusCode = re.getStatusLine().getStatusCode(); 

Tuttavia, i dati ricevuti sul server non possono essere analizzati in una stringa JSON. Si è mal formattato Penso che (questa è la prima volta ho usato JSON):

Se nel file php che faccio un eco sui $ _POST [ 'veicolo'] ottengo il seguente:

{\"date\":\"today\",\"engineer\":\"me\"} 

Qualcuno può dirmi dove sto andando male, o se c'è un modo migliore per ottenere ciò che sto cercando di fare? Spero che quanto sopra abbia senso!

+0

Grazie per aver dedicato del tempo per documentare il problema con la risposta 403. Ho fatto la stessa cosa per una settimana e finalmente il tuo post mi ha spostato nella giusta direzione! –

+0

@Toran Billups non è un problema, sono contento che ti abbia aiutato !! – Scoobler

+0

Le tue variabili postano correttamente nello script PHP. Come si fa a tirare ogni variabile dire "ingegnere" e "carburante" e inserirli in un database MySQL per esempio. Sembra che tutto ciò che puoi fare sia usare la variabile '$ _POST ['vehicle'];'. Sarebbe molto gradito una risposta a questo. – WebDevDanno

risposta

11

Dopo molte letture e ricerche ho trovato il problema, credo che magic_quotes_gpc sia abilitato sul server.

Così, utilizzando:

json_decode(stripslashes($_POST['vehicle'])); 

Nel mio esempio sopra rimuove le barre e permette al JSON da decodificare correttamente.

Non si sa ancora perché l'invio di StringEntity causa un errore 403?

+0

ya è corretto! : D – gumuruh

+1

Potrebbe eventualmente condividere il file PHP che contiene 'json_decode' perché penso che il modo in cui il mio server decodifica i dati di JSON (erroneamente) possa essere correlato al tuo. – WebDevDanno

+0

json_decode (stripslashes ($ _ POST ['veicolo']), vero); restituirà php array, json_decode (stripslashes ($ _ POST ['vehicle'])); restituisce php stdclass obj, che è difficile da usare. +1 per la risposta corretta, thx –

0

Change

(String url = "http://www.server.com/MainPage.php";) 

a

(String url = "http://www.server.com/MainPage.php?";) 

Punto interrogativo alla fine è necessario quando si sta cercando di inviare i parametri di script PHP.

+3

Grazie a Sergey, ma sto usando un metodo POST per inviare i dati, non passando i parametri per GET dallo script PHP. – Scoobler

4
StringEntity s = new StringEntity(c.toString()); 
s.setContentEncoding("UTF-8"); 
s.setContentType("application/json"); 
request.setEntity(s); 
1

Prova questo codice funziona per me

public void postData(String result,JSONObject obj) { 
// Create a new HttpClient and Post Header 
HttpClient httpclient = new DefaultHttpClient(); 
HttpParams myParams = new BasicHttpParams(); 
HttpConnectionParams.setConnectionTimeout(myParams, 10000); 
HttpConnectionParams.setSoTimeout(myParams, 10000); 

String json=obj.toString(); 

try { 

    HttpPost httppost = new HttpPost(result.toString()); 
    httppost.setHeader("Content-type", "application/json"); 

    StringEntity se = new StringEntity(obj.toString()); 
    se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json")); 
    httppost.setEntity(se); 

    HttpResponse response = httpclient.execute(httppost); 
    String temp = EntityUtils.toString(response.getEntity()); 
    Log.i("tag", temp); 


} catch (ClientProtocolException e) { 

} catch (IOException e) { 
} 

}

0

Prova questo codice funziona perfettamente

*For HttpClient class* download jar file "httpclient-4.3.6.jar" and put in libs folder then 
 
Compile: dependencies {compile files('libs/httpclient-4.3.6.jar')} 
 

 
repositories { 
 
     maven { 
 
      url "https://jitpack.io" 
 
     } 
 
    }

quindi chiamare classe HttpClient questo AsyncTask Ti piace questa:

classe privata YourTask estende AsyncTask { String error_msg privato = "Errore di Server";

private JSONObject response; 



    @Override 
    protected Boolean doInBackground(String... params) { 
     try { 
      JSONObject mJsonObject = new JSONObject(); 
      mJsonObject.put("user_id", "user name"); 
      mJsonObject.put("password", "123456"); 
      String URL=" Your Link" 

      //Log.e("Send Obj:", mJsonObject.toString()); 

      response = HttpClient.SendHttpPost(URL, mJsonObject); 
      boolean status = response != null && response.getInt("is_error") == 0; // response 

      return status; 
     } catch (JSONException | NullPointerException e) { 
      e.printStackTrace(); 
      mDialog.dismiss(); 
      return false; 
     } 
    } 

    @Override 
    protected void onPostExecute(Boolean status) { 
     // your code 

    } 
} 
Problemi correlati