设为首页 加入收藏

TOP

Android通过http传输文件到servlet
2014-11-24 08:29:44 来源: 作者: 【 】 浏览:1
Tags:Android 通过 http 传输 文件 servlet

下面贴贴代码吧:


httpclict如下:


package com.example.http ;


import java.io.File ;


import org.apache.commons.httpclient.HttpClient ;
import org.apache.commons.httpclient.HttpStatus ;
import org.apache.commons.httpclient.methods.PostMethod ;
import org.apache.commons.httpclient.methods.multipart.FilePart ;
import org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity ;
import org.apache.commons.httpclient.methods.multipart.Part ;


public class Hclient


{
/*
* private Context mContext ;
*
* public Hclient ( Context c ) { this.mContext = c ; }
*/


public void UpLoadFile ( String str)
{


String targetURL = null ;// TODO 指定URL
File targetFile = null ;// TODO 指定上传文件
targetFile = new File ( str) ;
targetURL = "http://192.168.1.100:8081/http/Http" ; // servleturl
PostMethod filePost = new PostMethod ( targetURL ) ;
try
{
// 通过以下方法可以模拟页面参数提交
// filePost.setParameter("name", "中文");
// filePost.setParameter("pass", "1234");
Part [ ] parts =
{ new FilePart ( targetFile.getName ( ) , targetFile ) } ;
filePost.setRequestEntity ( new MultipartRequestEntity (
parts , filePost.getParams ( ) ) ) ;
HttpClient client = new HttpClient ( ) ;
client.getHttpConnectionManager ( ).getParams ( )
.setConnectionTimeout ( 5000 ) ;
int status = client.executeMethod ( filePost ) ;
if ( status == HttpStatus.SC_OK )
{
System.out.println ( "上传成功" ) ;
// 上传成功
}
else
{
System.out.println ( "上传失败" ) ;
// 上传失败
}
}
catch ( Exception ex )
{
ex.printStackTrace ( ) ;
}
finally
{
filePost.releaseConnection ( ) ;


}
}
}


】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇Android扑克牌猜点小游戏源码 下一篇Qt错误:empty character constant

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容:

·Redis on AWS:Elast (2025-12-27 04:19:30)
·在 Spring Boot 项目 (2025-12-27 04:19:27)
·使用华为开发者空间 (2025-12-27 04:19:24)
·Getting Started wit (2025-12-27 03:49:24)
·Ubuntu 上最好用的中 (2025-12-27 03:49:20)