1. 程式人生 > >Httpclient的Get請求和Post請求

Httpclient的Get請求和Post請求

public class MainActivity extends Activity {
	private ListView listView;
	private ArrayList list;
	private Handler handler=new Handler(){
		public void handleMessage(android.os.Message msg) {
			listView.setAdapter(new ArrayAdapter(MainActivity.this, android.R.layout.simple_list_item_1, list));
		};
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		listView=(ListView) findViewById(R.id.listView);
		getData();
		
		
		
	}

	private void getData() {
		new Thread(){
			public void run() {
				try {
					//創建出HttpClient物件
					DefaultHttpClient httpClient = new DefaultHttpClient();
					//創建出請求方法
					HttpPost httpPost = new HttpPost(Url.POST_TEST);
					//創建出一個集合用來存放資料
					ArrayList list=new ArrayList();
					//把要請求的引數封裝到BasicNameValuePair類的物件
					BasicNameValuePair nameValuePair = new BasicNameValuePair("type", "junshi");
					BasicNameValuePair nameValuePair2 = new BasicNameValuePair("key", "2f41498b35e69877fc56dc96776e5d1f");
					//把物件存入集合
					list.add(nameValuePair);
					list.add(nameValuePair2);
					//把集合放入實體
					UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list);
					//執行
					httpPost.setEntity(entity);
					//執行post方法,請求網路資料
					HttpResponse response = httpClient.execute(httpPost);
					//獲得狀態行
					StatusLine line = response.getStatusLine();
					//獲得狀態碼
					int i = line.getStatusCode();
					//判斷
					if(i==200){
						//得到內容實體
						HttpEntity httpEntity = response.getEntity();
						//得到具體內容
						InputStream content = httpEntity.getContent();
						String json = inputToString(content);
						parseJson(json);
						handler.sendEmptyMessage(0);
					}
					
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}


		}.start();
		
	}
	

	private String inputToString(InputStream content) {
		ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
		int len=0;
		byte[] bt=new byte[1024];
		try {
			while((len=content.read(bt))!=-1){
				outputStream.write(bt, 0, len);
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return outputStream.toString();
		
	};
	

	private void parseJson(String json) {
		list = new ArrayList();
		try {
			JSONObject jsonObject = new JSONObject(json);
			JSONObject jsonObject2 = jsonObject.getJSONObject("result");
			JSONArray data = jsonObject2.getJSONArray("data");
			for (int i = 0; i < data.length(); i++) {
				JSONObject jsonObject3 = data.getJSONObject(i);
				String title = jsonObject3.getString("title");
				list.add(title);
			}
			
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}


}