void test(){post
String uploadUrl = "http://localhost:8080/upload/UploadServlet";
String end = "\r\n";
String twoHyphens = "--";
String boundary = "******";
try
{
URL url = new URL(uploadUrl);
HttpURLConnection httpURLConnection = (HttpURLConnection) url
.openConnection();this
//輸入輸出流
httpURLConnection.setDoInput(true);
httpURLConnection.setDoOutput(true);
httpURLConnection.setUseCaches(false);url
//get,post必須大寫
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setRequestProperty("Connection", "Keep-Alive");
httpURLConnection.setRequestProperty("Charset", "UTF-8");orm
// 必須在Content-Type請求頭中指定分界符中的任意字符串
httpURLConnection.setRequestProperty("Content-Type",
"multipart/form-data;boundary=" + boundary);
//獲取輸出流對象,預備上傳文件
DataOutputStream dos = new DataOutputStream(httpURLConnection
.getOutputStream());對象
//設置分界符,加end表示單獨一行
dos.writeBytes(twoHyphens + boundary + end);ip
//設置與上傳文件相關的信息
dos
.writeBytes("Content-Disposition: form-data; name=\"file\"; filename=\""
+ filename.substring(filename.lastIndexOf("/") + 1)
+ "\"" + end);utf-8
//在上傳文件信息與文件的內容之間必須有一個空行
dos.writeBytes(end);
FileInputStream fis = new FileInputStream(filename);
byte[] buffer = new byte[8192]; // 8k
int count = 0;
while ((count = fis.read(buffer)) != -1)
{
dos.write(buffer, 0, count);
}
fis.close();
dos.writeBytes(end);
dos.writeBytes(twoHyphens + boundary + twoHyphens + end);
dos.flush();
InputStream is = httpURLConnection.getInputStream();
InputStreamReader isr = new InputStreamReader(is, "utf-8");
BufferedReader br = new BufferedReader(isr);
String result = br.readLine();
Toast.makeText(this, result, Toast.LENGTH_LONG).show();
dos.close();
is.close();
}
catch (Exception e)
{
setTitle(e.getMessage());
}字符串
}get