上传文件到服务器在android
我想从我的android手机上传文件到服务器的URL。但服务器需要先登录。我怎么做到这一点上传文件到这个服务器的URL也登录URL。 例如: 上传网址: http://api.someapi.net/v1/medium/14 参数要求:文件和标题上传文件到服务器在android
登录网址: http://api.someapi.net/v1/user/login 参数要求:电子邮件地址和密码
使用下面的代码检查登录凭证。如果响应正常,请使用以下相同的代码将文件发送到网址,并使用不同的参数。否则做你想做的事。
URL siteUrl;
try {
siteUrl = new URL("yoururl");
HttpURLConnection conn = (HttpURLConnection) siteUrl
.openConnection();
conn.setRequestMethod("POST");
conn.setDoOutput(true);
conn.setDoInput(true);
DataOutputStream out = new DataOutputStream(conn.getOutputStream());
String content1 = "";
//Here param is the Map<String,String> which holds the value of email and password
Set getkey = param.keySet();
Iterator keyIter = getkey.iterator();
String content = "";
for (int i = 0; keyIter.hasNext(); i++) {
Object key = keyIter.next();
if (i != 0) {
content += "&";
}
content += key + "=" + param.get(key);
}
//Check by printing here
System.out.println(content);
out.writeBytes(content.trim());
out.flush();
out.close();
BufferedReader in = new BufferedReader(new InputStreamReader(
conn.getInputStream()));
String line = "";
while ((line = in.readLine()) != null) {
System.out.println(line);
}
in.close();
} catch (MalformedURLException e) {
e.printStackTrace();
}
希望它可以帮助
你需要Apache的Mime4J jar文件在您的项目(在这里 - http://james.apache.org/download.cgi#Apache_Mime4J )
,做:
MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
entity.addPart("file", new InputStreamBody(file, "UPLOAD.jpg"));
request.setEntity(entity);
田田!
感谢您的答复。我正在尝试..... –
感谢它的工作 –
如果你想确保在第一用户登录,您可以登录生成并返回一个令牌。然后有上传要求(令牌,文件,标题) – mario