使用BufferedReader读取URL时抛出IOException。

7

我已经成功地将代码连接到了计算机的php文件,并在Java程序中输出了正确的文本。但是,当我尝试将它添加到我的Android项目中以显示高分时,总是会抛出一个IOException错误,我无法找出原因。以下是我的代码。如果您能提供任何帮助,我将不胜感激。

package com.enophz.spacetrash;
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.MalformedURLException; import java.net.URL; import java.net.URLConnection;
import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.TextView; public class Scores extends Activity {
//private TextView HscoreText;
/** Called when the activity is first created. */ public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.scores);
Button next = (Button) findViewById(R.id.Button01); next.setOnClickListener(new View.OnClickListener() { public void onClick(View view) { Intent myIntent = new Intent(view.getContext(), Menu.class); startActivity(myIntent); }
});
TextView HscoreText = (TextView) findViewById(R.id.text);
try { URL page = new URL("http://192.168.1.108/score.php"); URLConnection pageconnection = page.openConnection(); BufferedReader in = new BufferedReader( new InputStreamReader( pageconnection.getInputStream()));
in.close();
HscoreText.setText("它起作用了!"); } catch(MalformedURLException e) { HscoreText.setText("URL格式错误"); } catch (IOException e) { HscoreText.setText("输入/输出错误"); }
}
}
1个回答

3

我不知道你希望从php页面获取什么类型的内容.. 但是以下方法可以帮助你从Web服务器获取内容:

HttpClient httpClient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
HttpGet httpGet = new HttpGet(myUrl);

HttpResponse response = httpClient.execute(httpGet, localContext);
BufferedReader reader = new BufferedReader(new InputStreamReader(
    response.getEntity().getContent(), "UTF-8"));

现在JSON将是单行的,因此您可以使用以下内容:
String sResponse = reader.readLine();
JSONObject JResponse = new JSONObject(sResponse);

否则,可以将整个内容作为字符串获取:
String sResponse;
StringBuilder s = new StringBuilder();

while ((sResponse = reader.readLine()) != null) {
s = s.append(sResponse);
}

我已经修改了我的代码以匹配你的示例。它可以编译,但在模拟器中运行时仍会抛出IOException异常。我的score.php页面只是输出一行JSON。 - drewsmug
两个示例中有问题的代码行都是使用 BufferedReader。使用 BufferedReader 读取网络连接不是最好的方法吗? - drewsmug
观察LogCat中的错误。检查您是否在清单中提供了Internet连接权限。此外,您的计算机localhost将在模拟器中为10.0.2.2。 - Vikas

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接