服务器不可用时应用程序崩溃。如何设置httpurlconnection的connectiontimeout?

时间:2013-09-14 10:01:50

标签: java android exception httpurlconnection connection-timeout

 String urlStr = "nana.com/nana/api/v1"
        HttpURLConnection conn = null;
BufferedReader rd = null;
StringBuilder sb = null;
try {
    URL url = new URL(urlStr);
    conn = (HttpURLConnection) url.openConnection();

    if (conn.getResponseCode() != 200) {
        throw new IOException(conn.getResponseMessage());
    }
    else {

    rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
    sb = new StringBuilder();
    String line;
    while ((line = rd.readLine()) != null) {
        sb.append(line);
    } 
    rd.close();

    conn.disconnect();
    }
} catch (IOException i) {
    i.printStackTrace();
                }catch (Exception e) {
    e.printStackTrace();

这是我的连接,我真的不想使用apache。我希望我的应用程序显示一些错误消息,如果服务器无法访问,但它崩溃了,我有点想法。

2 个答案:

答案 0 :(得分:0)

试试这种方式

try {
            String urlStr = "nana.com/nana/api/v1";
            HttpURLConnection conn = null;
            BufferedReader rd = null;
            StringBuilder sb = null;

            URL url = new URL(urlStr);
            conn = (HttpURLConnection) url.openConnection();
            conn.setRequestProperty("User-Agent", "Android Application");
            conn.setRequestProperty("Connection", "close");
            conn.setConnectTimeout(10 * 1000);
            conn.connect();
            if (conn.getResponseCode() == 200) {
                rd = new BufferedReader(new InputStreamReader(
                        conn.getInputStream()));
                sb = new StringBuilder();
                String line;
                while ((line = rd.readLine()) != null) {
                    sb.append(line);
                }
                rd.close();

                conn.disconnect();

            }else{
                throw new IOException(conn.getResponseMessage());
            }
        } catch (Throwable e) {
            e.printStackTrace();
        }

答案 1 :(得分:0)

This method is for default timeout when there is a problem in the connection eg socket timeout or connection     timeout.
public static DefaultHttpClient returnHttpClient() {
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 = 60000;
HttpConnectionParams.setConnectionTimeout(httpParameters,
        timeoutConnection);
// Set the default socket timeout (SO_TIMEOUT)
// in milliseconds which is the timeout for waiting for data.
int timeoutSocket = 600000;
HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);

return new DefaultHttpClient(httpParameters);
}