Upload a file from java client to a apache http server
我试图使用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()); } }
Neither the DefaultHttpClient nor the AndroidHttpClient digest URLs like user:password@... Instead you need to use B64 encoding in order to transmit your credentials to the apache server.
To do so try this
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;
}
The resulting string then has to be added to your HttpPost object
String auth = getB64Auth("username","password");
HttpPost postRequest = new HttpPost(URL);
postRequest.addHeader("Authorization",auth);
Also you need something (like a php script) that accepts the data on the server side. I doubt that "uploaded.txt" does that... This script is also responsible for processing, naming and saving the received file. For example you could use a StringBody you add to your MultiPartEntity to pass the name to be used to save the file on the server side.
See http://www.w3schools.com/PHP/php_file_upload.asp for more information
链接地址: http://www.djcxy.com/p/22188.html