Android examples for Network:URL
upload File to a URL
import java.io.DataOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import android.content.Context; public class Main { public static boolean uploadFile(Context context, String filePath, String fileName, String requestMethod) { boolean isUpload = false; try {//from www .j ava 2 s . co m File file = new File(filePath); if (!file.exists()) { return isUpload; } else { long fileSize = file.length(); if (fileSize <= 0) { return isUpload; } } URL url = new URL(getURL() + "/" + requestMethod); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setDoInput(true); conn.setDoOutput(true); conn.setUseCaches(false); conn.setRequestMethod("POST"); conn.setRequestProperty("Connection", "Keep-Alive"); conn.setRequestProperty("Charset", "UTF-8"); conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + "******"); DataOutputStream dos = new DataOutputStream(conn.getOutputStream()); dos.writeBytes("--******\r\n"); dos.writeBytes("Content-Disposition: form-data; name=\"file\"; filename=\"" + fileName + "\"" + "\r\n"); dos.writeBytes("\r\n"); FileInputStream fis = new FileInputStream(filePath); byte[] buffer = new byte[8192]; // 8k int count = 0; while ((count = fis.read(buffer)) != -1) { dos.write(buffer, 0, count); } fis.close(); dos.writeBytes("\r\n"); dos.writeBytes("--******--\r\n"); dos.flush(); if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) { isUpload = true; } else { } } catch (MalformedURLException e) { } catch (IOException e) { } return isUpload; } public static native String getURL(); }