调用getResponseCode()时应用程序崩溃

时间:2017-10-29 13:47:35

标签: java php android android-studio

这是我的代码

public static ArrayList<KeyValue> peticionRest(final ArrayList<KeyValue> parametros, final String funcionAPI, final String metodo){

    ArrayList<KeyValue> respuesta = new ArrayList<>();
    try {

        respuesta.clear();

        String urlParametros = URLEncoder.encode(parametros.get(0).getKey(), "utf-8")+"="+URLEncoder.encode(parametros.get(0).getValue(), "utf-8");
        for (int x = 1; x < parametros.size(); x++){
            urlParametros += "&"+URLEncoder.encode(parametros.get(x).getKey(), "utf-8")+"="+URLEncoder.encode(parametros.get(x).getValue(), "utf-8");
        }

        String stringURL = "url to site";
        URL url = new URL(stringURL);


        HttpURLConnection myConnection = (HttpURLConnection) url.openConnection();
        myConnection.setInstanceFollowRedirects(false);

        if (metodo.equals("post")){
            myConnection.setDoOutput(true);
        }
        for (int x = 0; x < parametros.size(); x++){
            myConnection.setRequestProperty(parametros.get(x).getKey(), parametros.get(x).getValue());
        }

        if (myConnection.getResponseCode() == 200) {


            InputStream responseBody = myConnection.getInputStream();
            InputStreamReader responseBodyReader = new InputStreamReader(responseBody, "UTF-8");
            JsonReader jsonReader = new JsonReader(responseBodyReader);
            jsonReader.setLenient(true);
            jsonReader.beginObject(); // Start processi ng the JSON object
            while (jsonReader.hasNext()) { // Loop through all keys
                String key = jsonReader.nextName(); // Fetch the next key
                String value = jsonReader.nextString();
                respuesta.add(new KeyValue(key, value));
            }
            jsonReader.close();

        } else {

            respuesta.add(new KeyValue("ok", "false"));
            respuesta.add(new KeyValue("error", "error en la peticion"));
        }
        myConnection.disconnect();

    } catch (Exception e) {
        e.printStackTrace();

    }
    return respuesta;

}

我得到一个“java.lang.IndexOutOfBoundsException:Index:0,Size:0”,因为respuesta为空。 如果我记录网址并单击它,它工作正常。 程序到达myConnection.getResponseCode()

时停止

有什么想法吗? 提前谢谢!

1 个答案:

答案 0 :(得分:0)

你的问题是

  

&#34; java.lang.IndexOutOfBoundsException:Index:0,Size:0

您的代码中有两个List。因此可能会导致其中。

在您的代码中。

 String urlParametros = URLEncoder.encode(parametros.get(0).getKey(), "utf-8")+"="+URLEncoder.encode(parametros.get(0).getValue(), "utf-8");

您使用parametros.get(0).getKey()。可能是问题所在。

试试这个。

在代码中致电parametros之前。

if(parametros != null && parametros.size() > 0){
    // you can do something here 
    String urlParametros = URLEncoder.encode(parametros.get(0).getKey(), "utf-8")+"="+URLEncoder.encode(parametros.get(0).getValue(), "utf-8");
}