将android phonegap应用程序连接到模拟器中的localhost

时间:2013-03-26 12:59:51

标签: android connection localhost

希望你们能帮助我。我对phonegap相对比较新。我已经开始了一个星期+现在关于这个问题。我在C#中有一个dbase wcf rest服务,并且已经构建了一个Android客户端来调用这个服务。当我在wp7中测试这个应用程序时,似乎一切正常工作,即以json格式调用此服务。但是当我将这个应用程序迁移到eclipse android环境并配置相关设置时,即使我将url:http //:localhost:1067 / Service1更改为http //:10.0.2.2:1067/Service1后,应用程序也无法成功运行。我还在使用我已修改为以下

的演示应用程序

的index.html

<!doctype html>
<html>
<head>
    <meta name="viewport" content="width=320 user-scalable=no" />
    <meta http-equiv="Content-type" content="text/html; charset=utf-8"/>
    <title>PhoneGap WP7</title>
    <link rel="stylesheet" href="master.css" type="text/css" media="screen" title="no title" charset="utf-8" />
    <script type="text/javascript" charset="utf-8" src="jquery-1.7.2.min.js"></script>
    <script type="text/javascript" charset="utf-8" src="console.js"></script>
    <script type="text/javascript" charset="utf-8" src="cordova-1.7.0.js"></script>
    <script type="text/javascript" charset="utf-8" src="init.js"></script>

</head>
<body>
  <div>
    <h1 id="welcomeMsg">Welcome</h1>
    <p><a href="#" onclick="login(); return false;">log in</a></p>
    <p><a href="#" onclick="getAjax(); return false;">Get Ajax</a></p>
    <p><a href="#" onclick="postAjax(); return false;">Post Ajax</a></p>
    <p><a href="#" onclick="getSingle(); return false;">Get Single Item</a></p>
    <p><a href="#" onclick="deleteSingle(); return false;">Delete</a></p>
    <p><a href="#" onclick="updateSingle(); return false;">Update</a></p>
    <p><a href="#" onclick="identify(); return false;">Identify</a></p>
    <p><a href="#" onclick="logViaForm(); return false;">Log via Form</a></p>
    <p><a href="#" onclick="logout(); return false;">log out</a></p>

    <p id="errorMessage" class="err"></p>
    <p id="loginCall"></p>
    <p id="ajaxCall"></p>
    <p id="postAjaxCall"></p>
    <p id="getSingleCall"></p>
    <p id="deleteSingleCall"></p>
    <p id="updateSingleCall"></p>
    <p id="identifyCall"></p>
    <p id="logViaFormCall"></p>
    <p id="logoutCall"></p>
    <input type="text" id="myTest" value="1" name="myTest" />
    </div>
   </body>
</html>

和init.js

$(document).ready(function () {
    document.addEventListener("deviceready", onDeviceReady, false);
    jQuery.support.cors = true; //Cross-Origin Resource Sharing
});

// phonegap is initialised
function onDeviceReady() {
    $("#welcomeMsg").append("...Ready");
}

function showAlert(msg) {
    navigator.notification.alert(
                    msg, // message
                    alertDismissed, // callback
                    'Alert', // title
                    'Done'  // buttonName
                    );
}

function showError(error, otherInfo) {
    var element = document.getElementById('errorMessage');
    element.innerHTML = "Errors: " + error.Message + "<br>" + (otherInfo ? otherInfo : "");
}

function getAjax() {
    var jqxhr = $.ajax({
        url: 'http://10.0.2.2/estatewcf/Service1/',
        type: 'GET',
        //headers:
        beforeSend: function (xhr) {
            //xhr.overrideMimeType('text/plain; charset=x-user-defined');
        },
        dataType: 'json',
        contentType: 'application/json; charset=utf-8',
        data: '{ "Idi":5, "Type": "mike" }'
    })
    .done(function (data) {
        var element = document.getElementById('ajaxCall');
        element.innerHTML = JSON.stringify(data, null, "\t");
    })
     .fail(function (xhr, status, error) {
         showError(error);
     })
     .always(function () { showAlert("complete"); });
 }


function postAjax(parameters) {
    var jqxhr = $.ajax({
        url: 'http://10.0.2.2/estatewcf/Service1/',
        type: 'POST',
        //headers:
        //beforeSend: function (xhr) {
        //},
        dataType: 'json',
        contentType: 'application/json; charset=utf-8',
        data: '{ "Id":5, "StringValue": "jerry 22" }'
    })
    .done(function (data) {
        var element = document.getElementById('postAjaxCall');
        element.innerHTML = JSON.stringify(data, null, "\t");
    })
     .fail(function (xhr, status, error) { showError(error); })
     .always(function () { showAlert("complete"); });
}

function login() {
    var jqxhr = $.ajax({
        url: 'http://10.0.2.2/estatewcf/login/',
        type: 'POST',
        //headers:
        //beforeSend: function (xhr) {
        //},
        dataType: 'json',
        contentType: 'application/json; charset=utf-8',
        data: '{ "Username":"test", "Password": "test" }'
    })
    .done(function (data) {
        var element = document.getElementById('loginCall');
        element.innerHTML = "Login Succesfull ? " + data;
    })
    .fail(function (xhr, status, error) { showError(error); })
    .always(function () { showAlert("complete"); });
}

function logout() {
    var jqxhr = $.ajax({
        url: 'http://10.0.2.2/estatewcf/login/logout',
        type: 'POST',
        //headers:
        //beforeSend: function (xhr) {
        //},
        dataType: 'json',
        contentType: 'application/json; charset=utf-8'
    })
    .done(function (data) {
        var element = document.getElementById('logoutCall');
        element.innerHTML = "Login Out Succesfull ? " + data;
    })
    .fail(function (xhr, status, error) { showError(error); })
    .always(function () { showAlert("complete"); });
}

function getSingle() {
    var longcentre = "3.355";
    var latcentre = "6.602";
    var locname = "hotel";
    var searchrad = "10";


    var jqxhr = $.ajax({
        url: 'http://10.0.2.2/estatewcf/Service1/?lat1='+latcentre+'&long1='+longcentre+'&srad='+searchrad+'&lname='+locname+'',
        //   url: 'http://10.0.2.2/estatewcf/Service1/?lat1=6.602&long1=3.355&srad=2.5&lname=bank',
        type: 'GET',
        //headers:
        beforeSend: function (xhr) {
            //xhr.overrideMimeType('text/plain; charset=x-user-defined');
        },
        dataType: 'json',
        contentType: 'application/json; charset=utf-8'
    })
    .done(function (data) {
        var element = document.getElementById('getSingleCall');
        element.innerHTML = JSON.stringify(data, null, "\t");
    })
    .fail(function (xhr, status, error) { showError(error); })
    .always(function () { showAlert("complete"); });
}



function deleteSingle(parameters) {

    var jqxhr = $.ajax({
        url: 'http://10.0.2.2/estatewcf/Service1/88',
        type: 'DELETE',
        //headers:
        beforeSend: function (xhr) {
            //xhr.overrideMimeType('text/plain; charset=x-user-defined');
        },
        dataType: 'json',
        contentType: 'application/json; charset=utf-8'
    })
    .done(function (data) {
        var element = document.getElementById('deleteSingleCall');
        element.innerHTML = JSON.stringify(data, null, "\t");
    })
     .fail(function (xhr, status, error) { showError(error); })
     .always(function () { showAlert("complete"); });
}

function updateSingle(parameters) {
    var jqxhr = $.ajax({
        url: 'http://10.0.2.2/estatewcf/Service1/99',
        type: 'PUT',
        //headers:
        beforeSend: function (xhr) {
            //xhr.overrideMimeType('text/plain; charset=x-user-defined');
        },
        dataType: 'json',
        contentType: 'application/json; charset=utf-8',
        data: '{ "Id":99, "StringValue": "JERRY 22 " }'
    })
    .done(function (data) {
        var element = document.getElementById('updateSingleCall');
        element.innerHTML = JSON.stringify(data, null, "\t");
    })
    .fail(function (xhr, status, error) { showError(error); })
    .always(function () { showAlert("complete"); });
}

function identify(parameters) {
    var jqxhr = $.ajax({
        url: 'http://10.0.2.2/estatewcf/login/identify',
        type: 'GET',
        dataType: 'json',
        contentType: 'application/json; charset=utf-8'
    })
     .done(function (data) {
         var element = document.getElementById('identifyCall');
         element.innerHTML = JSON.stringify(data, null, "\t");
     })
      .fail(function (xhr, status, error) { showError(error); })
      .always(function () { showAlert("complete"); });
}

function postAjax1(parameters) {

    var id = "2";
    var mysearchradius = "ope";

    var jqxhr = $.ajax({
        url: 'http://10.0.2.2/estatewcf/Service1/',
        type: 'POST',
        //headers:
        //beforeSend: function (xhr) {
        //},
        dataType: 'json',
        contentType: 'application/json; charset=utf-8',
        data: '{ "IDn":"' + id + '","type1":"' + mysearchradius + '" }'
    })
    .done(function (data) {
        var element = document.getElementById('postAjaxCall');
        element.innerHTML = JSON.stringify(data, null, "\t");
    })
     .fail(function (xhr, status, error) { showError(error); })
     .always(function () { showAlert("complete"); });
}

function logViaForm() {
    var jqxhr = $.ajax({
        url: 'http://10.0.2.2/estatewcf/login.aspx',
        type: 'GET',
        dataType: 'html'
    })
                .done(function (data) {
                    var eventVal = $(data).find('#__EVENTVALIDATION').attr('value');
                    var viewState = $(data).find('#__VIEWSTATE').attr('value');
                    //build post data
                    var postData = { __VIEWSTATE: viewState, __EVENTVALIDATION: eventVal, UserName: "test1", Password: "test2", LoginButton: "Log In" };

                    var jqxhr1 = $.ajax({
                        url: 'http://10.0.2.2/estatewcf/login.aspx',
                        type: 'POST',
                        dataType: 'html',
                        contentType: 'application/x-www-form-urlencoded; charset=utf-8',
                        data: postData
                    })
                    .done(function (data, status, jqxhr1) {
                        //this works but we will get an error dues to the redirect to the home.aspx
                        //TODO: need to handle that
                        var element = document.getElementById('logViaFormCall');
                        element.innerHTML = "Login Succesfull ! " + jqxhr1.status;
                    })
                     .fail(function (xhr, status, error) {
                         showError(error, "TODO: Works but need to handle redirect!!");

                         //but it really works!
                         var element = document.getElementById('logViaFormCall');
                         element.innerHTML = "Login Succesfull ! Verify that Authenticated AJAX calls work!";
                     })
                     .always(function () { showAlert("complete login"); });
                })
                .fail(function (xhr, status, error) { showError(error); })
                .always(function () { showAlert("complete"); });
}

cordova.xml

<cordova>
    <!--  
    access elements control the Android whitelist.  
    Domains are assumed blocked unless set otherwise
     -->

    <access origin="http://127.0.0.1*"/> <!-- allow local pages -->

    <!-- <access origin="https://maps.googleapis.com/maps/api/js?key=AIzaSyDD353fOPh-KBUQ-2ekPCg75uxXRn0D9Tk&sensor=false" /> allow any secure requests to example.com -->
    <!-- <access origin="https://10.0.2.2*" subdomains="true" /> such as above, but including subdomains, such as www -->
    <!-- <access origin="*."/> Allow all domains, suggested development use only -->

    <log level="DEBUG"/>
    <preference name="classicRender" value="true" />
</cordova

正如我之前所说,我已经使用vs2010服务器和iis7在本地测试了wcf服务 它似乎运行良好,但我无法让它在Android中工作。任何帮助将不胜感激。提前谢谢。

1 个答案:

答案 0 :(得分:1)

我发现这个代码没有错,除了取消评论评论的白名单部分,即转换:

<!-- <access origin="https://10.0.2.2*" subdomains="true" /> such as above, but including subdomains, such as www --> to

<access origin="https://10.0.2.2*" subdomains="true" />

并解决了它。