0

当我执行 httpRequest 时,如何设置连接超时?我回到之前的活动?因为我的apilcacion 被防火墙阻止了,我可以腾出一些时间无法连接到服务器,我返回到之前的活动并显示一个Toast 告诉我没有互联网连接?

这是我的代码的一部分:

protected String doInBackground(String... args) {

        List<NameValuePair> params = new ArrayList<NameValuePair>();

        JSONObject json = jParser.makeHttpRequest(url_list, "GET",
                params);

        Log.d("All Products: ", json.toString());

        try {

            int success = json.getInt(TAG_SUCCESS);

            if (success == 1) {

                daftar_rs = json.getJSONArray(TAG_DAFTAR_RS);

                for (int i = 0; i < daftar_rs.length(); i++) {
                    JSONObject c = daftar_rs.getJSONObject(i); 
//Continue here with a process to show a listview...

当没有互联网连接时,应用程序完全关闭并显示错误,有人知道我该如何解决吗?非常感谢你!老师们好!

4

1 回答 1

1

要检查您是否可以访问互联网,您可以使用类似的东西

public boolean connesso() {
        ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo netInfo = cm.getActiveNetworkInfo();
        if (netInfo != null && netInfo.isConnectedOrConnecting()) {
            return true;
        }
        return false;
    }

对于连接超时,我使用 httpclient 来发出请求,您也可以处理套接字超时

HttpParams httpParameters = new BasicHttpParams();
int timeout1 = 1000*10;
int timeout2 = 1000*10;
HttpConnectionParams.setConnectionTimeout(httpParameters, timeout1);
HttpConnectionParams.setSoTimeout(httpParameters, timeout2);
HttpClient httpclient = new DefaultHttpClient(httpParameters);

String jsonString = "";
HttpGet request;
try {
    request = new HttpGet(new URI(url));

    request.addHeader("User-Agent", "Android");

    HttpResponse response = httpclient.execute(request);

    StatusLine statusLine = response.getStatusLine();
    if (statusLine.getStatusCode() == HttpStatus.SC_OK) {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        response.getEntity().writeTo(out);
        out.close();
        jsonString = out.toString();
    }

    }catch(ConnectException e){             
    // handle your exception here, maybe something like
        Toast.makeText(context,"Error!",5000).show();
        finish(); // if your are within activity class, otherwise call finish on your activity          

    } catch (URISyntaxException e1) {
    // TODO Auto-generated catch block
        e1.printStackTrace();
        } catch (ClientProtocolException e) {
    // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
    // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    }
JSONObject myJsonObject = new JSONObject(jsonString);
// etc...
于 2013-04-02T19:19:04.727 回答