Android:我如何从我的Android应用程序发送文件到openshift上的远程服务器?

时间:2014-05-27 12:36:51

标签: php android openshift

我要做的是将文件保存在openshift上创建的远程服务器中(我使用php 5.3创建了一个应用程序)。这是发送文件的代码:

private void postFile(){
        try{
        String postReceiverUrl = "https://openshift.redhat.com/app/console/application/537e9c0be0b8cd34170000b6-alldata";

    HttpClient httpClient = new DefaultHttpClient();
    HttpPost httpPost = new HttpPost(postReceiverUrl);

    File file = new File(detail);
    FileBody fileBody = new FileBody(file);

    MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
    reqEntity.addPart("file", fileBody);
    httpPost.setEntity(reqEntity);


        HttpResponse  response = httpClient.execute(httpPost);
        HttpEntity resEntity = response.getEntity();

        if(resEntity != null){
            String responseStr = EntityUtils.toString(resEntity).trim();
            Log.v("MyApp", "Response:" + responseStr);
        }
        else Log.v("MyApp", "couldn't commnicate with the server");

    }catch (NullPointerException e) {
        e.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    }

        }

执行以下行时抛出异常:

HttpResponse  response = httpClient.execute(httpPost);

这是logcat消息:

05-27 15:32:01.557: D/libEGL(18546): loaded /vendor/lib/egl/libEGL_POWERVR_SGX544_115.so
05-27 15:32:01.607: D/libEGL(18546): loaded /vendor/lib/egl/libGLESv1_CM_POWERVR_SGX544_115.so
05-27 15:32:01.627: D/libEGL(18546): loaded /vendor/lib/egl/libGLESv2_POWERVR_SGX544_115.so
05-27 15:32:01.697: D/OpenGLRenderer(18546): Enabling debug mode 0
05-27 15:32:06.717: I/dalvikvm(18546): Total arena pages for JIT: 11
05-27 15:32:06.717: I/dalvikvm(18546): Total arena pages for JIT: 12
05-27 15:32:06.727: D/dalvikvm(18546): Rejecting registerization due to and-int/lit16 v0, v5, (#128)
05-27 15:32:06.737: D/dalvikvm(18546): Rejecting registerization due to and-int/lit16 v0, v5, (#128)
05-27 15:32:06.817: D/dalvikvm(18546): Rejecting registerization due to move v5, v4, (#0)
05-27 15:32:06.827: D/dalvikvm(18546): Rejecting registerization due to move v5, v4, (#0)
05-27 15:32:06.827: D/dalvikvm(18546): Rejecting registerization due to mul-int/lit8 v4, v2, (#31)
05-27 15:32:06.827: D/dalvikvm(18546): Rejecting registerization due to mul-int/lit8 v4, v2, (#31)
05-27 15:32:06.827: D/dalvikvm(18546): DexOpt: couldn't find static field Lorg/apache/http/message/BasicHeaderValueParser;.INSTANCE
05-27 15:32:06.837: W/dalvikvm(18546): VFY: unable to resolve static field 3758 (INSTANCE) in Lorg/apache/http/message/BasicHeaderValueParser;
05-27 15:32:06.837: D/dalvikvm(18546): VFY: replacing opcode 0x62 at 0x001b
05-27 15:32:06.837: D/dalvikvm(18546): DexOpt: couldn't find static field Lorg/apache/http/message/BasicHeaderValueFormatter;.INSTANCE
05-27 15:32:06.837: W/dalvikvm(18546): VFY: unable to resolve static field 3752 (INSTANCE) in Lorg/apache/http/message/BasicHeaderValueFormatter;
05-27 15:32:06.837: D/dalvikvm(18546): VFY: replacing opcode 0x62 at 0x0015
05-27 15:32:06.857: W/System.err(18546): android.os.NetworkOnMainThreadException
05-27 15:32:06.867: W/System.err(18546):    at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1128)
05-27 15:32:06.877: W/System.err(18546):    at java.net.InetAddress.lookupHostByName(InetAddress.java:385)
05-27 15:32:06.877: W/System.err(18546):    at java.net.InetAddress.getAllByNameImpl(InetAddress.java:236)
05-27 15:32:06.877: W/System.err(18546):    at java.net.InetAddress.getAllByName(InetAddress.java:214)
05-27 15:32:06.877: D/dalvikvm(18546): Rejecting registerization due to +iget-quick v3, v5, (#20)
05-27 15:32:06.877: W/System.err(18546):    at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:137)
05-27 15:32:06.877: W/System.err(18546):    at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
05-27 15:32:06.877: W/System.err(18546):    at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
05-27 15:32:06.877: W/System.err(18546):    at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360)
05-27 15:32:06.877: W/System.err(18546):    at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
05-27 15:32:06.877: W/System.err(18546):    at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
05-27 15:32:06.877: W/System.err(18546):    at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
05-27 15:32:06.877: W/System.err(18546):    at com.measuredistancewalked.PostData.postFile(PostData.java:108)
05-27 15:32:06.877: W/System.err(18546):    at com.measuredistancewalked.PostData.writeFile(PostData.java:82)
05-27 15:32:06.877: W/System.err(18546):    at com.measuredistancewalked.PostData.saveAllData(PostData.java:58)
05-27 15:32:06.877: W/System.err(18546):    at com.measuredistancewalked.DitanceWalkedActivity$1.onClick(DitanceWalkedActivity.java:74)
05-27 15:32:06.877: W/System.err(18546):    at android.view.View.performClick(View.java:4383)
05-27 15:32:06.877: W/System.err(18546):    at android.view.View$PerformClick.run(View.java:18097)
05-27 15:32:06.877: W/System.err(18546):    at android.os.Handler.handleCallback(Handler.java:725)
05-27 15:32:06.877: W/System.err(18546):    at android.os.Handler.dispatchMessage(Handler.java:92)
05-27 15:32:06.877: W/System.err(18546):    at android.os.Looper.loop(Looper.java:176)
05-27 15:32:06.877: W/System.err(18546):    at android.app.ActivityThread.main(ActivityThread.java:5279)
05-27 15:32:06.877: W/System.err(18546):    at java.lang.reflect.Method.invokeNative(Native Method)
05-27 15:32:06.877: W/System.err(18546):    at java.lang.reflect.Method.invoke(Method.java:511)
05-27 15:32:06.877: W/System.err(18546):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1102)
05-27 15:32:06.877: W/System.err(18546):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:869)
05-27 15:32:06.877: W/System.err(18546):    at dalvik.system.NativeStart.main(Native Method)
05-27 15:32:06.887: D/dalvikvm(18546): Rejecting registerization due to +iget-object-quick v7, v9, (#8)
05-27 15:32:06.907: I/dalvikvm(18546): Total arena pages for JIT: 13
05-27 15:32:06.907: I/dalvikvm(18546): Total arena pages for JIT: 14

我有以下post_file.php代码:

<?php
if($_FILES){
$file = $_FILES['file'];
$fileContents =  file_get_contents($file["all_data_file"]);
print_r($fileContents);
}
?>

我的问题是:

我在哪里上传我的PHP代码?和

除了在我的代码中提供我的openshift应用程序URL之外,我还应该做些什么来与服务器通信?

提前感谢您的帮助!

2 个答案:

答案 0 :(得分:0)

如果您的应用崩溃,请始终查看logcat。在99%的情况下,错误消息会告诉您确切的错误以及如何解决问题,就像您的情况一样:

05-27 15:32:06.857: W/System.err(18546): android.os.NetworkOnMainThreadException

您无法在UI线程中执行复杂的任务,这样做会导致您的应用冻结和延迟。在Android中,在网络方面有一个额外的安全防范。如果您尝试在UI线程上执行网络操作,则抛出异常,即此NetworkOnMainThreadException

解决方案:您必须在单独的Thread中执行工作。我建议您使用AsyncTask
看一下AsyncTask的示例,方法doInBackground()在单独的Thread中执行,您可以在那里执行所有工作。 doInBackground()完成后,它返回的结果将传递给onPostExecute()。将再次在UI线程上执行onPostExecute(),因此您可以在此处将AsyncTask的结果返回给用户界面。

private class ExampleTask extends AsyncTask<Void, Void, Boolean> {

    @Override
    protected Boolean doInBackground(Void... params) {

        // Do your work here

        // Return true if successful otherwise false
        return true;
    }

    @Override
    protected void onPostExecute(Boolean result) {
        super.onPostExecute(result);

        if(result) {
            // Work has been completed successfully    
        } else {
            // Work was not completed successfully
        }
    }
}

答案 1 :(得分:-1)

您需要将网络活动从UI线程移出,应该在AsyncTask中处理。

private class upload extends AsyncTask<URL, Integer, Long> {

    private void doInBackground(URL... urls) {
        try {
            String postReceiverUrl = "https://openshift.redhat.com/app/console/application/537e9c0be0b8cd34170000b6-alldata";

            HttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(postReceiverUrl);

            File file = new File(detail);
            FileBody fileBody = new FileBody(file);

            MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
            reqEntity.addPart("file", fileBody);
            httpPost.setEntity(reqEntity);

            HttpResponse response = httpClient.execute(httpPost);
            HttpEntity resEntity = response.getEntity();

            if(resEntity != null) {
                String responseStr = EntityUtils.toString(resEntity).trim();
                Log.v("MyApp", "Response:" + responseStr);
            } else {
                Log.v("MyApp", "couldn't commnicate with the server");
            }

        } catch (NullPointerException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

你执行AsyncTask就像这样:

new upload().execute(url);