我正在尝试使用apache HttpClient api将“myfile.txt”文件作为“uploaded.txt”上传到apache服务器(WAMP),但我收到“404 not found”状态。
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()); } }
答案 0 :(得分:0)
DefaultHttpClient和AndroidHttpClient都没有像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来传递用于在服务器端保存文件的名称。