Domanda

Al momento sto cercando di inviare alcuni dati da e applicazioni Android a un server php (entrambe sono controllate da me).

C'è un sacco di dati raccolti su un modulo nella app, questo è scritto nel database. Questa tutte le opere.

Nel mio codice principale, in primo luogo a 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");

Avanti passo 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 403 -. La risposta Forbidden

Ho provato a cambiare la funzione doPost un po '(questo è in realtà un po' meglio, come ho detto ho molto da trasmettere, in pratica 3 dello stesso modulo con dati diversi - così creo 3 JSONObjects, uno per ogni voce modulo - le voci provengono dal DB invece dell'esempio statica 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 può essere analizzato 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 quello che sto cercando di fare? Speriamo che quanto sopra ha un senso!

È stato utile?

Soluzione

Dopo un sacco di lettura e di ricerca ho trovato il problema di essere con, ho beleive magic_quotes_gpc essere abilitato sul server.

In questo modo, utilizzando:

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

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

Ancora non so perché l'invio di uno StringEntity causa un errore 403?

Altri suggerimenti

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

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) {
}

}

Cambia

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

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 HttpClient classe questa AsyncTask Ti piace questa:

classe privata YourTask estende AsyncTask {         String error_msg privato = "Errore del 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

    }
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top