實現該方法需要導入一些jar包
可以去一下地址下載:
http://pan.baidu.com/s/1hqrJF7m
?
java重寫?/**
* 實用工具類來獲取服務器資源
*
* get方法傳送數據
*
* 1、通過path設定傳送方式
* 2、創建客戶端
* 3、得到輸入流
* 4、讀取流準備工作
* 5、讀取并寫入
* @throws IOException
* @throws ClientProtocolException
*
*/
1 public static String getHttpResult(String path) throws ClientProtocolException, IOException{ 2 /*1、通過path設定傳送方式*/ 3 4 HttpGet get=new HttpGet(path); 5 /*2、創建客戶端*/ 6 HttpClient client=new DefaultHttpClient(); 7 //通過get方式發送數據給服務器 8 HttpResponse response=client.execute(get); 9 /*3、得到輸入流*/ 10 if(response.getStatusLine().getStatusCode()==200){ 11 InputStream in=response.getEntity().getContent(); 12 13 /*4、讀取流準備工作*/ 14 ByteArrayOutputStream bos=new ByteArrayOutputStream(); 15 byte[]arr=new byte [1024]; 16 int len=0; 17 18 /*5、讀取并寫入*/ 19 while((len=in.read(arr))!=-1){ 20 bos.write(arr, 0, len); 21 } 22 byte[]b=bos.toByteArray(); 23 return new String(b,0,b.length); 24 } 25 26 27 28 return null; 29 }
?
/**
* 實用工具類來獲取服務器資源
*
* Post方法傳送數據
*
* 1、通過path設定傳送方式
* 2、創建客戶端
* 3、得到輸入流
* 4、讀取流準備工作
* 5、讀取并寫入
* @throws IOException
* @throws ClientProtocolException
*
*/
1 public static String getHttpResult(String path) throws ClientProtocolException, IOException{ 2 /*0、初始化要發送的數據用list存儲*/ 3 List<NameValuePair> list=new ArrayList<NameValuePair>(); 4 list.add(new BasicNameValuePair("name", "zhangsan")); 5 list.add(new BasicNameValuePair("name", "lisi")); 6 list.add(new BasicNameValuePair("name", "wangwu")); 7 /*1、通過path設定傳送方式*/ 8 9 HttpPost post=new HttpPost(path); 10 /*2、創建客戶端*/ 11 HttpClient client=new DefaultHttpClient(); 12 //通過post表單方式發送數據給服務器 13 14 //建立表單 15 UrlEncodedFormEntity entity=new UrlEncodedFormEntity(list,"utf-8"); 16 //裝載到post中 17 post.setEntity(entity); 18 19 HttpResponse response=client.execute(post); 20 /*3、得到輸入流*/ 21 if(response.getStatusLine().getStatusCode()==200){ 22 InputStream in=response.getEntity().getContent(); 23 24 /*4、讀取流準備工作*/ 25 ByteArrayOutputStream bos=new ByteArrayOutputStream(); 26 byte[]arr=new byte [1024]; 27 int len=0; 28 29 /*5、讀取并寫入*/ 30 while((len=in.read(arr))!=-1){ 31 bos.write(arr, 0, len); 32 } 33 byte[]b=bos.toByteArray(); 34 return new String(b,0,b.length); 35 } 36 37 38 39 return null; 40 } 41
?