0

我试图让我的应用程序将用相机拍摄的图像上传到服务器。我知道这不是服务器,因为我可以毫无问题地访问 url。我得到Error in http connection android.os.NetworkOnMainThreadException了错误。这是我尝试使用的代码。

public void uploadFile(Bitmap file) {
        Bitmap bitmapOrg = file;
        ByteArrayOutputStream bao = new ByteArrayOutputStream();
        bitmapOrg.compress(Bitmap.CompressFormat.JPEG, 90, bao);
        byte[] ba = bao.toByteArray();
        String ba1=Base64.encodeBytes(ba);

        ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
        nameValuePairs.add(new BasicNameValuePair("image",ba1));

        try {
            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost("http://example.info/appserver/upload.php");
            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
            HttpResponse response = httpclient.execute(httppost);
            HttpEntity entity = response.getEntity();
            is = entity.getContent();
        } catch(Exception e){
            Log.e("log_tag", "Error in http connection "+e.toString());
        }

    }
4

1 回答 1

3

网络活动不能在主线程(UI 线程)上完成,因为它极大地影响了您的应用程序对用户的感觉。查看有关使用 AsyncTasks 进行网络访问的培训文档以获取解决方案。

于 2013-03-10T22:26:37.807 回答