【发布时间】:2016-08-01 03:20:49
【问题描述】:
我的 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;
?>
【问题讨论】:
-
500 错误是服务器端。请你把
stacktrace日志 -
在 onPostExecute 你应该 Toast
resultado。现在你什么也看不见了。 -
内容类型为 application/json 的 GET? json 在哪里?
-
500 错误是服务器端,但是当我用浏览器调用它时工作正常。
-
我用 POST 和 GET 试试这个,但效果不好
标签: java android json web-services httpurlconnection