Url.OpenConnection无法找到网址

时间:2015-08-05 09:37:25

标签: android listview url webview xml-parsing

我的Url.OpenConnection找不到Android 4.3中的网址(我的客户端智能手机,她在西班牙),列表视图不会加载任何甚至没有崩溃,但通常在Android 2.2上加载xml内容(我在阿根廷) ,任何人都知道问题会是什么,请从http://dev.mejorconsalud.com/feed/网页获取xml,我没有任何猫日志,所以请提出任何建议

URL url = new URL(urlString);
URLConnection conn = url.openConnection();

DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(conn.getInputStream());

1 个答案:

答案 0 :(得分:0)

Try to use these two class. It will help you.

**UHttpClient .java**

public class UHttpClient {

    private HttpClient httpClient = null;

    public static final int OK = 200;
    public static final int NO_CONTENT = 204;

    private static final int CONNECTION_TIMEOUT = 5000;

    /* timeout for waiting for data, since once connection is established then waiting for response*/
    private static final int SOCKET_TIMEOUT = 20000;    

    public UHttpClient(UAppInstance appInstance, String loginURL, String deviceID) 
    throws UBaseException {


        HttpParams httpParameters = new BasicHttpParams();

        // Set the timeout in milliseconds until a connection is established.
        HttpConnectionParams.setConnectionTimeout(httpParameters, CONNECTION_TIMEOUT);

        // Set the default socket timeout (SO_TIMEOUT) 
        // in milliseconds which is the timeout for waiting for data.
        HttpConnectionParams.setSoTimeout(httpParameters, SOCKET_TIMEOUT);

        //httpClient = new DefaultHttpClient(httpParameters);
        httpClient = new DefaultHttpClient();

        login(loginURL, deviceID);
    }

    /**
     * Makes the GET call
     * @param urlStr - Url string
     * @param paramNames - parameter names
     * @param paramValues - parameter values
     * @return - response body string
     * @throws UBaseException
     */
    public String executeGet(String urlStr, String[] paramNames, String[] paramValues)
    throws UBaseException {

        HttpGet httpget = null;

        try {
            int length = paramNames != null ? paramNames.length : 0;

            urlStr = length > 0 ? (urlStr + "?") : urlStr;
            for (int k = 0; k < length; k++) {
                urlStr = k > 0 ? (urlStr + "&") : urlStr;
                urlStr = urlStr + paramNames[k] + "=" + paramValues[k];
            }

            httpget = new HttpGet(urlStr);

            // Execute HTTP Get Request
            ResponseHandler<String> respHandler = new BasicResponseHandler();
            String response = httpClient.execute(httpget, respHandler);

            return response;

        } catch (SocketTimeoutException e) {
                throw new UBaseException("Connection Timeout", e);
        } catch (Exception e) {
            if(null == e.getMessage() || "".equals(e.getMessage()))
                throw new UBaseException("Unable to connect to server", e);
            else
                throw new UBaseException(e.getMessage(), e);
        }
    }

    /**
     * Makes the POST call
     * @param urlStr - Url string
     * @param paramNames - parameter names
     * @param paramValues - parameter values
     * @return - response body string
     * @throws UBaseException
     */
    public String executePost(String urlStr, String[] paramNames, String[] paramValues)
    throws UBaseException {

        HttpPost httppost = new HttpPost(urlStr);

        try {
            int length = paramNames != null ? paramNames.length : 0;
            ArrayList<NameValuePair> paramsList = new ArrayList<NameValuePair>();

            for (int k = 0; k < length; k++) {
                paramsList.add(new BasicNameValuePair(paramNames[k], paramValues[k]));
            }

            List<NameValuePair> nameValuePairs = paramsList;
            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

            // Execute HTTP Post Request
            ResponseHandler<String> respHandler = new BasicResponseHandler();
            String response = httpClient.execute(httppost, respHandler);

            return response;

        } catch (SocketTimeoutException e) {
                throw new UBaseException("Connection Timeout", e);
        } catch (Exception e) {
            if(null == e.getMessage() || "".equals(e.getMessage()))
                throw new UBaseException("Unable to connect to server", e);
            else
                throw new UBaseException(e.getMessage(), e);
        }
    }


    protected void login(String url, String deviceID)
    throws UBaseException {

        String[] argNames = new String[] {"userDeviceID", "loginMode", "command"};
        String[] argValues = new String[] {deviceID, "handheldLogin", "login"};

        String response = executePost(url, argNames, argValues);

        if(null != response){
            response = response.trim();
        }

        // if response message is not success that means it's a failure so raising exception 
        if("success".equals(response) == false) {
            if(!"".equals(response))
                throw new UBaseException(response, null);
            else
                throw new UBaseException("Remote login failed to '" + url + "'", null);
        }
    }
}



**URemoteConnection.java**



public class URemoteConnection {

    private UHttpClient client = null;
    private String remoteHost = null;

    private String appName = null;
    private String servletName = null;
    private String remoteURL = null;
    private String deviceID = null;

    private String httpPortNum = "";
    private String httpsPortNum = "";

    private static final String REMOTE_APP_NAME = "_REMOTE_APP_NAME_";
    private static final String REMOTE_HOST_ADDRESS = "_REMOTE_HOST_ADDR_";
    private static final String REMOTE_HTTP_PORT = "_REMOTE_HTTP_PORT_";
    private static final String REMOTE_HTTPS_PORT = "_REMOTE_HTTPS_PORT_";

    private static final String FEEDBACK_MSG_SEPERATOR = "-stat-";
    private static final String FEEDBACK_MSG_SUCCESS_STR = "200";

    /**
     * URemoteConnection constructor
     * 
     * @param appInstance
     *            - UAppInstance object
     * @param app
     *            - remote application name
     * @param servlet
     *            - servlet name
     * @throws UBaseException
     */
    public URemoteConnection(UAppInstance appInstance, String app,
            String servlet) throws UBaseException {

        try {
            appName = app;
            servletName = servlet;
            remoteHost = getServerAddress(appInstance, appName);
            httpPortNum = getServerHttpPort(appInstance, appName);
            httpsPortNum = getServerHttpsPort(appInstance, appName);
            deviceID = CommonUtils.getUserDeviceID(appInstance);

            remoteURL = "http://" + remoteHost + ":" + httpPortNum + "/"
                    + appName + "/" + servletName;

            String loginURL = "http://" + remoteHost + ":" + httpPortNum + "/"
                    + appName + "/Login";

            Log.d("URemoteConnection", "remoteURL : " + remoteURL);

            Log.d("URemoteConnection", "loginURL : " + loginURL);

            client = new UHttpClient(appInstance, loginURL, deviceID);

        } catch (Exception e) {
            throw new UBaseException(e.getMessage(), e);
        }
    }

    /**
     * Call to do any data upload. Makes Http POST call.
     * 
     * @param argsNames
     * @param argsValues
     * @return - response text
     * @throws UBaseException
     */
    public String processData(String[] argsNames, String[] argsValues)
            throws UBaseException {
        try {
            String response = client.executePost(remoteURL, argsNames,
                    argsValues);
            response = _filterFeedBackMsg(response);
            return response;

        } catch (Exception e) {
            throw new UBaseException(e.getMessage(), e);
        }
    }

    /**
     * Call to do any data download. Makes Http GET call.
     * 
     * @param argsNames
     * @param argsValues
     * @return - response body string
     * @throws UBaseException
     */
    public String requestData(String[] argsNames, String[] argsValues)
            throws UBaseException {
        try {
            String response = client.executeGet(remoteURL, argsNames,
                    argsValues);
            response = _filterFeedBackMsg(response);
            return response;

        } catch (Exception e) {
            throw new UBaseException(e.getMessage(), e);
        }
    }

    /**
     * Loads the remote app details from database and populates the in-memory
     * cache.
     * 
     * @param appInstance
     * @throws UDBAccessException
     */
    public static void loadRemoteAppDetails(UAppInstance appInstance)
            throws UDBAccessException {
        Cursor cur = appInstance.getDBHandle().executeQuery(
                "mobi_remote_app",
                new String[] { "remote_app_name", "remote_host_address",
                        "remote_http_port", "remote_https_port" }, null, null,
                null, null, null);

        while (null != cur && cur.moveToNext()) {
            String appName = cur.getString(cur
                    .getColumnIndex("remote_app_name"));

            appInstance.setAttribute(REMOTE_APP_NAME, appName);
            appInstance.setAttribute(REMOTE_HOST_ADDRESS + "~" + appName,
                    cur.getString(cur.getColumnIndex("remote_host_address")));
            appInstance.setAttribute(REMOTE_HTTP_PORT + "~" + appName,
                    cur.getString(cur.getColumnIndex("remote_http_port")));
            appInstance.setAttribute(REMOTE_HTTPS_PORT + "~" + appName,
                    cur.getString(cur.getColumnIndex("remote_https_port")));
        }

        if (null != cur) {
            cur.close();
        }
    }

    public static String getServerAddress(UAppInstance appInstance,
            String appName) {

        return "172.16.0.117"; 
    }

    public static String getServerHttpPort(UAppInstance appInstance,
            String appName) {

        return "8080";
    }

    public static String getServerHttpsPort(UAppInstance appInstance,
            String appName) {
        return appInstance.getAttribute(REMOTE_HTTPS_PORT + "~" + appName, "");
    }

    /*
     * Checking if from the server side if any error coming then throw the
     * exception else sent the original feedback
     */
    private static String _filterFeedBackMsg(String feedBackMsg)
            throws Exception {
        if (feedBackMsg != null && !"".equals(feedBackMsg)
                && !feedBackMsg.equalsIgnoreCase("null")) {
            if (feedBackMsg.indexOf(FEEDBACK_MSG_SEPERATOR) > -1) {
                String feedBackMsgArr[] = feedBackMsg
                        .split(FEEDBACK_MSG_SEPERATOR);
                if (feedBackMsgArr != null && feedBackMsgArr.length > 1) {
                    if (feedBackMsgArr[0] != null
                            && !FEEDBACK_MSG_SUCCESS_STR
                                    .equals(feedBackMsgArr[0])) {
                        throw new Exception(feedBackMsgArr[1]);
                    }
                }
            }
        }
        return feedBackMsg;
    }
}