Android 无法在应用程序中连接我的网络服务 [英] Android unable to connect my web-service in app

查看:65
本文介绍了Android 无法在应用程序中连接我的网络服务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

一定有很多关于我的问题.但是我找不到一个好的解决方案,所以这就是我发布问题的原因.

There must be a lot of questions regarding to mine. But i couldn't find a good solution for it, so that's why i am posting a question.

我使用 yii 框架创建了一个 REST web-service.下面是我的 api

I have created a REST web-service using yii framework. Below is my code for the api

class UsersController extends ActiveController
{
public $modelClass = 'app\models\Users';
public function actions()
{
    $actions = parent::actions();
    unset($actions['index']);
 return $actions;

}
public function actionIndex()
{
    $users = Users::find()->all();
    \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
    $users1['users'] = $users;
    return $users1;
}}

我的api的结果是

{
"users": [
    {
        "Id": 1,
        "Name": "Faisal"
    },
    {
        "Id": 2,
        "Name": "Salman"
    },
    {
        "Id": 3,
        "Name": "Asim"
    },
    {
        "Id": 4,
        "Name": "Asad"
    },
    {
        "Id": 5,
        "Name": "Mateen"
    },
    {
        "Id": 6,
        "Name": "Omar"
    },
    {
        "Id": 7,
        "Name": "Usama"
    }
]}

安卓部分见下

Users.java

public class Users {

private String Id;
private String Name;

public String getId() {
    return Id;
}

public void setId(String id) {
    this.Id = id;
}

public String getName() {
    return Name;
}

public void setName(String name) {
    this.Name = name;
}}

JSONfunctions.java

public class JSONfunctions {


public static JSONObject getJSONfromURL(String url)
{
    InputStream is = null;
    String result = "";
    JSONObject jArray = null;

    // Download JSON data from URL

    try {
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost(url);
        HttpResponse response = httpclient.execute(httppost);
        HttpEntity httpEntity = response.getEntity();
        is = httpEntity.getContent();
    } catch (ClientProtocolException e) {

        Log.e("log_tag", "Error in http connection " + e.toString());
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    // Convert response to string

    try {
        BufferedReader reader = new BufferedReader(new InputStreamReader(is , "iso-8859-1"),8);
        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line= reader.readLine())!=null)
        {
            sb.append(line + "\n");
        }
        is.close();
        result = sb.toString();
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (IOException e) {
        Log.e("log_tag", "Error converting result " + e.toString());
        e.printStackTrace();
    }

    try {
        jArray = new JSONObject(result);

    } catch (JSONException e) {
        Log.e("log_tag", "Error parsing data " + e.toString());
        e.printStackTrace();
    }

    return jArray;
}}

MainActivity.java

public class MainActivity extends AppCompatActivity {

JSONObject jsonObject;
JSONArray jsonArray;
ProgressDialog progressDialog;
ArrayList<String> userList;
ArrayList<Users> users;

TextView textViewResult;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    // Download JSON file AsyncTask
    new DownloadJSON().execute();
}


// Download JSON file AsyncTask
private class DownloadJSON extends AsyncTask<Void, Void, Void>
{

    /*@Override
    protected void onPreExecute() {
        super.onPreExecute();
        progressDialog = new ProgressDialog(MainActivity.this);
        progressDialog.setMessage("Fetching Users....!");
        progressDialog.setCancelable(false);
        progressDialog.show();

    }*/
    @Override
    protected Void doInBackground(Void... params) {

        // Locate the Users Class
        users = new ArrayList<Users>();

        // Create an array to populate the spinner
        userList = new ArrayList<String>();
        // http://localhost:8000/app/web/users/
        // JSON file URL address
        jsonObject = JSONfunctions.getJSONfromURL("http://10.0.2.2:8000/app/web/users/");

        try
        {
            // Locate the NodeList name
            jsonArray = jsonObject.getJSONArray("users");

            for(int i=0; i<jsonArray.length(); i++)
            {
                jsonObject = jsonArray.getJSONObject(i);

                Users user = new Users();

                user.setId(jsonObject.optString("Id"));
                user.setName(jsonObject.optString("Name"));
                users.add(user);

                userList.add(jsonObject.optString("Name"));

            }
        } catch (JSONException e) {
            Log.e("Error", e.getMessage());
            e.printStackTrace();
        }


        return null;
    }

    @Override
    protected void onPostExecute(Void args)
    {
        // Locate the spinner in activity_main.xml
        Spinner spinner = (Spinner)findViewById(R.id.spinner);

        // Spinner adapter
        spinner.setAdapter(new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_spinner_dropdown_item, userList));

        // Spinner on item click listener

        spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {

                textViewResult = (TextView)findViewById(R.id.textView);

                // Set the text followed by the position

                textViewResult.setText("Hi " + users.get(position).getName() + " your ID is " + users.get(position).getId());

            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
                textViewResult.setText("");
            }
        });
    }


}}

现在,当我运行应用程序时,预期结果将是

Now when i run the app the expected result would be

实际的结果是

logcat 我收到了警告

 org.json.JSONException: No value for users
 02-15 17:11:58.672 2158-2197/com.example.accurat.myapp W/System.err:     at org.json.JSONObject.get(JSONObject.java:389)
 02-15 17:11:58.673 2158-2197/com.example.accurat.myapp W/System.err:     at org.json.JSONObject.getJSONArray(JSONObject.java:584)
 02-15 17:11:58.673 2158-2197/com.example.accurat.myapp W/System.err:     at com.example.accurat.myapp.MainActivity$DownloadJSON.doInBackground(MainActivity.java:70)
 02-15 17:11:58.673 2158-2197/com.example.accurat.myapp W/System.err:     at com.example.accurat.myapp.MainActivity$DownloadJSON.doInBackground(MainActivity.java:42)
 02-15 17:11:58.673 2158-2197/com.example.accurat.myapp W/System.err:     at android.os.AsyncTask$2.call(AsyncTask.java:292)
 02-15 17:11:58.673 2158-2197/com.example.accurat.myapp W/System.err:     at java.util.concurrent.FutureTask.run(FutureTask.java:237)
 02-15 17:11:58.673 2158-2197/com.example.accurat.myapp W/System.err:     at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
 02-15 17:11:58.673 2158-2197/com.example.accurat.myapp W/System.err:     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
 02-15 17:11:58.673 2158-2197/com.example.accurat.myapp W/System.err:     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
 02-15 17:11:58.673 2158-2197/com.example.accurat.myapp W/System.err:     at java.lang.Thread.run(Thread.java:818)

命中点jsonArray = jsonObject.getJSONArray("users");

注意:我现在正在模拟器上测试结果.

Note: I am testing the results on emulator for now.

更新 1

对不起,我忘了提,首先我使用一个简单的 php 文件,代码如下

Sorry i forgot to mention, first i use a simple php file the code is bellow

{"users":[{"Id":"1","Name":"Faisal"},{"Id":"2","Name":"Salman"},{"Id":"3","Name":"Asim"},{"Id":"4","Name":"Asad"},{"Id":"5","Name":"Mateen"},{"Id":"6","Name":"Omar"},{"Id":"7","Name":"Usama"}]}

我的地址是 http://10.0.2.2:8000/MobileApp/index.php 并且工作正常.为了我的安全和易用性,我选择 yii.

My address was http://10.0.2.2:8000/MobileApp/index.php and it was working fine. For security and easiness of mine i choose yii.

我一定错过了一些我不知道的东西

I must be missing something that i don't know

任何帮助将不胜感激.

推荐答案

请更改您的代码.希望有帮助

Please change your code. Hope it helps

 private class Task extends AsyncTask<JSONObject, Void, JSONObject>{
    @Override
    protected JSONObject doInBackground(JSONObject... params) {
        try {
            JSONParser json_parser = new JSONParser();
            json_object = json_parser.getJson(url);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return json_object;
    }

    @Override
    protected void onPostExecute(JSONObject result){
        LoadEmployee(result);
    }
}

private class JSONParser {
    .....
    public JSONObject getJson(String url) {
        try {
            HttpClient httpClient = new DefaultHttpClient();
            HttpGet httpget = new HttpGet(url);
            HttpResponse httpResponse = httpClient.execute(httpget);
            BufferedReader rd = new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent()));
            StringBuffer hasil = new StringBuffer();
            String line = "";
            while ((line = rd.readLine()) != null) {
                hasil.append(line);
            }
            json = hasil.toString();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        try {
            jObj = new JSONObject(json);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return jObj;
    }
}

这篇关于Android 无法在应用程序中连接我的网络服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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