2 ethanhola ethanhola 于 2016.03.02 17:03 提问

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个回答

qq_28375209
qq_28375209   2016.03.02 17:11

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

ethanhola
ethanhola 我这可以打开…
接近 2 年之前 回复
danielinbiti
danielinbiti   Ds   Rxr 2016.03.02 17:57

是get还是post

huc.setRequestMethod("GET"); 
改成
huc.setRequestMethod("POST"); 
huc.connect();
dongfeng9ge
dongfeng9ge   Ds   Rxr 2016.03.02 22:42

你把GET改成POST试试

Csdn user default icon
上传中...
上传图片
插入图片
准确详细的回答,更有利于被提问者采纳,从而获得C币。复制、灌水、广告等回答会被删除,是时候展现真正的技术了!