httpUrlconnection将500错误代码返回给任何调用

时间:2016-08-01 03:20:50

标签: java android json web-services httpurlconnection

我的android代码在Amazon Elastic Beanstalk上调用php webservice(json)返回错误代码500,但getErrorStream返回正确的返回我的服务。

当我调用getInputStream时,我收到错误IOException,但是URL是正确的,当我用浏览器调用返回时是正确的。

我的代码:

public class AsyncLogin extends AsyncTask<String, String, String> {

    private Activity activity;

    public AsyncLogin(Activity activity)
    {
        this.activity = activity;
    }

    @Override
    protected String doInBackground(String... url) {

        StringBuilder resultado = new StringBuilder();
        try {
            String urlx = url[0];
            URL urlNet = new URL(urlx);
            HttpURLConnection conn= (HttpURLConnection) urlNet.openConnection();
            conn.setReadTimeout(10000);
            conn.setConnectTimeout(15000);
            conn.setRequestMethod("GET");
            conn.setRequestProperty("Content-Type", "application/json");
            conn.setUseCaches(false);

            conn.connect();

            int resposta = conn.getResponseCode();

            InputStream retorno = conn.getInputStream();
            BufferedReader br = new BufferedReader(new InputStreamReader(retorno));


            String linha = "";
            while ((linha=br.readLine())!= null)
            {
                resultado.append(linha);
            }

            conn.disconnect();

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

        return resultado.toString();
    }

    @Override
    protected void onPostExecute(String resultado){
        if (Boolean.valueOf(resultado))
        {
            Toast.makeText(activity, "1", Toast.LENGTH_LONG).show();
        }else {
            Toast.makeText(activity, "2", Toast.LENGTH_LONG).show();
        }

    }
}

我的php代码是:

<?php
    header('Content-type: application/json');
    $data = array(
    'Teste' => 'Alo mundo!'  
    );

    $resultado = json_encode($data);

    echo $resultado;
?>

1 个答案:

答案 0 :(得分:0)

我的PHP在最后一行代码行上有错误,当我在webbrowser上看到phpcode打印我的json没有显示错误,但最后一行生成错误代码500,当我用Android调用时,正确的错误代码是500。

我用我的php解决了最后一行(关闭连接),这段代码运行正常。