从java客户端上传文件到apache http服务器

我试图使用apache HttpClient api将“myfile.txt”文件上传到apache服务器(WAMP)中作为“uploaded.txt”,但我得到了“404未找到”状态。

public class Httpupload1 {


    public static void main(String[] args) throws Exception 
    {

        String url = "http://username:password@localhost/uploaded.txt";

        DefaultHttpClient httpclient = new DefaultHttpClient();

        HttpPost httppost = new HttpPost(url);
        MultipartEntity entity = new MultipartEntity();

        ContentBody body = new FileBody(
                new File("C:/Users/username/Desktop/myfile.txt"),
                ContentType.APPLICATION_OCTET_STREAM
                );

        entity.addPart("file", body);
        httppost.setEntity(entity);

        HttpResponse response = httpclient.execute(httppost);
        System.out.println(response.getStatusLine());


    }
}

DefaultHttpClient和AndroidHttpClient摘要URL都不是user:password @ ...而是需要使用B64编码才能将凭据传输到apache服务器。

要做到这一点尝试

     public String getB64Auth (String login, String pass) {
       String source=login+":"+pass;
       String auth="Basic "+android.util.Base64.encodeToString(source.getBytes(),android.util.Base64.URL_SAFE|Base64.NO_WRAP);
       return auth;
     }

生成的字符串必须添加到您的HttpPost对象中

String auth = getB64Auth("username","password");
HttpPost postRequest = new HttpPost(URL);
postRequest.addHeader("Authorization",auth);

你也需要一些东西(比如php脚本)来接受服务器端的数据。 我怀疑“uploaded.txt”这样做......这个脚本还负责处理,命名和保存接收到的文件。 例如,您可以使用添加到MultiPartEntity的StringBody来传递名称以用于在服务器端保存文件。

有关更多信息,请参阅http://www.w3schools.com/PHP/php_file_upload.asp

链接地址: http://www.djcxy.com/p/22187.html

上一篇: Upload a file from java client to a apache http server

下一篇: apache HttpClient, upload a file via form: use StringBody instead of FileBody