Não é possível chamar a API REST no Android
Estou tentando chamar um serviço web REST do meu telefone. Eu estou usando o código a seguir para concluir isso. Eu tenho apenas uma atividade que tem um botão e uma visão de texto. Sempre que eu clico no botão, ele dá o seguinte errologcat
:
AndroidRuntime :: at android.os.Handler.dispatchMessage(Handler.java:92)
O que estou fazendo errado? Como posso resolver isso ??? A seguir estão minhas aulas.
rest.java
public class Rest extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.start_rest);
Button button = (Button) findViewById(R.id.btn);
button.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
String url = "http://192.168.1.145/tst.php";
RestService re = new RestService();
JSONObject jb = RestService.doGet(url);
TextView tv = (TextView) findViewById(R.id.txtView);
tv.setText(jb.toString());
}
});
}
}
RestService.java
public class RestService {
public static JSONObject doGet(String url) {
JSONObject json = null;
HttpClient httpclient = new DefaultHttpClient();
// Prepare a request object
HttpGet httpget = new HttpGet(url);
// Accept JSON
httpget.addHeader("accept", "application/json");
// Execute the request
HttpResponse response;
try {
response = httpclient.execute(httpget);
// Get the response entity
// Log.e("myApp", "Issue is here...!");
HttpEntity entity = response.getEntity();
// If response entity is not null
if (entity != null) {
// get entity contents and convert it to string
InputStream instream = entity.getContent();
String result= convertStreamToString(instream);
// construct a JSON object with result
json=new JSONObject(result);
// Closing the input stream will trigger connection release
instream.close();
}
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// Return the json
return json;
}
private static String convertStreamToString(InputStream is) {
BufferedReader br = null;
StringBuilder sb = new StringBuilder();
String line;
try {
br = new BufferedReader(new InputStreamReader(is));
while ((line = br.readLine()) != null) {
sb.append(line);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return sb.toString();
}
}