Android: 将 httpURLConnection 连接到服务器

Android: connect httpURLConnection to the server

我想用 HttpURLConnection API 每 60 秒向服务器发送 JSON 字符串。我是 运行 我的智能手机设备上的应用程序,它通过 USB 数据线连接到笔记本电脑。使用此 URL http://zzzzz.byethost8.com/connection.php 我得到代码 500 作为 getResponseCode() 的输出。我什至在 wamp 服务器上尝试过,但我在那里没有得到任何输出。

对于 WAMP,我使用了这个 URL:http://192.168.134.45/connection.php 其中 192.168.134.45 是我的 Wi-Fi IP 地址。

JSON 字符串:

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

doInBackground()方法的实现:

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 使用默认 WAMP 设置的连接文件。

<?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!");
 }
?>

我正在开发一个应用程序,该应用程序使用 json 与服务器交互以发送和接收数据,我目前正在使用 ion 库用于网络操作而不是异步创建任务等。 这里有一个示例代码:

Android实现(不需要创建异步任务):

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();
                }
            });

和php实施:

$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();
}