Android和JSON。捕获异常 - 错误链接

时间:2014-01-19 00:34:16

标签: android json exception-handling

我正在创建一个通过JSON与服务器通信的应用程序。用户可以输入服务器的地址,并且当用户输入错误的链接时我想提供受控的行为。我不想通过捕捉一般异常来隐藏问题,我想抓住具体的一个,但我无法弄清楚如何。

当用户输入错误的链接时,这是一个日志:

01-19 00:08:10.205: W/dalvikvm(12576): threadid=12: thread exiting with uncaught exception (group=0x410af2a0)
01-19 00:08:10.220: E/AndroidRuntime(12576): FATAL EXCEPTION: AsyncTask #1
01-19 00:08:10.220: E/AndroidRuntime(12576): java.lang.RuntimeException: An error     occured while executing doInBackground()
01-19 00:08:10.220: E/AndroidRuntime(12576):    at     android.os.AsyncTask$3.done(AsyncTask.java:299)
01-19 00:08:10.220: E/AndroidRuntime(12576):    at     java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
01-19 00:08:10.220: E/AndroidRuntime(12576):    at     java.util.concurrent.FutureTask.setException(FutureTask.java:124)
01-19 00:08:10.220: E/AndroidRuntime(12576):    at     java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
01-19 00:08:10.220: E/AndroidRuntime(12576):    at     java.util.concurrent.FutureTask.run(FutureTask.java:137)
01-19 00:08:10.220: E/AndroidRuntime(12576):    at     android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
01-19 00:08:10.220: E/AndroidRuntime(12576):    at     java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
01-19 00:08:10.220: E/AndroidRuntime(12576):    at     java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
01-19 00:08:10.220: E/AndroidRuntime(12576):    at     java.lang.Thread.run(Thread.java:856)
01-19 00:08:10.220: E/AndroidRuntime(12576): Caused by: java.lang.IllegalStateException:     Target host must not be null, or set in parameters. scheme=null, host=null, path=aaaaaasss
01-19 00:08:10.220: E/AndroidRuntime(12576):    at     org.apache.http.impl.client.DefaultRequestDirector.determineRoute(DefaultRequestDirector.jav    a:591)
01-19 00:08:10.220: E/AndroidRuntime(12576):    at     org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:293)
01-19 00:08:10.220: E/AndroidRuntime(12576):    at         org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:670)
01-19 00:08:10.220: E/AndroidRuntime(12576):    at     org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:509)
01-19 00:08:10.220: E/AndroidRuntime(12576):    at     org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
01-19 00:08:10.220: E/AndroidRuntime(12576):    at     pl.mosek.micro.JSONParser.makeHttpRequestJSONObject(JSONParser.java:62)
01-19 00:08:10.220: E/AndroidRuntime(12576):    at     pl.mosek.micro.SignInActivity$UserLoginTask.doInBackground(SignInActivity.java:287)
01-19 00:08:10.220: E/AndroidRuntime(12576):    at     pl.mosek.micro.SignInActivity$UserLoginTask.doInBackground(SignInActivity.java:1)
01-19 00:08:10.220: E/AndroidRuntime(12576):    at     android.os.AsyncTask$2.call(AsyncTask.java:287)
01-19 00:08:10.220: E/AndroidRuntime(12576):    at     java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
01-19 00:08:10.220: E/AndroidRuntime(12576):    ... 5 more

这是JSONParser类:

public class JSONParser {

static InputStream is = null;
static JSONObject jObj = null;
static JSONArray jArray = null;
static String json = "";
private boolean started = false;
private boolean finished = false;

public static String getJson() {
    return json;
}

// constructor
public JSONParser() {

}

// function get json from url
// by making HTTP POST or GET mehtod
public JSONObject makeHttpRequestJSONObject(String url, String method,
        List<NameValuePair> params) {

    finished = false;
    started = true;

    // Making HTTP request
    try {

        // check for request method
        if (method == "POST") {
            // request method is POST
            // defaultHttpClient
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url);
            httpPost.setEntity(new UrlEncodedFormEntity(params));

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

        } else if (method == "GET") {
            // request method is GET
            DefaultHttpClient httpClient = new DefaultHttpClient();
            String paramString = URLEncodedUtils.format(params, "utf-8");
            url += "?" + paramString;
            HttpGet httpGet = new HttpGet(url);

            HttpResponse httpResponse = httpClient.execute(httpGet);
            HttpEntity httpEntity = httpResponse.getEntity();
            is = httpEntity.getContent();
        }

    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    try {
        BufferedReader reader = new BufferedReader(new InputStreamReader(
                is, "iso-8859-1"), 8);
        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }
        is.close();
        json = sb.toString();
    } catch (Exception e) {
        Log.e("Buffer Error", "Error converting result " + e.toString());
    }

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

    started = false;
    finished = true;
    // return JSON String
    return jObj;

}

public JSONArray makeHttpRequestJSONArray(String url, String method,
        List<NameValuePair> params) {

    finished = false;
    started = true;

    // Making HTTP request
    try {

        // check for request method
        if (method == "POST") {
            // request method is POST
            // defaultHttpClient
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url);
            httpPost.setEntity(new UrlEncodedFormEntity(params));

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

        } else if (method == "GET") {
            // request method is GET
            DefaultHttpClient httpClient = new DefaultHttpClient();
            String paramString = URLEncodedUtils.format(params, "utf-8");
            url += "?" + paramString;
            HttpGet httpGet = new HttpGet(url);

            HttpResponse httpResponse = httpClient.execute(httpGet);
            HttpEntity httpEntity = httpResponse.getEntity();
            is = httpEntity.getContent();
        }

    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    try {
        BufferedReader reader = new BufferedReader(new InputStreamReader(
                is, "iso-8859-1"), 8);
        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }
        is.close();
        json = sb.toString();
    } catch (Exception e) {
        Log.e("Buffer Error", "Error converting result " + e.toString());
    }

    // try parse the string to a JSON object
    try {
        jArray = new JSONArray(json);
    } catch (JSONException e) {
        Log.e("JSON Parser", "Error parsing data " + e.toString());
    }

    started = false;
    finished = true;
    // return JSON String
    return jArray;

}

public boolean isStarted() {
    return started;
}

public boolean isFinished() {
    return finished;
}

}

我应该怎样做以捕捉特定的例外?

3 个答案:

答案 0 :(得分:0)

你可以抓住:

IllegalStateException (Exception e)

或者您可以在执行请求之前检查错误输入。

答案 1 :(得分:0)

pl.mosek.micro.JSONParser.makeHttpRequestJSONObject(JSONParser.java:62)

我不知道你的线在哪里(62),但你可以看到错误:

  

目标主机不能为空,或者在参数中设置。方案= NULL,   host = null,path = aaaaaasss

我认为你应该在使用前检查null。

在这一行:

httpPost.setEntity(new UrlEncodedFormEntity(params));

params是否为空?

而且几乎很重要,请检查您的InputStream

BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);

is是否为空?

答案 2 :(得分:0)

您正在以Java无法比较的方式比较字符串。

应该是:

if ("POST".equals(method))

你们都没有评价为真,所以你没有设置URL而HTTP对象也在窒息。