用Java的HttpClient写一个简单的http请求和返回

468 篇文章 0 订阅
Java代码   收藏代码
  1. import java.io.BufferedReader;  
  2. import java.io.IOException;  
  3. import java.io.InputStream;  
  4. import java.io.InputStreamReader;  
  5.   
  6. import org.apache.http.HttpEntity;  
  7. import org.apache.http.HttpResponse;  
  8. import org.apache.http.client.ClientProtocolException;  
  9. import org.apache.http.client.HttpClient;  
  10. import org.apache.http.client.methods.HttpGet;  
  11. import org.apache.http.impl.client.DefaultHttpClient;  
  12.   
  13. public class TTT  
  14. {  
  15.   
  16.     /** 
  17.      * @param args 
  18.      * @throws IOException  
  19.      * @throws ClientProtocolException  
  20.      */  
  21.     public static void main(String[] args) throws ClientProtocolException, IOException  
  22.     {  
  23.         // 创建HttpClient实例     
  24.         HttpClient httpclient = new DefaultHttpClient();  
  25.         // 创建Get方法实例     
  26.         HttpGet httpgets = new HttpGet("http://127.0.0.1/testhttp.php?username=yonghuming");    
  27.         HttpResponse response = httpclient.execute(httpgets);    
  28.         HttpEntity entity = response.getEntity();    
  29.         if (entity != null) {    
  30.             InputStream instreams = entity.getContent();    
  31.             String str = convertStreamToString(instreams);  
  32.             System.out.println("Do something");   
  33.             System.out.println(str);  
  34.             // Do not need the rest    
  35.             httpgets.abort();    
  36.         }  
  37.     }  
  38.       
  39.     public static String convertStreamToString(InputStream is) {      
  40.         BufferedReader reader = new BufferedReader(new InputStreamReader(is));      
  41.         StringBuilder sb = new StringBuilder();      
  42.        
  43.         String line = null;      
  44.         try {      
  45.             while ((line = reader.readLine()) != null) {  
  46.                 sb.append(line + "\n");      
  47.             }      
  48.         } catch (IOException e) {      
  49.             e.printStackTrace();      
  50.         } finally {      
  51.             try {      
  52.                 is.close();      
  53.             } catch (IOException e) {      
  54.                e.printStackTrace();      
  55.             }      
  56.         }      
  57.         return sb.toString();      
  58.     }  
  59.   
  60. }  

 

 

HTTP服务器的testhttp.php内容如下

Php代码   收藏代码
  1. <?php  
  2. if ($_GET['username'])   
  3. {  
  4.     $dt["username"] = $_GET['username'];  
  5.         echo json_encode($dt);  
  6. }  
  7. ?>  

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值