* 步驟:
1. 建立HttpClient對象
2. 建立HttpGet或者HttpPost對象。將地址傳給構造方法。
3. 讓HttpClient對象執行請求。獲得響應對象HttpResponse
4. 從HttpResponse對象中獲得響應碼。
5. 判斷響應碼是否爲200,若是200則得到HttpEntity.
6. 用EntityUtils將數據從HttpEntity中得到數組
//http://localhost:8080/MyServer/login?username=admin&userpwd=111
String path = "http://localhost:8080/MyServer/login"; //1:建立HttpClient
HttpClient client = new DefaultHttpClient(); //2:建立請求。
HttpPost post = new HttpPost(path); //將數據封裝到post對象裏。 //建立一個存儲封裝鍵值對對象的集合
List<NameValuePair> params = new ArrayList<NameValuePair>(); //將數據封裝到NameValuePair對象裏,第一個參數爲鍵,第二個參數爲值
NameValuePair value1 = new BasicNameValuePair("username", "admin"); NameValuePair value2 = new BasicNameValuePair("userpwd", "1112"); //將對象添加到集合中。
params.add(value1); params.add(value2); //將數據集合封裝成HttpEntity
HttpEntity entity = new UrlEncodedFormEntity(params); //設置HttpEntity
post.setEntity(entity); //讓客戶端執行請求。
HttpResponse response = client.execute(post); int code = response.getStatusLine().getStatusCode(); if(code==200){ HttpEntity result_entity = response.getEntity(); String str = EntityUtils.toString(result_entity); System.out.println(str); }
//建立HttpClient對象--客戶端
HttpClient client = new DefaultHttpClient(); //建立請求。---Get:HttpGet
String path = "http://a3.att.hudong.com/36/11/300001378293131694113168235_950.jpg"; HttpGet get = new HttpGet(path); //讓客戶端執行請求。獲得響應對象
try { HttpResponse response = client.execute(get); //獲得響應碼。:響應碼和服務器端發送給客戶端的數據都封裝在HttpResponse裏。
int code = response.getStatusLine().getStatusCode(); if(code==200){ //成功響應。 //獲得服務器端的數據。
HttpEntity entity = response.getEntity(); byte[] b = EntityUtils.toByteArray(entity); //將byte數組的數據寫到文件中。
FileOutputStream fos = new FileOutputStream("f:\\a3.jpg"); fos.write(b); fos.close(); }