Ethan_KF 2016-03-02 09:03 采纳率: 0%
浏览 1346

android网络开发 requestcode不为200

一个简单的例子,新建一个Asynctask,从网络获取一张图片,显示到ImageView上,但是requestcode一直是405是怎么回事?菜鸟一枚,大神勿喷
public class MainActivity extends AppCompatActivity {
public static final String URLPATH = "http://img1.imgtn.bdimg.com/it/u=1853916932,391038869&fm=21&gp=0.jpg";
ImageView iv = null;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    iv = (ImageView) findViewById(R.id.imageView);
}

public void click(View view) {
    MyAsynctask mTask = new MyAsynctask();
    mTask.execute(URLPATH);
}

class MyAsynctask extends AsyncTask<String, Void, Bitmap> {
    @Override
    protected Bitmap doInBackground(String... params) {
        InputStream inputStream = null;
        URL url = null;
        HttpURLConnection huc = null;
        Bitmap bmp = null;
        String path = getApplicationContext().getFilesDir().getAbsolutePath();
        System.out.println("path: " + path);
        try {
            url = new URL(params[0]);
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }

        if (url != null) {
            try {
                huc = (HttpURLConnection) url.openConnection();
                huc.setConnectTimeout(5000);
                huc.setDoInput(true);
                huc.setDoOutput(true);
                huc.setRequestMethod("GET");

                if (huc.getResponseCode() == 200) {
                    inputStream = huc.getInputStream();
                    byte[] data = new byte[1024];
                    int len = 0;
                    OutputStream os = new FileOutputStream(path + "/test.jpg");
                    while ((len = inputStream.read(data)) != -1) {
                        os.write(data, 0, len);
                    }
                    bmp = BitmapFactory.decodeFile(path + "/test.png");
                } else {
                    System.out.println("hola: connection error!" + huc.getResponseCode());
                }

            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return bmp;
    }

    @Override
    protected void onPostExecute(Bitmap bmp) {
        if (bmp != null) {
            iv.setImageBitmap(bmp);
        }
    }
}

}

  • 写回答

3条回答 默认 最新

  • Cynthia_nl 2016-03-02 09:11
    关注

    你的图片地址有问题,都打不开

    评论

报告相同问题?

悬赏问题

  • ¥30 求解达问题(有红包)
  • ¥15 请解包一个pak文件
  • ¥15 不同系统编译兼容问题
  • ¥100 三相直流充电模块对数字电源芯片在物理上它必须具备哪些功能和性能?
  • ¥30 数字电源对DSP芯片的具体要求
  • ¥20 antv g6 折线边如何变为钝角
  • ¥30 如何在Matlab或Python中 设置饼图的高度
  • ¥15 nginx中的CORS策略应该如何配置
  • ¥30 信号与系统实验:采样定理分析
  • ¥100 我想找人帮我写Python 的股票分析代码,有意请加mathtao