【问题标题】:android - httpconnection error while uploading image to serverandroid - 将图像上传到服务器时出现httpconnection错误
【发布时间】:2014-02-21 21:52:12
【问题描述】:

我正在尝试将图像发送到我的 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;
    }

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

【问题讨论】:

标签: android image-uploading


【解决方案1】:

使用 Asyn Task 有两种方法可以做到这一点

    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 对象在主线程和工作线程之间发送消息。

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

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();
}

【讨论】:

  • 能否请您编辑我的代码并告诉我应该在哪里编写您的代码。我是安卓新手。对此感到抱歉
【解决方案2】:

这个异常是因为你在主线程上传图片...而是使用AsyncTask将图片上传到服务器...

【讨论】:

  • 我不想使用异步任务。请告诉我发送图片的其他方式
  • 因为后台处理需要很长时间,这就是原因。我想要一些更好的方法来做到这一点
  • 然后你可以使用后台运行的服务并上传图片
猜你喜欢
  • 1970-01-01
  • 2018-05-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-03-07
  • 2019-06-10
相关资源
最近更新 更多