今日尝试进行从服务器端获取文件数据,并显示内容,失败。
失败原因:文件未找到。下面给出代码
1 package com.example.toas; 2 3 import androidx.appcompat.app.AppCompatActivity; 4 5 import android.graphics.Bitmap; 6 import android.graphics.BitmapFactory; 7 import android.os.Build; 8 import android.os.Bundle; 9 import android.os.Environment; 10 import android.os.Handler; 11 import android.os.Message; 12 import android.os.StrictMode; 13 import android.view.View; 14 import android.widget.Button; 15 import android.widget.ImageView; 16 import android.widget.TextView; 17 import android.widget.Toast; 18 19 import java.io.BufferedReader; 20 import java.io.File; 21 import java.io.FileNotFoundException; 22 import java.io.FileOutputStream; 23 import java.io.FileReader; 24 import java.io.IOException; 25 import java.io.InputStream; 26 import java.io.OutputStream; 27 import java.net.HttpURLConnection; 28 import java.net.MalformedURLException; 29 import java.net.URL; 30 import java.net.URLConnection; 31 32 public class MainActivity extends AppCompatActivity { 33 private TextView trytxt; 34 private Button btnt; 35 private Button btni; 36 private ImageView trypng; 37 private Bitmap bitmap; 38 private MyHandle myHandler; 39 @Override 40 protected void onCreate(Bundle savedInstanceState) { 41 super.onCreate(savedInstanceState); 42 setContentView(R.layout.activity_main); 43 44 trytxt = (TextView)findViewById(R.id.trytxt); 45 trypng = (ImageView)findViewById(R.id.trypng); 46 btnt = (Button)findViewById(R.id.btnt); 47 btni = (Button)findViewById(R.id.btni); 48 myHandler = new MyHandle(); 49 50 btni.setOnClickListener(new View.OnClickListener() { 51 @Override 52 public void onClick(View v) { 53 DownloadImageRunner runnerble = new DownloadImageRunner(); 54 new Thread(runnerble).start(); 55 } 56 }); 57 } 58 59 private class DownloadImageRunner implements Runnable{ 60 public void run(){ 61 Message msg = new Message(); 62 msg.what = 1; 63 try{ 64 URL url = new URL("http://39.101.190.190:8080/usr/local/CloudNote/Image/try_image1_20200511114113.png"); 65 HttpURLConnection conn; 66 conn = (HttpURLConnection)url.openConnection(); 67 conn.setConnectTimeout(6000); 68 conn.setDoInput(true); 69 conn.setUseCaches(false); 70 InputStream is = conn.getInputStream(); 71 bitmap = BitmapFactory.decodeStream(is); 72 is.close(); 73 } catch (MalformedURLException e) { 74 msg.what=0; 75 e.printStackTrace(); 76 } catch (IOException e) { 77 msg.what=0; 78 e.printStackTrace(); 79 } 80 myHandler.sendMessage(msg); 81 } 82 } 83 private class MyHandle extends Handler { 84 public void HandleMessage(Message msg){ 85 super.handleMessage(msg); 86 if(msg.what==1){ 87 trypng.setImageBitmap(bitmap); 88 }else{ 89 Toast.makeText(MainActivity.this,"获取图片失败",Toast.LENGTH_SHORT).show(); 90 } 91 } 92 } 93 }
代码非常简单,报错原因是连接上出现了java.io.FileNotFoundException: http://39.101.190.190:8080/usr/local/CloudNote/Image/try_image1_20200511114113.png错误,一开始我尝试使用本地的Tomcat进行图片显示尝试未能成功,这里换上的ip地址是我们团队的服务器地址,连接同样未能实现。由于时间有点晚只能做出失败总结,明日会排查错误并着手设计个人笔记排版。