如何将HttpURLConnection放入BroadcastReceiver OnReceive()?

时间:2014-04-24 15:25:46

标签: java service broadcastreceiver httpurlconnection

我有一个HttpURLConnection上传文件,然后我的服务器通过电子邮件发送它。它很棒。但是,我不希望它出现在一个Activity中,我想在SMS接收器OnRecieve()中使用它,但我似乎无法让它工作。

请帮帮忙?当我将代码放入OnReceive()时,它只是失败了:(

这是我的代码,非常简单:

 StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
         StrictMode.setThreadPolicy(policy); 

        try{
         int serverResponseCode = 0;
            final String upLoadServerUri = "http://MY_URL_EXAMPLE/upload_file_functions.php";
          String fileName = "/mnt/sdcard/MyFile.dat";

            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("/mnt/sdcard/MyFile.dat"); 

                     // open a URL connection to the Servlet
                       FileInputStream fileInputStream = new FileInputStream(sourceFile);
                       URL url = new URL(upLoadServerUri);

                       // Open a HTTP  connection to  the URL
                       conn = (HttpURLConnection) url.openConnection(); 
                       conn.setDoInput(true); // Allow Inputs
                       conn.setDoOutput(true); // Allow Outputs
                       conn.setUseCaches(false); // Don't use a Cached Copy
                       conn.setRequestMethod("POST");
                       conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
                       dos = new DataOutputStream(conn.getOutputStream());
                       dos.writeBytes(twoHyphens + boundary + lineEnd); 
                       dos.writeBytes("Content-Disposition: form-data; name=\"file\";filename=\""+ fileName + "\"" + lineEnd);
                       dos.writeBytes(lineEnd);

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

                       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){

                           // it worked !
                       }    

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

        }catch (Exception e){

        }

1 个答案:

答案 0 :(得分:0)

我必须说,有时会在这里结束F%$ kn输家。我将继续回答我的OWN问题: 你不能在BroadcastReceiver()中做一个httpURLrequest。必须在服务中完成:

public class UploadService extends IntentService
{

public UploadService() 
{
      super("UploadService");
}

@Override
protected void onHandleIntent(Intent intent)
{

public void postForm(String phn, String mssg) 
{
    try{
 int serverResponseCode = 0;
        final String upLoadServerUri = "http://MY_URL_EXAMPLE/upload_file_functions.php";
      String fileName = "/mnt/sdcard/MyFile.dat";

        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("/mnt/sdcard/MyFile.dat"); 

                 // open a URL connection to the Servlet
                   FileInputStream fileInputStream = new FileInputStream(sourceFile);
                   URL url = new URL(upLoadServerUri);

                   // Open a HTTP  connection to  the URL
                   conn = (HttpURLConnection) url.openConnection(); 
                   conn.setDoInput(true); // Allow Inputs
                   conn.setDoOutput(true); // Allow Outputs
                   conn.setUseCaches(false); // Don't use a Cached Copy
                   conn.setRequestMethod("POST");
                   conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
                   dos = new DataOutputStream(conn.getOutputStream());
                   dos.writeBytes(twoHyphens + boundary + lineEnd); 
                   dos.writeBytes("Content-Disposition: form-data; name=\"file\";filename=\""+ fileName + "\"" + lineEnd);
                   dos.writeBytes(lineEnd);

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

                   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){

                       // it worked !
                   }    

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

    }catch (Exception e){

    }
}
}

跟:

context.startService(new Intent(context, UploadService.class));