关于android:bufferedReader for URL抛出IOException

bufferedReader for URL throws IOException

我得到了我的代码连接到我的计算机php文件并在java程序中输出正确的文本。 当我试图将它添加到我的android项目以显示高分时它总是抛出IOException并且我无法弄清楚原因。 这是我的代码。 任何帮助,将不胜感激。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
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("It Worked!");
        }
        catch(MalformedURLException e)
        {
         HscoreText.setText("MalformedURL");
        }
        catch (IOException e)
        {
         HscoreText.setText("IOException");
  }

    }

}

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

1
2
3
4
5
6
7
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将是单行,因此您可以使用:

1
2
String sResponse = reader.readLine();
JSONObject JResponse = new JSONObject(sResponse);

否则将整个内容作为字符串获取:

1
2
3
4
5
6
String sResponse;
StringBuilder s = new StringBuilder();

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