java - Android:将 httpURLConnection 连接到服务器

标签 java php android json httpurlconnection

我想使用 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;

}

具有默认 WAMP 设置的 PHP 连接文件。

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

关于java - Android:将 httpURLConnection 连接到服务器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29876775/

相关文章:

java - 当 onCreate 中完成某些操作(不是声明或初始化)但 onClick 中未完成某些操作时,应用程序崩溃

java - 持久性提供者密码困境

php - 条件语句中的 !preg_match() 函数始终为 false

android - 通过 ConstraintLayout 在两个维度上使用比率来显示 3 个相同大小的正方形

java - 如何使用存储库和 View 模型更新房间数据库中的字段

android - 在 Android 中解锁设备屏幕时启动服务

java - GUI等待键盘 "enter"并继续显示

java - 如何从 Java 中的字符串中删除\u200B(零长度空白 Unicode 字符)?

php - 如何编辑 PHP.ini 文件。我尝试了很多,但未能在我的域上找到基于 Linux 的 Web 服务器

php - wordpress如何存储wp_usermeta?