我想創建一個使用android的移動客戶端來使用本地REST API 我已經在eclipse上創建了其他服務器並且運行沒有問題 但我試圖創建我的客戶端Android工作室,它也在運行,但是當我點擊按鈕時沒有任何事情發生。如何使用Android REST api
public class MainActivity extends AppCompatActivity {
private Button btnChercher;
private TextView tvJson;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnChercher = (Button) findViewById(R.id.btnchercher);
tvJson = (TextView) findViewById(R.id.tvJson);
btnChercher.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
new JsonTask().execute("http://localhost:8080/membres");
}
}
);
}
public class JsonTask extends AsyncTask<String,String,String>{
@Override
protected String doInBackground(String... params) {
HttpURLConnection connection=null;
BufferedReader reader=null;
try {
URL url = new URL(params[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer = new StringBuffer();
String line ="";
while ((line=reader.readLine())!=null){
buffer.append(line);
}
String finalJson = buffer.toString();
JSONObject parentObject = new JSONObject();
JSONArray parentArray = parentObject.getJSONArray("");
JSONObject finalObject = parentArray.getJSONObject(0);
String nomMembre = finalObject.getString("nomMembre");
return nomMembre+"\n";
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
} finally {
if(connection!=null){
connection.disconnect();
}
if(reader!=null){
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return null;
}
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
tvJson.setText(result);
}
}
}`
研究使用[Retrofit](http://square.github.io/retrofit/)它簡化了大部分創建REST客戶端的工作。 – chRyNaN