`
gaojingsong
  • 浏览: 1153193 次
  • 性别: Icon_minigender_1
  • 来自: 深圳
文章分类
社区版块
存档分类
最新评论

【httpClient4之模拟Http协议文件上传】

阅读更多

1、上传过程

2、上传结果


 3、上传的核心代码

 

//httpClient4使用http-mime.jar包的MultipartEntity实现,

public static String postFile(File file,String url) throws Exception {  

 

       FileBody bin = null;  

       HttpClient httpclient = new DefaultHttpClient();  

       HttpPost httppost = new HttpPost(url);  

       if(file != null) {  

           bin = new FileBody(file);  

       }  

 

       StringBody desc = new StringBody("this is a haproxy config file");  

       

       //请记住,这边传递汉字会出现乱码,解决方法如下,设置好编码格式就好  

        //new StringBody("汉字",Charset.forName("UTF-8")));    

         

       MultipartEntity reqEntity = new MultipartEntity();  

       reqEntity.addPart("email", desc);  

       

       reqEntity.addPart("file1", bin);  

         

       httppost.setEntity(reqEntity);  

       System.out.println("执行: " + httppost.getRequestLine());  

         

       HttpResponse response = httpclient.execute(httppost);  

       System.out.println("statusCode is " + response.getStatusLine().getStatusCode());  

       HttpEntity resEntity = response.getEntity();  

       System.out.println("-------------------------");  

       System.out.println(response.getStatusLine());  

       if (resEntity != null) {  

         System.out.println("返回长度: " + resEntity.getContentLength());  

         System.out.println("返回类型: " + resEntity.getContentType());  

         InputStream in = resEntity.getContent();  

         System.out.println("in is " + in);  

         System.out.println(getStrFromInputSteam(in));  

       }  

       if (resEntity != null) {  

         resEntity.consumeContent();  

       }  

       return null;  

   }  

 

public static InputStream getInputStreamFromString(String str){  

        InputStream in=new ByteArrayInputStream(str.getBytes());

return in;  

 

 

public static String getStrFromInputSteam(InputStream in) throws Exception{  

    BufferedReader bf=new BufferedReader(new InputStreamReader(in,"UTF-8"));  

    //最好在将字节流转换为字符流的时候 进行转码  

    StringBuffer buffer=new StringBuffer();  

    String line="";  

    while((line=bf.readLine())!=null){  

        buffer.append(line);  

    }  

      

   return buffer.toString();  

 

}  

  • 大小: 103.9 KB
  • 大小: 102.9 KB
0
0
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics