报错
java.lang.NullPointerException: Attempt to invoke virtual method 'void java.io.OutputStream.close()' on a null object reference
at com.example.androidnetwork.PostTestActivity$3.run(PostTestActivity.java:261)
public void postFile(View view) {
new Thread(new Runnable() {
@Override
public void run() {
InputStream inputStream = null;
BufferedInputStream bis = null;
OutputStream outputStream = null;
try {
File file = new File("/storage/self/primary/Download/u=3340390700,4267772580&fm=173&app=49&f=JPEG.jpg");
String boundary = "--------------------------467592652334333334357333";
String filekey = "file";
String filename = file.getName();
Log.e(TAG, "run: "+filename );
String fileType = "image/jpeg";
URL url = new URL(BASE_URL+"/file/upload");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setConnectTimeout(10000);
connection.setRequestProperty("User-Agent","Android/"+ Build.VERSION.SDK_INT);
connection.setRequestProperty("Accept","*/*");
connection.setRequestProperty("Cache-Control","no-cache");
connection.setRequestProperty("Content-Type","multipart/form-data; boundary="+boundary);
connection.setRequestProperty("Connection","keep-alive");
connection.setDoOutput(true);
connection.setDoInput(true);
//连接
connection.connect();
outputStream = connection.getOutputStream();
//准备数据
StringBuilder headersb = new StringBuilder();
headersb.append("--");
headersb.append(boundary);
headersb.append("\r\n");
headersb.append("Content-Disposition: form-data; name=\""+filekey+"\"; filename=\""+filename+"\"");
headersb.append("\r\n");
headersb.append("Content-Type:"+fileType);
headersb.append("\r\n");
headersb.append("\r\n");
Log.e(TAG, "run: "+headersb.toString() );
byte[] bytes = headersb.toString().getBytes("UTF-8");
outputStream.write(bytes);
//文件内容
FileInputStream fis = new FileInputStream(file);
bis = new BufferedInputStream(fis);
byte[] buffer = new byte[1024];
int len;
while ((len=bis.read(buffer,0,buffer.length))!=-1){
outputStream.write(buffer,0,len);
}
//写尾部信息
StringBuilder footersb = new StringBuilder();
headersb.append("\r\n");
footersb.append("--");
footersb.append(boundary);
footersb.append("--");
headersb.append("\r\n");
headersb.append("\r\n");
outputStream.write(footersb.toString().getBytes("UTF-8"));
outputStream.flush();
int responseCode = connection.getResponseCode();
Log.e(TAG, "run: "+responseCode );
if (responseCode == 200){
inputStream = connection.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));
String line = br.readLine();
Log.e(TAG, "run: "+line );
}
} catch (Exception e) {
e.printStackTrace();
}finally {
if (bis!=null){
try {
bis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
try {
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
if (inputStream!=null){
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}).start();
}
}
您的每一个用心回答,都会让这个世界变得更美好一些!