HTTP协议的应用与总结

最近在看Http协议等网络部分的知识,网络通而信可谓android中比较重要的部分了,而实现Http通信的最重要的莫过于俩个接口:HttpURLConnectionHttpClient。一般情况下俩个接口简单的访问网络。Apache提供的是后者,以后网络部分估计HttpClient用的较多一下。而且实现较容易理解一些。以下是源代码:首先实现的HttpURLConnectionGET方法,下面俩个接口的俩个方法即GETPOST均会实现。。。

public class BaiscHttpGetWay  {

         

         private String path1=null;

         private String resultData=null;

         public String getpath(String path) throws Exception

         {  

                   this.path1=path;

                   URL url=new URL(path1);

                   System.out.println(path1);

                     if(url!=null)

                     {             //由于get的方法相比较容易就不做解释了

                              HttpURLConnection conn=(HttpURLConnection)url.openConnection();

                              conn.setDoInput(true);

                              conn.setRequestMethod("GET");

                              conn.setConnectTimeout(5*1000);

                                if(conn.getResponseCode()==200)

                                {

                                         InputStream is=conn.getInputStream();

                                         resultData=getresultdata(is);

                                         System.out.println(resultData);

                           

                                }

                            conn.disconnect(); 

                             

                     }
 

                   return resultData;

         }

         private String getresultdata(InputStream is) throws Exception

         {

                   // TODO Auto-generated method stub

           ByteArrayOutputStream out=new ByteArrayOutputStream();

           byte[] buffer=new byte[1024];

           int len=-1;

           while((is.read(buffer))!=-1)

           {

                     out.write(buffer,0,len);
         

           }

           byte[] data=out.toByteArray();

                   return new String(data);

         }
    

}

然后是POSt方法的实现:

public class BasicHttpPostWay

{

         private String path1=null;

         private String resultData=null;

         public String getpath(String path,String param)throws Exception

         {  
                   //传递是以二进制传递字符串无法完成此操作所以用byte数组传递也可以用其他方法

                   byte[] data=param.getBytes();

                   this.path1=path;

                   URL url=new URL(path1);

                   System.out.println(path1);

                   if(url!=null)

                   {

                            HttpURLConnection conn=(HttpURLConnection)url.openConnection();

                            //这里是Post请求,所以就设置为true

                            conn.setDoInput(true);

                            conn.setDoOutput(true);

                            //设置请求Post

                            conn.setRequestMethod("POST");

                            conn.setConnectTimeout(5*1000);

                            //由于Post请求不能使用缓存

                            conn.setUseCaches(false);

                            conn.setInstanceFollowRedirects(true);

                            //设置其他畅通设置格式以及数组长度,不过若你不用数组直接用字符串的话

                            //查了一下可以用URLEcode.encode进行操作

                            conn.setRequestProperty("Connection","Keep-Alive" );

                            conn.setRequestProperty("Charset", "UTF-8");

                            conn.setRequestProperty("Content-Length",String.valueOf(data) );

                            //配置本次连接Content-type,后面参数正文为Orlencoded编码过的form参数具体是啥我也不知到反正为固定格式

                            conn.setRequestProperty("Content-Type","application/x-www-form-urlencoded" );

                            //连接,从打开连接即openConnection到connect之间必须先配好

                            conn.connect();

                            //查了一下大部分Post都是用DataOutputStream完成此操作

                            DataOutputStream out=new DataOutputStream(conn.getOutputStream());

                             out.write(data);

                             //刷新,关闭

                             out.flush();

                             out.close();

                             if(conn.getResponseCode()==200)

                             {

                                      InputStream is=conn.getInputStream();

                                      //定义一个方法用来转换流的内容

                                       resultData=getresultData(is);

                                      System.out.println(resultData);

                             }

                            

                            conn.disconnect();

                   }
                   return resultData;

         }

         private String getresultData(InputStream is) throws Exception

         {        // TODO Auto-generated method stub

                     ByteArrayOutputStream out=new ByteArrayOutputStream();

                     byte[] buffer=new byte[1024];

                     int len=-1;

                     while((is.read(buffer))!=-1)

                     {

                              out.write(buffer,0,len);

                     }

                     byte[] data=out.toByteArray();
                            return new String(data);

         }

 

}

接下来是HttpClient借口中方法的实现:

首先是GET方法:
public class ApacheHttpGetWay

{

         

         private String  path1=null;

         private String  resultDataString=null;

         

         public String getpath(String path)throws Exception

         { 

                    this.path1=path;

                    //HttpGet的连接对象

                    HttpGet httpGet=new HttpGet(path1);

                    //声明一个HttpClient的对象

                    HttpClient httpClient=new DefaultHttpClient();

                    //执行请求并用HttpResponse接受请求过来的内容

                    HttpResponse httpResponse=httpClient.execute(httpGet);

                    //判断请求是否成功

                    if(httpResponse.getStatusLine().getStatusCode()==HttpStatus.SC_OK)

                    {  //取得返回的字符串

                             resultDataString=EntityUtils.toString(httpResponse.getEntity());

                             System.out.println(resultDataString);

                             

                    }

                    else 

                             {

                         System.out.println("it is null!!!");                

                             }

                   return resultDataString;

                   

                   

         }

}

//然后是POST方法
 

public class ApacheHttpPostWay

 

{

        private String  path1=null;

        private String  resultDataString=null;

 

         public String getpath(String path,List<NameValuePair> param)throws Exception

         {   

                   this.path1=path;

                   //设置连接对象即连接请求

                   HttpPost post=new HttpPost(path1);

                   //将参数加入请求里面定死的

                   post.setEntity(new UrlEncodedFormEntity(param,HTTP.UTF_8));

                   //获取HttpClient的对象

                   HttpClient httpClient=new DefaultHttpClient();

                   //执行请求并将字符返回到httpResponse

                   HttpResponse httpResponse=httpClient.execute(post);

                   //判断是否连接成功格式定死的

                   if(httpResponse.getStatusLine().getStatusCode()==HttpStatus.SC_OK)

                   { //返回字符串格式定死的

                            resultDataString=EntityUtils.toString(httpResponse.getEntity());

                            System.out.println(resultDataString);

                   }

                   else {

                            System.out.println("it is null!!!");

                   }
                   return resultDataString;

         }

 

}


总之而言,在做项目的过程中POST方法使用的较多,因其保密性较好,不过GET用的也较多,所以看个人喜好了。在学习这一块内容的时候要好好把握俩个接口的使用法,这样才能不容易记混!!

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值