将图像上传到服务器时出现android-httpconnection错误

时间:2014-02-21 13:27:32

标签: android image-uploading

我正在尝试将图像发送到我的php服务器,但我收到这些错误

 android.os.NetworkOnMainThreadException
at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1144)
at java.net.InetAddress.lookupHostByName(InetAddress.java:385)
at java.net.InetAddress.getAllByNameImpl(InetAddress.java:236)
at java.net.InetAddress.getAllByName(InetAddress.java:214)
at libcore.net.http.HttpConnection.<init>(HttpConnection.java:70)
at libcore.net.http.HttpConnection.<init>(HttpConnection.java:50)
at libcore.net.http.HttpConnection$Address.connect(HttpConnection.java:340)

这是我发送图片的代码

public int uploadFile(String sourceFileUri) {
      System.out.println("file path is " + sourceFileUri); //here i am successfully   getting the image path
        String upLoadServerUri = "http://www";
        String fileName = sourceFileUri;
        int serverResponseCode = 0;
        HttpURLConnection conn = null;
        DataOutputStream dos = null;
        String lineEnd = "\r\n";
        String twoHyphens = "--";
        String boundary = "*****";
        int bytesRead, bytesAvailable, bufferSize;
        byte[] buffer;
        int maxBufferSize = 1 * 1024 * 1024;
        File sourceFile = new File(sourceFileUri);
        if (!sourceFile.isFile()) {
            Log.e("uploadFile", "Source File Does not exist");
            return 0;
        }
        try { // open a URL connection to the Servlet
            FileInputStream fileInputStream = new FileInputStream(sourceFile);
            URL url = new URL(upLoadServerUri);
            conn = (HttpURLConnection) url.openConnection(); // Open a HTTP
                                                                // connection to
                                                                // the URL
            conn.setDoInput(true); // Allow Inputs
            conn.setDoOutput(true); // Allow Outputs
            conn.setUseCaches(false); // Don't use a Cached Copy
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Connection", "Keep-Alive");
            conn.setRequestProperty("ENCTYPE", "multipart/form-data");
            conn.setRequestProperty("Content-Type",
                    "multipart/form-data;boundary=" + boundary);
            conn.setRequestProperty("uploaded_file", fileName);
            dos = new DataOutputStream(conn.getOutputStream());

            dos.writeBytes(twoHyphens + boundary + lineEnd);
            dos.writeBytes("Content-Disposition: form-data; name=\"uploaded_file\";filename=\""
                    + fileName + "\"" + lineEnd);
            dos.writeBytes(lineEnd);

            bytesAvailable = fileInputStream.available(); // create a buffer of
                                                            // maximum size

            bufferSize = Math.min(bytesAvailable, maxBufferSize);
            buffer = new byte[bufferSize];

            // read file and write it into form...
            bytesRead = fileInputStream.read(buffer, 0, bufferSize);

            while (bytesRead > 0) {
                dos.write(buffer, 0, bufferSize);
                bytesAvailable = fileInputStream.available();
                bufferSize = Math.min(bytesAvailable, maxBufferSize);
                bytesRead = fileInputStream.read(buffer, 0, bufferSize);
            }

            // send multipart form data necesssary after file data...
            dos.writeBytes(lineEnd);
            dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);

            // Responses from the server (code and message)
            serverResponseCode = conn.getResponseCode();
            String serverResponseMessage = conn.getResponseMessage();

            Log.i("uploadFile", "HTTP Response is : " + serverResponseMessage
                    + ": " + serverResponseCode);
            if (serverResponseCode == 200) {
               System.out.println("server is ok");
            }

            // close the streams //
            fileInputStream.close();
            dos.flush();
            dos.close();

        } catch (MalformedURLException ex) {

            Log.e("Upload file to server", "error: " + ex.getMessage(), ex);
        } catch (Exception e) {
            e.printStackTrace();

            Log.e("Upload file to server Exception",
                    "Exception : " + e.getMessage(), e);
        }
        return serverResponseCode;
    }

我不想使用异步任务。请给我一些其他方式发送图像

2 个答案:

答案 0 :(得分:0)

此例外是因为您在主线程上传图像...而是使用AsyncTask将图像上传到服务器......

答案 1 :(得分:0)

使用Asyn任务

可以使用两种方法
    public class MyUploadTask extends AsynTask<void,void,void>{
          void doInBackground(){
             //... do your upload task
            }
      }

另一个是使用线程

Thread myUploadTask = new Thread(new Runnable(){
              void run(){
                 //... do your upload task
              }
        });
myUploadTask.start();

如果你想在普通线程中将更新发布到UI,请使用android.os.Handler对象在主线程和工作线程之间发送消息。

在你的情况下: 如果我想在onc​​reate()方法中将图像发送到服务器

public void onCreate(){
   super.onCreate();
     uploadToServer();
}
public void uploadToServer(){
Thread myUploadTask = new Thread (new Runnable(){
void run(){
    //Calling the upload Image method
  uploadFile("www.yourdomin.com/uploadFile");
   }
});
 myUploadTask.start();
}