0

我想将文件从我的 android 手机上传到服务器 URL。但服务器需要先登录。我怎样才能将文件上传到此服务器 URL 以及登录 URL。例如:上传网址: http ://api.someapi.net/v1/medium/14 所需参数:文件和标题

登录网址: http ://api.someapi.net/v1/user/login 所需参数:邮箱和密码

4

2 回答 2

0

您的项目需要 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);

多田!

于 2012-08-28T15:00:04.073 回答
0

使用以下代码检查登录凭据。如果响应正常,则使用下面的相同代码和不同的参数将文件发送到 url。否则随心所欲。

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();
    }

希望能帮助到你

于 2012-08-28T15:03:39.003 回答