2011-05-19 31 views
1

我已经编写了Android类,它将调用RESTful Web服务。如果请求成功,则 响应将是JSON对象。我写的android类是这样的:如何将JSON响应转换为字符串并在屏幕中显示?

公共类的Android扩展活动{

public void onCreate(Bundle savedInstanceState) 
    { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.main); 
    TextView txt = (TextView) findViewById(R.id.textView1); 
    txt.setText(getInputStreamFromUrl("http://localhost:8080/kyaw")); 
    } 

    public static String getInputStreamFromUrl(String url) { 
      InputStream content = null; 
      try { 
      HttpClient httpclient = new DefaultHttpClient(); 
      HttpResponse response = httpclient.execute(new HttpGet(url)); 
      content = response.getEntity().getContent(); 
      } catch (Exception e) { 
      Log.e("[GET REQUEST]", "Network exception"); 
      } 
      String result=convert(content); 
      return result; 
     } 

    private static String convert(InputStream in) 
    { 
     BufferedReader reader=new BufferedReader(new InputStreamReader(in)); 
     StringBuilder sb=new StringBuilder(); 
     String line=null; 
     try{ 
      while((line=reader.readLine())!=null){ 
       sb.append(line+"\n"); 
      } 
     }catch(Exception e) 
     { 
      e.printStackTrace(); 
     }finally{ 
      try{ 
       in.close(); 
      }catch(IOException e){ 
       e.printStackTrace(); 
      } 
     } 
     return sb.toString(); 
    } 

}

我有一个问题后,我run.I会得到异常怎么我返回的响应string.But是JSON。我应该如何将JSON转换为字符串或其他方式,然后如何在Android屏幕上显示结果?

感谢enter image description here

+0

什么异常? FC?来自服务器的JSON响应是一个字符串。 – Selvin 2011-05-19 07:47:36

+0

嗨selvin,当我运行类andriod虚拟设备提醒我有异常然后关闭,但不显示什么异常。我调试它,我发现在HttpResponse响应= httpclient.execute(新HttpGet(URL))异常; 。我不知道为什么,我是新来的 – sudo 2011-05-19 07:57:09

+0

首先启用Logcat http://stackoverflow.com/questions/3280051/how-to-enable-logcat-in-eclipse。第二提供日志从logcat窗口 – Selvin 2011-05-19 07:59:24

回答

1

很好的 “http://本地主机:8080 /觉” 是一个问题......这个你poining不要仿真器仿真器的主机。 ..你让网络错误

尝试 “http://ip.of.your.host:8080/kyaw”

编辑:

 content = response.getEntity().getContent();// here comes an error 
     } catch (Exception e) { 
     Log.e("[GET REQUEST]", "Network exception");//we catch it here 
     } 
     //here you got content == null 
     //so you getting null point exception 
+0

thanks selvin。它解决了 – sudo 2011-05-19 11:40:42

1

我只是这样做:

HttpClient client = new DefaultHttpClient(); 
HttpPost poster = new HttpPost("http://www.example.com/json.php"); 
poster.addHeader("Content-Type", "text/json"); 
poster.setEntity(new StringEntity(data.toString())); 
//data being a json object created and filled earlier 
HttpResponse response = client.execute(poster);         
if(response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) 
{ 
    DataInputStream input = new DataInputStream(response.getEntity().getContent()); 
    JSONObject json = new JSONObject(input.readLine()); 
    json.toString(2); 
} 
相关问题