Я написал класс Android, который будет называть веб-службу RESTful. Если запрос выполнен успешно, ответ будет 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();
}
}
У меня проблема после того, как я запустил. Я получу исключение coz, я возвращаюсь как строка. Но ответ JSON. Как мне преобразовать JSON в String или другим способом, а затем как показать результат на экране Android?
спасибо
well "http://localhost: 8080/kyaw" - проблема... этим вы используете эмулятор не эмулятор-хост... и вы получаете сетевую ошибку
попробуйте "http://ip.of.your.host:8080/kyaw"
EDIT:
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
Я просто делаю это:
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);
}