http 网络请求 下载图片

访问网络最主要的也就是 http协议了。

http协议很简单,但是很重要。

直接上代码了,里面都是1个代码块 代码块的,用哪一部分直接拷出去用就好了。


1.访问网络用 get 和 post 自己组拼提交参数 ,httpclient 方式提交

2.上传 和 下载

3.比如访问服务器后 返回来的 xml 和 json 的简单解析方法

<p>HttpClient其实是一个interface类型,HttpClient封装了对象需要执行的Http请求、身份验证、连接管理和其它特性</p>
<p>HttpClient有三个已知的实现类分别是:</p>
<p>AbstractHttpClient, AndroidHttpClient, DefaultHttpClient<br>
</p>
<p> AndroidHttpClient是对HttpClient的包装,内部带访问连接器,并设置为可以多线程使用,</p>
String  path = "http://192.168.13.1";
    String  username ="ll";
    String  pwd="123";
     
    /**   get 组拼    */
    public void  httpGet()
            throws Exception {
     
        String param1 = URLEncoder.encode(username);
        String param2 = URLEncoder.encode(pwd);
        URL url = new URL(path + "?name=" + param1 + "&password=" + param2);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("GET");
        conn.setReadTimeout(5000);
        // 数据并没有发送给服务器
        // 获取服务器返回的流信息
        InputStream in = conn.getInputStream();
        byte[] result = StreamTool.getBytes(in);
 
        //return new String(result);
    }
     
     
     
    /** post  组拼   */
    public  void  httpPost() throws Exception {
     
        URL url = new URL(path);
        String param1 = URLEncoder.encode(username);
        String param2 = URLEncoder.encode(pwd);
        //开始连接
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        String data = "username=" + param1 + "&password=" + param2;
        //设置方式 post
        conn.setRequestMethod("POST");
        //timeout  5000
        conn.setConnectTimeout(5000);
        // 设置 http协议可以向服务器写数据
        conn.setDoOutput(true);
        // 设置http协议的消息头
        conn.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
        conn.setRequestProperty("Content-Length",  String.valueOf(data.length()));
        // 把我们准备好的data数据写给服务器
        OutputStream os = conn.getOutputStream();
        os.write(data.getBytes());
        // httpurlconnection 底层实现 outputstream 是一个缓冲输出流
        // 只要我们获取任何一个服务器返回的信息 , 数据就会被提交给服务器 , 得到服务器返回的流信息
        int code = conn.getResponseCode();
        if (code == 200) {
            InputStream is = conn.getInputStream();
            byte[] result = StreamTool.getBytes(is);
            String ss= new String(result);
        }
         
    }
     
     
    /**   httpclient  get   */
    public void httpClentGet () throws Exception{
        //获取到一个浏览器的实例 
        HttpClient client = new DefaultHttpClient();
        //准备请求的地址 
        String param1 = URLEncoder.encode(username);
        String param2 = URLEncoder.encode(pwd);
        HttpGet httpGet = new HttpGet(path + "?name=" + param1 + "&password=" + param2);
        //敲回车 发请求 
        HttpResponse  ressponse = client.execute(httpGet);
        int code = ressponse.getStatusLine().getStatusCode();
        if( code ==  200){
            InputStream is  =ressponse.getEntity().getContent();
            //byte[] result = StreamTool.getBytes(is);
             
        }
 
    }
     
     
    //  不需要的时候关闭 httpclient   client.getConnectionManager().shutdown();
    /**    httpclient  post **/
    public  void httpClentPost() throws Exception{  
        //1. 获取到一个浏览器的实例 
        HttpClient client = new DefaultHttpClient();
        HttpPost httppost = new HttpPost(path);
        // 键值对  BasicNameValuePair
        List<namevaluepair> parameters = new ArrayList<namevaluepair>();
        parameters.add(new BasicNameValuePair("username", username));
        parameters.add(new BasicNameValuePair("pwd", pwd));
        UrlEncodedFormEntity entity = new UrlEncodedFormEntity(parameters, "utf-8");
        //3.设置post请求的数据实体 
        httppost.setEntity(entity);
        //4. 发送数据给服务器
        HttpResponse  ressponse = client.execute(httppost);
        int code = ressponse.getStatusLine().getStatusCode();
        if(code == 200){
            InputStream is  =ressponse.getEntity().getContent();
            byte[] result = StreamTool.getBytes(is);
             
            //return new String(result);
        }
         
    }
     
     
    /*** 下载一个东西    ***/
    public void getFileData(Context context){
                 
        try {
             HttpClient client = new DefaultHttpClient();
             HttpGet httpGet = new HttpGet(path);
             //执行
             HttpResponse  ressponse = client.execute(httpGet);
             int code = ressponse.getStatusLine().getStatusCode();
                 
              
                  if(code == HttpStatus.SC_OK){
                        InputStream in =ressponse.getEntity().getContent();
                        //图片 
//                      Bitmap bitmap = BitmapFactory.decodeStream(in);
//                      in.close();
                         
                        //文件什么的比如读取了是要写在本地的
                        //小文件直接读取   大文件读取一点写一点
                        //byte[] result = StreamTool.getBytes(in);
                        //
                         
                         //这里可以得到文件的类型 如image/jpg /zip /tiff 等等 但是发现并不是十分有效,有时明明后缀是.rar但是取到的是null,这点特别说明
                        System.out.println(ressponse.getEntity().getContentType());
                        //可以判断是否是文件数据流
                        System.out.println(ressponse.getEntity().isStreaming());
                        //设置本地保存的文件
                        //File storeFile = new File("c:/0431la.zip");  
                        String path="sdcard/aa.txt";
                        FileOutputStream output = context.openFileOutput(path, context.MODE_PRIVATE);
                        //得到网络资源并写入文件
                        InputStream input = ressponse.getEntity().getContent();
                        byte b[] = new byte[1024];
                        int j = 0;
                        while( (j = input.read(b))!=-1){
                             output.write(b,0,j);
                        }
                        output.flush();
                        output.close(); 
                     }  
        } catch (Exception e) {
            // TODO: handle exception
        }               
    }
     
     
    /**
     * 提交数据给服务器 带一个文件 
     * @param filepath 文件在手机上的路径 
     */
    public void PostData(String filepath) throws Exception{
         
        // 实例化上传数据的 数组  part [] username  pwd
        Part[] parts = {
                  new StringPart("username", username), 
                  new StringPart("pwd", pwd), 
                  new FilePart("file", new File(filepath))
                  };
         
        PostMethod file_Post = new PostMethod(path);
        //                              多种类型的数据实体
        file_Post.setRequestEntity(new MultipartRequestEntity(parts, file_Post.getParams()));
        //创建 client
        org.apache.commons.httpclient.HttpClient client = new org.apache.commons.httpclient.HttpClient();
        //timeout
        client.getHttpConnectionManager().getParams().setConnectionTimeout(5000);
        //执行
        int status = client.executeMethod(file_Post);
         
        if(status==200){
             
         
 
        }
 
    }
     
     
    //传送文件
    public void setFile() throws Exception{
 
         HttpClient httpclient = new DefaultHttpClient();   
         HttpPost httppost = new HttpPost("http://192.168.1.1");   
         File file = new File(path);   
         InputStreamEntity reqEntity = new InputStreamEntity(   
                 new FileInputStream(file), -1);   
         reqEntity.setContentType("binary/octet-stream");   
         reqEntity.setChunked(true);   
      
         // FileEntity entity = new FileEntity(file, "binary/octet-stream");   
         httppost.setEntity(reqEntity);   
         System.out.println("executing request " + httppost.getRequestLine());   
         HttpResponse response = httpclient.execute(httppost); 
         
         if(response.getStatusLine().getStatusCode() == 200){
              
              
         }
         
    }
     
     
     
     
    /** 1.
     *  一般访问了就会返回来1个  webservice
     *  pull解析访问webservice 返回来的xml
     *   **/
     
    public void  pullJX(byte[]  bb)  throws Exception{
        // byte[] bb = EntityUtils.toByteArray(response.getEntity());
         XmlPullParser pullParser = Xml.newPullParser();
         pullParser.setInput(new ByteArrayInputStream(bb), "UTF-8");
         int event = pullParser.getEventType();   
         List<object> info;
         while(event != XmlPullParser.END_DOCUMENT){
                  switch (event) {
                       case XmlPullParser.START_DOCUMENT:
                        info = new ArrayList<object>();
                        break;
                         
                       case XmlPullParser.START_TAG:                                
                        if("aa".equals(pullParser.getName())){
                            String id = pullParser.nextText().toString();
 
                        }
                        break;
                         
                       case XmlPullParser.END_TAG:
                          if("aa".equals(pullParser.getName())){                                 
                         }
                      break;
                  }
            event = pullParser.next();
          }
    }
     
 
    /**2.
     *  解析 json  数据 [{id:"001",name:"lilei",age:"20"},{id:"002",name:"zhangjia",age:"30"}]  
     */
    private static List parseJSON(InputStream  in) throws Exception{
        byte[] data = StreamTool.getBytes(in);
        String s =new String(data);
        // 转换成  json 数组对象   [{"001","ll","20"},{"002","zj","30"},]
        JSONArray json = new JSONArray(s);
            for (int i = 0; i < json.length() ; i++) {
                  JSONObject j = json.getJSONObject(i);
                  String aa1 = j.getString("id");
                  String aa2 = j.getString("name");
                  String aa3 = j.getString("age");
            }
          return  null;
       }


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值