面试:你懂什么是分布式系统吗?Redis分布式锁都不会?>>>
void test(){
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();
//输入输出流
httpURLConnection.setDoInput(true);
httpURLConnection.setDoOutput(true);
httpURLConnection.setUseCaches(false);
//get,post必须大写
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setRequestProperty("Connection", "Keep-Alive");
httpURLConnection.setRequestProperty("Charset", "UTF-8");
// 必须在Content-Type请求头中指定分界符中的任意字符串
httpURLConnection.setRequestProperty("Content-Type",
"multipart/form-data;boundary=" + boundary);
//获取输出流对象,预备上传文件
DataOutputStream dos = new DataOutputStream(httpURLConnection
.getOutputStream());
//设置分界符,加end表示单独一行
dos.writeBytes(twoHyphens + boundary + end);
//设置与上传文件相关的信息
dos
.writeBytes("Content-Disposition: form-data; name=\"file\"; filename=\""
+ filename.substring(filename.lastIndexOf("/") + 1)
+ "\"" + end);
//在上传文件信息与文件的内容之间必须有一个空行
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());
}
}