简体   繁体   中英

Android: connect httpURLConnection to the server

I want to send JSON string to the server every 60 seconds with HttpURLConnection API. I am running the app on my smartphone device, which is connected to the laptop via USB cable. With this URL http://zzzzz.byethost8.com/connection.php I am getting the code 500 as output of getResponseCode() . I even tried it with the wamp server, but I am not getting any output there.

For WAMP I used this URL: http://192.168.134.45/connection.php where 192.168.134.45 is my Wi-Fi IP address.

JSON String:

{
    "latitude":80.86898504,
    "longitude":20.66561187,
    "time":"26.04.2015 12:45:11",
    "route":4
}

The implementation of doInBackground() method:

protected Void doInBackground(String... params) {
    // TODO Auto-generated method stub

    try {
        System.out.println("The output of : doInBackground " +params[0]);

        //URL myUrl = new URL("http://byethost8.com/connection.php");
        URL myUrl = new URL("http://192.168.182.15/connection.php");
        HttpURLConnection conn = (HttpURLConnection) myUrl.openConnection();
        conn.setRequestMethod("POST");
        conn.setDoOutput(true);
        conn.setConnectTimeout(10000);
        conn.setReadTimeout(10000);
        conn.setRequestProperty("Content-Type", "application/json");
        System.out.println("The output of getResponsecode: "+conn.getResponseCode());
        conn.connect();
        // create data output stream
        DataOutputStream wr = new DataOutputStream(conn.getOutputStream());
        // write to the output stream from the string
        wr.writeBytes(params[0]);
        wr.close();

    } catch (IOException e) {

        e.printStackTrace();
    }
    return null;

}

PHP connection file with the default WAMP setting.

<?php
 $json = json_decode(file_get_contents('php://input', true));

 //hotname-username-password-datebase.
 $db = new mysqli("sql209.byethost8.com", "b8_16138121", "fadi88", "b8_16138121_busTracker");  
 echo "You are in!";
 if ($db->connect_errno) {
    die("We are sorry, you could not be connected to the server,
        please check your connection setting!");
 }
?>

I'm developing an application which interfaces with a server using json for sending and receiving data and the I'm currently using ion library for network operations instead of creating a task asynchronously etc.. Here a sample code:

Android implementation (you don't need to create an async task):

JsonObject jsonObject = new JsonObject();
jsonObject.addProperty("metodo", "inserisciLuogo");
jsonObject.addProperty("latitudine", latitudine);
jsonObject.addProperty("longitudine", longitudine);
jsonObject.addProperty("nome", nome);
jsonObject.addProperty("indirizzo", indirizzo);
jsonObject.addProperty("Utente_idUtente", Utils.getUserID(getApplicationContext()));

Log.e(TAG, jsonObject.toString());

Ion.with(getApplicationContext())
        .load(URL)
        .setJsonObjectBody(jsonObject)
        .asJsonObject()
        .setCallback(new FutureCallback<JsonObject>() {
            @Override
            public void onCompleted(Exception e, JsonObject result) {
                if (result != null) {
                    Boolean risultato = result.get("risultato").getAsString().equals("1");
                    Log.e(TAG, risultato.toString());
                    if(risultato)
                        Toast.makeText(getApplicationContext(), getString(R.string.place_added), Toast.LENGTH_LONG).show();
                     else
                        Toast.makeText(getApplicationContext(), getString(R.string.place_add_error), Toast.LENGTH_LONG).show();
                 }
                 else
                    Toast.makeText(getApplication(), getString(R.string.error_no_server), Toast.LENGTH_LONG).show();
                }
            });

And php implementation:

$json = json_decode(file_get_contents('php://input'), true);
$conn = new PDO("mysql:host=$dbhost;dbname=$dbname",$dbuser,$dbpass);
if($json['metodo'] == "inserisciLuogo"){

    $latitudine = $json['latitudine'];
    $longitudine = $json['longitudine'];
    $nome = $json['nome'];
    $indirizzo = $json['indirizzo'];
    $Utente_idUtente = $json['Utente_idUtente'];

    $sql = "INSERT INTO luogo (latitudine, longitudine, nome, indirizzo, Utente_idUtente)
        VALUES (:latitudine, :longitudine, :nome, :indirizzo, :Utente_idUtente)";
    $query = $conn->prepare($sql);
    $query->bindParam(':latitudine', $latitudine, PDO::PARAM_STR);
    $query->bindParam(':longitudine', $longitudine, PDO::PARAM_STR);
    $query->bindParam(':nome', $nome, PDO::PARAM_STR);
    $query->bindParam(':indirizzo', $indirizzo, PDO::PARAM_STR);
    $query->bindParam(':Utente_idUtente', $Utente_idUtente, PDO::PARAM_STR);

    $result = $query->execute();

    if($result)
        echo json_encode(array('risultato' => "1"));
    else
        echo $query->errorCode();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM