安卓:HttpURLConnection类连接到服务器 [英] Android: connect httpURLConnection to the server

查看:314
本文介绍了安卓:HttpURLConnection类连接到服务器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想JSON字符串发送到服务器每隔60秒 HttpURLConnection类 API。我正在我的智能手机设备,该设备通过USB线连接到笔记本电脑上的应用程序。有了这个网址 http://zzzzz.byethost8.com/connection.php 我收到code 500 GETRESPONSE code()。我甚至与WAMP服务器尝试过,但我没有得到任何输出那里。

有关WAMP我用这个网址: http://192.168.134.45/connection.php ,其中 192.168.134.45 是我的Wi-Fi IP地址。

JSON字符串:

  {
    纬度:80.86898504,
    东经:20.66561187,
    时代:2015年4月26日十二时45分11秒,
    路线:4
}

的实施 doInBackground()方法:

 保护无效doInBackground(字符串... PARAMS){
    // TODO自动生成方法存根    尝试{
        的System.out.println(的输出:doInBackground+ PARAMS [0]);        // URL myUrl =新的URL(http://byethost8.com/connection.php);
        网址myUrl =新的URL(http://192.168.182.15/connection.php);
        HttpURLConnection的康恩=(HttpURLConnection类)myUrl.openConnection();
        conn.setRequestMethod(POST);
        conn.setDoOutput(真);
        conn.setConnectTimeout(10000);
        conn.setReadTimeout(10000);
        conn.setRequestProperty(内容类型,应用/ JSON);
        的System.out.println(GETRESPONSE code的输出:+ conn.getResponse code());
        conn.connect();
        //创建数据输出流
        DataOutputStream类WR =新的DataOutputStream类(conn.getOutputStream());
        //写入字符串中的输出流
        wr.writeBytes(PARAMS [0]);
        wr.close();    }赶上(IOException异常五){        e.printStackTrace();
    }
    返回null;}

PHP连接文件的默认设置WAMP

 < PHP
 $ JSON = json_de code(的file_get_contents('PHP://输入',真)); // hotname - 用户名 - 密码DATEBASE。
 $分贝=新mysqli的(sql209.byethost8.com,b8_16138121,fadi88,b8_16138121_busTracker);
 回声你在!
 如果($ DB-GT&; connect_errno){
    模具(很抱歉,您不能连接到服务器,
        请检查您的网络连接设置)!;
 }
?>


解决方案

我正在开发它使用JSON用于发送和接收的数据与服务器接口的应用程序和我目前使用的离子 库实现网络操作,而不是异步创建任务等。
下面的示例code:

Android的执行(你并不需要创建一个异步任务):

 的JSONObject的JSONObject =新的JSONObject();
jsonObject.addProperty(方法方法,inserisciLuogo);
jsonObject.addProperty(latitudine,latitudine);
jsonObject.addProperty(longitudine,longitudine);
jsonObject.addProperty(诺姆,诺姆);
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(新FutureCallback<&JSONObject的GT;(){
            @覆盖
            公共无效onCompleted(例外五,结果的JSONObject){
                如果(结果!= NULL){
                    布尔risultato = result.get(risultato)符getAsString()等于(1)。;
                    Log.e(TAG,risultato.toString());
                    如果(risultato)
                        Toast.makeText(getApplicationContext(),的getString(R.string.place_added),Toast.LENGTH_LONG).show();
                     其他
                        Toast.makeText(getApplicationContext(),的getString(R.string.place_add_error),Toast.LENGTH_LONG).show();
                 }
                 其他
                    Toast.makeText(getApplication(),的getString(R.string.error_no_server),Toast.LENGTH_LONG).show();
                }
            });

和PHP实现:

  $ JSON = json_de code(的file_get_contents('PHP://输入'),TRUE);
康涅狄格州$ =新PDO(MySQL的:主机= $ DBHOST; DBNAME = $ DBNAME,$ DBUSER,$ DBPASS);
如果($ json的['方法方法'] ==inserisciLuogo){    $ latitudine = $ json的['latitudine'];
    $ longitudine = $ json的['longitudine'];
    $诺姆= $ json的['诺姆'];
    $ indirizzo = $ json的['indirizzo'];
    $ Utente_idUtente = $ json的['Utente_idUtente'];    $ SQL =INSERT INTO luogo(latitudine,longitudine,诺姆,indirizzo,Utente_idUtente)
        VALUES(:latitudine,:longitudine,:诺姆,:indirizzo,:Utente_idUtente);
    $查询= $ conn-> prepare($的SQL);
    $查询 - > bindParam(':latitudine',$ latitudine,PDO :: PARAM_STR);
    $查询 - > bindParam(':longitudine',$ longitudine,PDO :: PARAM_STR);
    $查询 - > bindParam(':诺姆',$诺姆,PDO :: PARAM_STR);
    $查询 - > bindParam(':indirizzo',$ indirizzo,PDO :: PARAM_STR);
    $查询 - > bindParam(':Utente_idUtente',$ Utente_idUtente,PDO :: PARAM_STR);    $结果= $查询 - >执行();    如果($结果)
        回声json_en code(阵列('risultato'=>中1));
    其他
        回声$查询 - >错误code();
}

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

这篇关于安卓:HttpURLConnection类连接到服务器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆