从Android手机连接本地Web服务

时间:2016-04-04 06:12:40

标签: android web-services

我正在尝试连接到我的计算机上运行的Web服务(localhost)。我已经从restClient测试了它的工作正常。但是,我无法从Android应用程序(我正在处理)测试它们。似乎存在连接问题。 这是调用代码:

@Override
        protected Void doInBackground(String... params) {

            HttpURLConnection urlConnection = null;
            BufferedReader reader = null;
            String mobileNo = params[0];


            String format = "json";

            try {
                // Construct the URL for Login

                JSONObject requestObject = new JSONObject();
                requestObject.put(MOBILE_NO, mobileNo);

                final String LOGIN_BASE_URL =
                        "http://192.168.42.251:8080/SpringSample/login";

                Uri builtUri = Uri.parse(LOGIN_BASE_URL).buildUpon()
                        .build();

                URL url = new URL(builtUri.toString());

                // Create the request to OpenWeatherMap, and open the connection
                urlConnection = (HttpURLConnection) url.openConnection();
                urlConnection.setRequestMethod("POST");
                urlConnection.connect();
                // Request Body
                OutputStream outStream = urlConnection.getOutputStream();
                if (outStream == null) {
                    throw new ConnectException();
                }
                outStream.write(requestObject.toString().getBytes());


                int responseCode = urlConnection.getResponseCode();

                if (responseCode == 409) {

                } else if (responseCode == 201) {

                } else {
                    throw new ConnectException();
                }

            } catch (IOException e) {
                Log.e(LOG_TAG, "Error ", e);

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

            } catch (ConnectException e) {
                Log.e(LOG_TAG, "Error ", e);

            } finally {
                if (urlConnection != null) {
                    urlConnection.disconnect();
                }
                if (reader != null) {
                    try {
                        reader.close();
                    } catch (final IOException e) {
                        Log.e(LOG_TAG, "Error closing stream", e);
                    }
                }
            }

            return null;
        }

例外是:

 Caused by: android.system.ErrnoException: connect failed: ETIMEDOUT (Connection timed out)

0 个答案:

没有答案