0

代码:

   public static String openUrl(String url, String method,
            RequestParam params) throws NuageException {
        HttpURLConnection conn = null;
        String response = "";
        String decodParam = params.decod();
        if (method.equals(GET)) 
            {
            url = url + "?" + decodParam;
            // Log.v(LOG_TAG, "GET:" + url);
        }

         try {
            Log.v("开始请求:", String.valueOf(System.currentTimeMillis()));
            conn = (HttpURLConnection) new URL(url).openConnection();
            conn.setReadTimeout(READTIMEOUT);
            conn.setConnectTimeout(CONNECTTIMEOUT);
            conn.setUseCaches(false);
            conn.setRequestProperty("Connection", "Keep-Alive");
            if (method.equals(POST)) {
                conn.setRequestMethod("POST");
                conn.setDoOutput(true);
                conn.getOutputStream().write(decodParam.getBytes("UTF-8"));
                // Log.v(LOG_TAG, "POST:" + url + " " + decodParam);
            }
            InputStream is = null;
            conn.connect();
            int responseCode = conn.getResponseCode();
            if (responseCode == 200 || responseCode == 201
                    || responseCode == 202) {
                is = conn.getInputStream();
            } else {
                is = conn.getErrorStream();
            }
            response = read(is);
            Log.v("请求结束:", String.valueOf(System.currentTimeMillis()));
            Log.v(LOG_TAG, "response:" + response);
            checkResponse(response);
        } catch (MalformedURLException e) {
            throw new NuageException(e);
        } catch (IOException e) {
            if (e.getMessage() != null && e.getMessage().equals(
                    "Received authentication challenge is null"))
                throw new NuageException(new NuageError(
                        NuageError.ERROR_SESSIONKEY_INVALID, "", "", ""));
            e.printStackTrace();
            throw new NuageException(e);
        } catch (NuageException e) {
            throw e;
        } finally {
            if (conn != null) {
                conn.disconnect();
            }
        }
        return response;
    }

有时我会java.net.SocketTimeoutException: Connection timed out在浏览器仍然工作时得到。

任何人都可以帮助改进我的代码?

4

0 回答 0