我编写了一个调用RESTful Web服务的android类。如果请求成功, 响应将是JSON对象。我写这样的android类:
public class android extends Activity {
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();
}
}
我运行后遇到问题。我会得到异常因为我返回一个字符串。但是响应是JSON。我应该如何将JSON转换为String或其他方式然后如何在android屏幕中显示结果?
感谢
答案 0 :(得分: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);
}
答案 1 :(得分:1)
好“http:// localhost:8080 / kyaw”是一个问题...由此你想到模拟器而不是模拟器的主机...并且你得到网络错误
尝试“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