0

我编写了一个 java restful web 服务并将其部署在 ec2 实例上,并以 tomcat7 作为服务器。我正在尝试从 Web 服务检索响应对象中的 json 数组。我的响应对象是这样的:-

{
    "Transactional": [
        {
            "a": "Y",
            "a1": "4",
            "a2": "5",
            "a3": "0",
            "a4": "1",
            "a5": "4",
            "a6": "3",
            "a7": "6",
            "a8": "9",
            "a9": "5",
            "b_MovieID": "0",
            "c": "N",
            "c1": "0",
            "c2": "0",
            "c3": "0",
            "c4": "0",
            "c5": "0",
            "c6": "0",
            "d": "N",
            "d1": "0",
            "d2": "0",
            "d3": "0",
            "d4": "0",
            "d5": "0",
            "d6": "0",
            "d7": "0",
            "g1": "10",
            "g2": "8",
            "g3": "2",
            "g4": "8",
            "g5": "0",
            "g6": "7",
            "g7": "8",
            "h": "N",
            "h1": "0",
            "h2": "0",
            "h3": "0",
            "h4": "0",
            "h5": "0",
            "h6": "0",
            "movieID": "1",
            "r": "N",
            "r1": "0",
            "r2": "0",
            "r3": "0",
            "r4": "0",
            "r5": "0",
            "r6": "0",
            "r7": "0",
            "s": "N",
            "s1": "0",
            "s2": "0",
            "s3": "0",
            "s4": "0",
            "s5": "0",
            "s6": "0",
            "SB": "N",
            "SB1": "0",
            "SB2": "0",
            "SB3": "0",
            "SB4": "0",
            "SP": "N",
            "SP1": "0",
            "SP2": "0",
            "SP3": "0",
            "t": "N",
            "t1": "0",
            "t2": "0",
            "t3": "0",
            "t4": "0",
            "t5": "0",
            "t6": "0",
            "t7": "0",
            "t8": "0",
            "t9": "0",
            "TA1": "N",
            "TA2": "N",
            "TA3": "N",
            "TC1": "N",
            "TC2": "N",
            "TG1": "N",
            "TG2": "N",
            "TG3": "N",
            "TG4": "N",
            "TG5": "N",
            "TH1": "N",
            "TH2": "N",
            "TH3": "N",
            "TR1": "N",
            "TS1": "N",
            "TS2": "N",
            "TSB1": "N",
            "TSP1": "N",
            "TW1": "N",
            "w": "N",
            "w1": "0",
            "w2": "0",
            "w3": "0",
            "w4": "0",
            "w5": "0"
        },
        {
            "a": "Y",
            "a1": "1",
            "a2": "6",
            "a3": "0",
            "a4": "4",
            "a5": "3",
            "a6": "4",
            "a7": "2",
            "a8": "3",
            "a9": "4",
            "b_MovieID": "0",
            "c": "N",
            "c1": "0",
            "c2": "0",
            "c3": "0",
            "c4": "0",
            "c5": "0",
            "c6": "0",
            "d": "N",
            "d1": "0",
            "d2": "0",
            "d3": "0",
            "d4": "0",
            "d5": "0",
            "d6": "0",
            "d7": "0",
            "g1": "5",
            "g2": "6",
            "g3": "6",
            "g4": "7",
            "g5": "0",
            "g6": "8",
            "g7": "7",
            "h": "N",
            "h1": "0",
            "h2": "0",
            "h3": "0",
            "h4": "0",
            "h5": "0",
            "h6": "0",
            "movieID": "2",
            "r": "N",
            "r1": "0",
            "r2": "0",
            "r3": "0",
            "r4": "0",
            "r5": "0",
            "r6": "0",
            "r7": "0",
            "s": "N",
            "s1": "0",
            "s2": "0",
            "s3": "0",
            "s4": "0",
            "s5": "0",
            "s6": "0",
            "SB": "N",
            "SB1": "0",
            "SB2": "0",
            "SB3": "0",
            "SB4": "0",
            "SP": "N",
            "SP1": "0",
            "SP2": "0",
            "SP3": "0",
            "t": "N",
            "t1": "0",
            "t2": "0",
            "t3": "0",
            "t4": "0",
            "t5": "0",
            "t6": "0",
            "t7": "0",
            "t8": "0",
            "t9": "0",
            "TA1": "N",
            "TA2": "N",
            "TA3": "N",
            "TC1": "N",
            "TC2": "N",
            "TG1": "N",
            "TG2": "N",
            "TG3": "N",
            "TG4": "N",
            "TG5": "N",
            "TH1": "N",
            "TH2": "N",
            "TH3": "N",
            "TR1": "N",
            "TS1": "N",
            "TS2": "N",
            "TSB1": "N",
            "TSP1": "N",
            "TW1": "N",
            "w": "N",
            "w1": "0",
            "w2": "0",
            "w3": "0",
            "w4": "0",
            "w5": "0"
        }
    ]
}

我正在尝试使用以下代码在我的 android 应用程序中的 java 中检索它:-

try {
            JSONObject jsonObj = new JSONObject(response);
            JSONArray jsonArr;

            jsonArr = jsonObj.getJSONArray("Transactional");

            for (int i = 0; i < jsonArr.length(); i++) {
                JSONObject obj = jsonArr.getJSONObject(i);

                try {

                    int A1 = obj.getInt("a1");
                    System.out.println("A1  value : " + A1);
                    break;
                } catch (JSONException ex) {

                }

            }

这是从 json 数组中检索数据的正确方法吗?我收到以下错误:-

12-14 11:11:56.526: E/WebServiceTask(18921): ec2-xx-xx-xxx-xxx.compute-1.amazonaws.com
12-14 11:11:56.526: E/WebServiceTask(18921): java.net.UnknownHostException: ec2-xx-xx-xxx-xxx.compute-1.amazonaws.com
12-14 11:11:56.526: E/WebServiceTask(18921):    at    java.net.InetAddress.lookupHostByName(InetAddress.java:506)
12-14 11:11:56.526: E/WebServiceTask(18921):    at java.net.InetAddress.getAllByNameImpl(InetAddress.java:294)
12-14 11:11:56.526: E/WebServiceTask(18921):    at java.net.InetAddress.getAllByName(InetAddress.java:256)
12-14 11:11:56.526: E/WebServiceTask(18921):    at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:136)
12-14 11:11:56.526: E/WebServiceTask(18921):    at    org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
12-14 11:11:56.526: E/WebServiceTask(18921):    at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
12-14 11:11:56.526: E/WebServiceTask(18921):    at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:359)
12-14 11:11:56.526: E/WebServiceTask(18921):    at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
12-14 11:11:56.526: E/WebServiceTask(18921):    at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
12-14 11:11:56.526: E/WebServiceTask(18921):    at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
12-14 11:11:56.526: E/WebServiceTask(18921):    at com.movies.CategorySelection$WebServiceTask.doResponse(SubCategorySelection.java:248)
12-14 11:11:56.526: E/WebServiceTask(18921):    at com.movies.CategorySelection$WebServiceTask.doInBackground(SubCategorySelection.java:147)
12-14 11:11:56.526: E/WebServiceTask(18921):    at com.movies.CategorySelection$WebServiceTask.doInBackground(SubCategorySelection.java:1)
12-14 11:11:56.526: E/WebServiceTask(18921):    at android.os.AsyncTask$2.call(AsyncTask.java:185)
12-14 11:11:56.526: E/WebServiceTask(18921):    at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:306)
12-14 11:11:56.526: E/WebServiceTask(18921):    at java.util.concurrent.FutureTask.run(FutureTask.java:138)
12-14 11:11:56.526: E/WebServiceTask(18921):    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1088)
12-14 11:11:56.526: E/WebServiceTask(18921):    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:581)
12-14 11:11:56.526: E/WebServiceTask(18921):    at java.lang.Thread.run(Thread.java:1019)
12-14 11:11:56.576: E/SubCategorySelection(18921): Error parsing data org.json.JSONException: End of input at character 0 of 

尽管我知道我遇到了未知主机异常,但我可以在同一主机中的示例 url 上轻松检索示例数据

http://ec2-xx-xx-xxx-xxx.compute-1.amazonaws.com:8080/MovieAppRestWebService/rest/movie/sample

这可能意味着我解析数据的方式有问题。谁能帮忙!

这是我调用网络服务的方式:-

private static final String SERVICE_URL_ACTION = "http://ec2-xx-xx-xxx-xxx.compute-1.amazonaws.com:8080/MovieAppRestWebService/rest/movie/A";

Button bNext = (Button) findViewById(R.id.btnNext);
    bNext.setOnClickListener(new OnClickListener() {

        public void onClick(View v) {
            retrieveSampleData(v);
        }
    });

public void retrieveSampleData(View vw) {

    WebServiceTask wst = new WebServiceTask(WebServiceTask.GET_TASK, this,
            "GETting data...");

    wst.execute(new String[] { SERVICE_URL_ACTION });
}

private class WebServiceTask extends AsyncTask<String, Integer, String> {

    public static final int POST_TASK = 1;
    public static final int GET_TASK = 2;

    private static final String TAG = "WebServiceTask";

    // connection timeout, in milliseconds (waiting to connect)
    private static final int CONN_TIMEOUT = 3000;

    // socket timeout, in milliseconds (waiting for data)
    private static final int SOCKET_TIMEOUT = 5000;

    private int taskType = GET_TASK;
    private Context mContext = null;
    private String processMessage = "Processing...";

    private ArrayList<NameValuePair> params = new ArrayList<NameValuePair>();

    private ProgressDialog pDlg = null;

    public WebServiceTask(int taskType, Context mContext,
            String processMessage) {

        this.taskType = taskType;
        this.mContext = mContext;
        this.processMessage = processMessage;
    }


    @SuppressWarnings("deprecation")
    private void showProgressDialog() {

        pDlg = new ProgressDialog(mContext);
        pDlg.setMessage(processMessage);
        pDlg.setProgressDrawable(mContext.getWallpaper());
        pDlg.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        pDlg.setCancelable(false);
        pDlg.show();

    }

    @Override
    protected void onPreExecute() {

        hideKeyboard();
        showProgressDialog();

    }

    protected String doInBackground(String... urls) {

        String url = urls[0];
        String result = "";

        HttpResponse response = doResponse(url);

        if (response == null) {
            return result;
        } else {

            try {

                result = inputStreamToString(response.getEntity()
                        .getContent());

            } catch (IllegalStateException e) {
                Log.e(TAG, e.getLocalizedMessage(), e);

            } catch (IOException e) {
                Log.e(TAG, e.getLocalizedMessage(), e);
            }

        }

        return result;
    }

    @Override
    protected void onPostExecute(String response) {

        handleResponse(response);
        pDlg.dismiss();

    }

    public void handleResponse(String response) {

        // try {
        //
        // JSONObject jArray = (JSONObject)JSONValue.parse(response);
        // JSONObject jObj = jArray.getJSONObject("movieTransactional");
        //
        // for (int i = 0; i < jArray.length(); i++) { // **line 2**
        // JSONObject childJSONObject = jArray.get(i);
        // String name = childJSONObject.getString("name");
        // int age = childJSONObject.getInt("age");
        // }


        try {
            JSONObject jsonObj = new JSONObject(response);
            JSONArray jsonArr;

            jsonArr = jsonObj.getJSONArray("movieTransactional");

            for (int i = 0; i < jsonArr.length(); i++) {
                JSONObject obj = jsonArr.getJSONObject(i);

                try {

                    int A1 = obj.getInt("a1");
                    System.out.println("A1  value : " + A1);
                    break;
                } catch (JSONException ex) {

                }

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

        }
    }

    // Establish connection and socket (data retrieval) timeouts
    private HttpParams getHttpParams() {

        HttpParams htpp = new BasicHttpParams();

        HttpConnectionParams.setConnectionTimeout(htpp, CONN_TIMEOUT);
        HttpConnectionParams.setSoTimeout(htpp, SOCKET_TIMEOUT);

        return htpp;
    }

    private HttpResponse doResponse(String url) {

        // Use our connection and data timeouts as parameters for our
        // DefaultHttpClient
        HttpClient httpclient = new DefaultHttpClient(getHttpParams());

        HttpResponse response = null;

        try {
            switch (taskType) {

            case POST_TASK:
                HttpPost httppost = new HttpPost(url);
                // Add parameters
                httppost.setEntity(new UrlEncodedFormEntity(params));

                response = httpclient.execute(httppost);
                break;
            case GET_TASK:
                HttpGet httpget = new HttpGet(url);
                response = httpclient.execute(httpget);
                break;
            }
        } catch (Exception e) {

            Log.e(TAG, e.getLocalizedMessage(), e);

        }

        return response;
    }

    private String inputStreamToString(InputStream is) {

        String line = "";
        StringBuilder total = new StringBuilder();

        // Wrap a BufferedReader around the InputStream
        BufferedReader rd = new BufferedReader(new InputStreamReader(is));

        try {
            // Read response until the end
            while ((line = rd.readLine()) != null) {
                total.append(line);
            }
        } catch (IOException e) {
            Log.e(TAG, e.getLocalizedMessage(), e);
        }

        // Return full string
        return total.toString();
    }

}
4

1 回答 1

1

问题解决了!

我没有在我的 android 应用程序中添加以下权限。

<uses-permission android:name="android.permission.INTERNET" />

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

由于我的应用程序能够访问互联网,因此未知主机异常。

于 2012-12-14T14:45:21.497 回答