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!
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! –
@Toran Billups non è un problema, sono contento che ti abbia aiutato !! – Scoobler
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