доступ к сообщению об ошибке запрещен при загрузке изображения на сервер - PullRequest
0 голосов
/ 17 октября 2011
 I am new to android. So, not able to trace out the error message while uploading image to the server. 

Я получил некоторый код из Интернета для загрузки изображения на сервер, ссылка - и изменил свою программу соответствующим образом. При попытке запустить программу выдает сообщение об ошибке в эмуляторе, как показано на следующем снимке экрана. enter image description here

И даже проверил все вещи на локальном хосте, и он работает нормально. А вот мой код для загрузки изображения. Пожалуйста, проверьте это и дайте мне несколько советов.

public class uploadimage extends Activity {

    InputStream inputStream;

        @Override

    public void onCreate(Bundle icicle) {

            super.onCreate(icicle);

            setContentView(R.layout.main);



            Bitmap bitmap = BitmapFactory.decodeResource(getResources(),R.drawable.icon);           ByteArrayOutputStream stream = new ByteArrayOutputStream();

            bitmap.compress(Bitmap.CompressFormat.PNG, 90, stream); //compress to which format you want.

            byte [] byte_arr = stream.toByteArray();

            String image_str = Base64.encodeBytes(byte_arr);

            ArrayList<NameValuePair> nameValuePairs = new  ArrayList<NameValuePair>();



            nameValuePairs.add(new BasicNameValuePair("image",image_str));



            try{

                HttpClient httpclient = new DefaultHttpClient();

                HttpPost httppost = new HttpPost("http://localhost/Upload_image_ANDROID/upload_image.php");

                httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

                HttpResponse response = httpclient.execute(httppost);

                String the_string_response = convertResponseToString(response);

                Toast.makeText(uploadimage.this, "Response " + the_string_response, Toast.LENGTH_LONG).show();

            }catch(Exception e){

                  Toast.makeText(uploadimage.this, "ERROR " + e.getMessage(), Toast.LENGTH_LONG).show();

                  System.out.println("Error in http connection "+e.toString());

            }

        }


        public String convertResponseToString(HttpResponse response) throws IllegalStateException, IOException{



             String res = "";

             StringBuffer buffer = new StringBuffer();

             inputStream = response.getEntity().getContent();

             int contentLength = (int) response.getEntity().getContentLength(); //getting content length…..

             Toast.makeText(uploadimage.this, "contentLength : " + contentLength, Toast.LENGTH_LONG).show();

             if (contentLength < 0){

             }

             else{

                    byte[] data = new byte[512];

                    int len = 0;

                    try
                    {

                        while (-1 != (len = inputStream.read(data)) )

                        {

                            buffer.append(new String(data, 0, len)); //converting to string and appending  to stringbuffer…..

                        }

                    }

                    catch (IOException e)

                    {

                        e.printStackTrace();

                    }

                    try

                    {

                        inputStream.close(); // closing the stream…..

                    }

                    catch (IOException e)

                    {

                        e.printStackTrace();

                    }

                    res = buffer.toString();     // converting stringbuffer to string…..



                    Toast.makeText(uploadimage.this, "Result : " + res, Toast.LENGTH_LONG).show();

                    //System.out.println("Response => " +  EntityUtils.toString(response.getEntity()));

             }

             return res;

        }

}

Заранее спасибо.

1 Ответ

2 голосов
/ 17 октября 2011

Вместо

"http://localhost"

используйте

http://10.0.2.2

для эмулятора.А если вы хотите проверить устройство, используйте specific IP of System, предоставленное маршрутизатором или сетью.

Thankx.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...