标签:
package com.pingyijinren.test; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.Button; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.util.EntityUtils; import org.json.JSONArray; import org.json.JSONObject; public class MainActivity extends AppCompatActivity{ private Button button; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); button=(Button)findViewById(R.id.button); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { sendRequestWithHttpURLConnection(); } }); } private void sendRequestWithHttpURLConnection(){ new Thread(new Runnable(){ @Override public void run(){ try{ HttpClient httpClient = new DefaultHttpClient(); HttpGet httpGet=new HttpGet("http://172.29.209.1/get_data.json"); HttpResponse httpResponse=httpClient.execute(httpGet); if(httpResponse.getStatusLine().getStatusCode()==200){ HttpEntity httpEntity=httpResponse.getEntity(); String response= EntityUtils.toString(httpEntity,"utf-8"); parseJSONWithJSONObject(response); } } catch(Exception e){ e.printStackTrace(); } } }).start(); } private void parseJSONWithJSONObject(String jsonData){ try{ JSONArray jsonArray=new JSONArray(jsonData); for(int i=0;i<jsonArray.length();i++){ JSONObject jsonObject=jsonArray.getJSONObject(i); Log.d("MainActivity","id is "+jsonObject.getString("id")); Log.d("MainActivity","version is "+jsonObject.getString("version")); Log.d("MainActivity","name is "+jsonObject.getString("name")); } } catch(Exception e){ e.printStackTrace(); } } }
标签:
原文地址:http://www.cnblogs.com/zqxLonely/p/5508507.html