如何使用android使用REST api [英] How to consume REST api with android
本文介绍了如何使用android使用REST api的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试创建一个使用android的移动客户端来使用我在eclipse上创建了休息服务器的本地REST API并且它运行没有问题但我正在尝试在android studio上创建我的客户端并且它也在运行但是当我点击按钮没有发生任何事情。
我尝试过:
I am trying to create a mobile client using android to consume a local REST API I have created rest server on eclipse and it is running without problems but i am trying to create my client on android studio and it is running also but when i click on the button nothing is happening.
What I have tried:
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);
}
}
}
推荐答案
localhost是当前的主机(Android应用程序),所以你应该用服务器计算机名称或服务器IP替换本地主机。
http:// localhost:8080 / membres替换为http :// server_ip:8080 / membres
goodluck
Hi,
localhost is current host (android app), so you should replace local host with server computer name or server IP.
http://localhost:8080/membres replace with http://server_ip:8080/membres
goodluck
这篇关于如何使用android使用REST api的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文