我的 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;
?>
最佳答案
我的 PHP 在最后一行代码上有错误,当我在网络浏览器上看到 phpcode 打印我的 json 时没有显示错误,但最后一行生成错误代码 500,当我用 Android 调用时,正确的错误代码是 500。
我用我的 php 解决了最后一行(关闭连接),这段代码工作正常。
关于java - httpUrlconnection 向任何调用返回 500 错误代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38690538/