0
 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。如果服务器无法访问,我希望我的应用程序显示一些错误消息,但它会崩溃,我有点没有想法。

4

2 回答 2

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();
        }
于 2013-09-14T10:11:12.920 回答
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);
}
于 2013-09-14T10:15:06.387 回答