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
    关注

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

    评论

报告相同问题?

悬赏问题

  • ¥15 R语言Rstudio突然无法启动
  • ¥15 关于#matlab#的问题:提取2个图像的变量作为另外一个图像像元的移动量,计算新的位置创建新的图像并提取第二个图像的变量到新的图像
  • ¥15 改算法,照着压缩包里边,参考其他代码封装的格式 写到main函数里
  • ¥15 用windows做服务的同志有吗
  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值