android网络应用3——HttpURLConnection

来源:互联网 发布:和禹网络是培训公司么? 编辑:程序博客网 时间:2024/05/23 00:03

ps:以下内容来自对李刚的《疯狂Android讲义》的学习

HttpURLConnection继承自URLConnection,因此也可以向指定网站发送get,post请求,但是HttpURLConnection 在URLConnection的基础下提供了以下便捷的方法:

  • public int getResponseCode() throws IOException 
    获取服务器的响应代码
  •  public String getResponseMessage() throws IOException 
    获取服务器的响应信息
  •  public void setRequestMethod(String method) throws ProtocolException
    设置请求的方法,比如"POST","GET"
使用HttpURLConnection发送post请求上传图片

public boolean updateImg(String theurl,HashMap<String, String> params,File file)
    {
    String end = "\r\n";
    String twoHyphens = "--";
    String boundary = "*****";
    Random random = new Random();  
        int temp = random.nextInt(); 
    String imguri=System.currentTimeMillis()+"_"+temp+".jpg";
    String result="";
   try
    {
     
       URL url =new URL(theurl);
       HttpURLConnection con=(HttpURLConnection)url.openConnection();
       //允许Input、Output,不使用Cache 
       con.setDoInput(true);
       con.setDoOutput(true);
       con.setUseCaches(false);
       //设置传送的method=POST 
       con.setRequestMethod("POST");
       // setRequestProperty 
       con.setRequestProperty("Connection", "Keep-Alive");
       con.setRequestProperty("Charset", "UTF-8");
       con.setRequestProperty("Content-Type","multipart/form-data;boundary="+boundary);
   
       StringBuilder sb = new StringBuilder();   
       //上传的表单参数部分,格式请参考文章    
            for (Entry<String, String> entry : params.entrySet()) 
            {
            //构建表单字段内容    
                sb.append("--");    
                sb.append(boundary);    
                sb.append("\r\n");    
                sb.append("Content-Disposition: form-data; name=\""+ entry.getKey() + "\"\r\n\r\n");    
                sb.append(entry.getValue());    
                sb.append("\r\n");    
            }    
  
            sb.append("--");    
            sb.append(boundary);    
            sb.append("\r\n");    
  
            DataOutputStream ds = new DataOutputStream(new BufferedOutputStream(con.getOutputStream()));  
            ds.write(sb.toString().getBytes());  
            Log.v("albumBLL_sb", sb.toString());

            ds.writeBytes("Content-Disposition: form-data; name=\"pbytes\"; filename=\"" + imguri + "\"" + "\r\n"+"Content-Type: image/jpeg\r\n\r\n");  


       
           
      // FileInputStream fStream = new FileInputStream(file);
           
       DataInputStream in=new DataInputStream(new BufferedInputStream(new FileInputStream(file)));
       // 设置每次写入1024bytes 
       int bufferSize = 1024;
       byte[] buffer = new byte[bufferSize];

       int length = -1;
       //从文件读取数据至缓冲区 
       while((length = in.read(buffer)) != -1)
       {
         ds.write(buffer, 0, length);
       }
       in.close();
       ds.writeBytes(end);
       ds.writeBytes(twoHyphens + boundary + twoHyphens + end);
       ds.flush();
       InputStream is = con.getInputStream();
       int ch;
       StringBuffer b =new StringBuffer();
       while( ( ch = is.read() ) != -1 )
       {
         b.append( (char)ch );
       }
       result=b.toString();
       ds.close();
 
    }
    catch(Exception e)
    {
    Log.v("albumbll", e.getMessage());
        
    }
    Log.v("albumbll_result", result);
    if(result.contains("success"))
    {
    return true;
    }
    return false;
    }

原创粉丝点击