1

花了一整天的时间查看这段代码,但仍然无法弄清楚为什么我用于我的应用程序的任何 wifi 连接在我退出应用程序后会丢失(按主页、返回 btns 等)

public JSONObject getJSONFromUrl(String url, List<NameValuePair> params, boolean isUploadingFile, MultipartEntity entity) throws Exception {

        // Initialize
        HttpEntity httpEntity = null;
        HttpPost httpPost = null;
        is = null; jObj = null; json = "";

        // Making HTTP request
        try {
            HttpParams httpParameters = new BasicHttpParams();
            // Set the timeout in milliseconds until a connection is established.
            // The default value is zero, that means the timeout is not used.
            int timeoutConnection = 10000;
            HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
            // Set the default socket timeout (SO_TIMEOUT)
            // in milliseconds which is the timeout for waiting for data.
            int timeoutSocket = 10000;
            HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);

            // defaultHttpClient
            DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters);
            httpPost = new HttpPost(url);
            if (isUploadingFile)
                httpPost.setEntity(entity);
            else
                httpPost.setEntity(new UrlEncodedFormEntity(params,"UTF-8"));

            HttpResponse httpResponse = httpClient.execute(httpPost);
            httpEntity = httpResponse.getEntity();

        } catch (Exception e) {
            Log.e("EXCEPTIONS", e.toString());
            return jObj;
        }

        if (httpEntity != null) {
            is = httpEntity.getContent();
            // Read the server response
            try {
                BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
                StringBuilder sb = new StringBuilder();
                String line = null;
                while ((line = reader.readLine()) != null) {
                    sb.append(line + "\n");
                }

                is.close();
                reader.close();
                json = sb.toString();

                //Log.e("JSON", json); // !!! comment this line for release !!!
            } catch (Exception e) {
                Log.e("Buffer Error", "Error converting result " + e.toString());
            } finally {
                try {
                    if (httpEntity != null)
                        httpEntity.consumeContent();
                } catch (Exception e) {
                    Log.e("EXCEPTIONS", e.toString());
                }
            }

            // Try parsing the string to a JSON object
            try {
                jObj = new JSONObject(json);
            } catch (Exception e) {
                Log.e("JSON Parser", "Error parsing data " + e.toString());
            }
        }

        // Return JSON Object
        return jObj;

    }
4

0 回答 0