我正在尝试将Android应用程序中的文件发送到Asp.net服务器。我试过各种例子。但每次我都失败了。从服务器端:
HttpFileCollection uploadFiles = Request.Files;
uploadFiles.Count;
始终返回0.我拥有Android应用程序的必要权限。没有任何错误。这是Android应用代码:
new Thread(new Runnable() {
@Override
public void run() {
try {
String url = "http://www.xxxxxx.net/xxxxxx.aspx";
File fil = new File(Environment
.getExternalStorageDirectory(), "sample.txt");
if (fil.exists()) {
System.out.println("exists");
}
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
InputStreamEntity reqEntity = new InputStreamEntity(
new FileInputStream(fil), -1);
reqEntity.setContentType("binary/octet-stream");
reqEntity.setChunked(true); // Send in multiple parts if
// needed
httppost.setEntity(reqEntity);
HttpResponse response = httpclient.execute(httppost);
System.out.println("end");
} catch (Exception e) {
System.out.println("asd: " + e.toString());
}
}
}).start();
服务器端:
protected void Page_Load(object sender, EventArgs e)
{
using (StreamWriter _testData = new StreamWriter(Server.MapPath("~/data.txt"), true))
{
_testData.WriteLine("start");
HttpFileCollection uploadFiles = Request.Files;
_testData.WriteLine("file count: " + uploadFiles.Count);
}
}
答案 0 :(得分:0)
我试图使用一个库,它就可以了。我仍然不知道旧代码有什么问题。不过我使用this library并且它有效。以下是适用于任何人需要的应用代码:
HttpClient httpClient = new DefaultHttpClient();
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost("http://www.somesite.net/this.aspx");
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
final File file = new File(MainActivity.this.getFilesDir().getPath() + "/sample.txt");
FileBody fb = new FileBody(file);
builder.addPart("file", fb);
final HttpEntity yourEntity = builder.build();
post.setEntity(yourEntity);
httpClient.execute(post);
我没有改变服务器端。