我上传这个文件了吗?这是我的代码:
它基本上只是一个将文件(csv)发送到Web服务器的异步任务.
我回来状态代码400 :(任何人都知道我做错了什么?
编辑:现在我回到状态码411,但是当我指定内容长度时,它会返回ClientProtocolException.
这是我现在的代码:
UploadTask uploadtask;
public class UploadTask extends AsyncTask<Void, byte[], Boolean> {
HttpPost httppost;
@Override
protected Boolean doInBackground(Void... params) {
Boolean result = false;
String id = projectIDs.get((int) spinner.getSelectedItemId());
Log.i("TAG", id);
try {
l(send(String.valueOf(id), "http://" + site
+ "/restlet/position.csv?project=" + id,
"/csv.csv"));
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return result;
}
private void entity(String id, String file) throws JSONException,
UnsupportedEncodingException, FileNotFoundException {
// Add your data
File myFile = new File(Environment.getExternalStorageDirectory(),
file);
FileEntity fileEntity = new FileEntity(myFile, "multipart/form-data;");
fileEntity.setChunked(true);
long len = fileEntity.getContentLength();
httppost.getParams().setParameter("project", id);
httppost.setEntity(fileEntity);
//httppost.addHeader("Content-Length",String.valueOf(len));
httppost.setHeader("Content-Length", String.valueOf(len));
}
private String send(String id, String URL, String file)
throws ClientProtocolException, IOException, JSONException {
l(URL);
HttpResponse response = null;
httppost = new HttpPost(URL);
entity(id, file);
response = httpclient.execute(httppost);
Header[] head = response.getAllHeaders();
String str = String.valueOf(response.getStatusLine()
.getStatusCode());
response.getEntity().consumeContent();
return str;
}
}
Run Code Online (Sandbox Code Playgroud)
这里该代码工作了上传文件到web服务器:)多小时的奋斗后,我知道了,不得不从阿帕奇进口MultipartEntity,StringBody和FileBody然而,
httppost = new HttpPost(URL);
MultipartEntity entity = new MultipartEntity();
entity.addPart("title", new StringBody("position.csv", Charset.forName("UTF-8")));
File myFile = new File(Environment.getExternalStorageDirectory(), file);
FileBody fileBody = new FileBody(myFile);
entity.addPart("file", fileBody);
httppost.setEntity(entity);
httppost.getParams().setParameter("project", id);
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
18111 次 |
最近记录: |