2016-03-15 78 views
0

我真的堅持這一點,我試圖從Android活動發送數據到PHP文件,我的代碼只是不工作。應用程序只要打開就停止。我真的很感激,如果有人能給我一個指示什麼修復,或者如果你可以編輯代碼併發佈一個例子,非常感謝。 這裏是我的代碼 -安卓到PHP不工作

package com.xavware.httptest; 
import android.content.Context; 
import android.net.ConnectivityManager; 
import android.net.NetworkInfo; 
import android.os.AsyncTask; 
import android.support.v7.app.AppCompatActivity; 
import android.os.Bundle; 
import android.view.View; 
import android.widget.EditText; 
import android.widget.Toast; 

import org.apache.http.NameValuePair; 
import org.apache.http.client.ClientProtocolException; 
import org.apache.http.client.HttpClient; 
import org.apache.http.client.entity.UrlEncodedFormEntity; 
import org.apache.http.client.methods.HttpPost; 
import org.apache.http.impl.client.DefaultHttpClient; 
import org.apache.http.message.BasicNameValuePair; 

import java.io.BufferedReader; 
import java.io.BufferedWriter; 
import java.io.DataOutputStream; 
import java.io.IOException; 
import java.io.InputStream; 
import java.io.InputStreamReader; 
import java.io.OutputStream; 
import java.io.OutputStreamWriter; 
import java.net.HttpURLConnection; 
import java.net.MalformedURLException; 
import java.net.URL; 
import java.util.ArrayList; 
import java.util.List; 

import javax.net.ssl.HttpsURLConnection; 

public class MainActivity extends AppCompatActivity { 


    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 

    } 

    public void go(View v) { 
     check(); 
    } 

    private boolean check() { 
     ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); 
     NetworkInfo info = cm.getActiveNetworkInfo(); 
     if (info != null && info.isConnected()) { 
      Toast.makeText(getApplicationContext(), "Yes There is Internet", Toast.LENGTH_LONG).show(); 
     } else { 
      Toast.makeText(getApplicationContext(), "No Internet", Toast.LENGTH_LONG).show(); 
     } 
     return info != null && info.isConnected(); 
    } 

    public void sendPostRequest(View v){ 
     new PostClass(this).execute(); 
    } 

    private class PostClass extends AsyncTask<String, Void, Void>{ 

     private final Context context; 

     public PostClass(Context c){ 
      this.context = c; 
     } 

     @Override 
     protected Void doInBackground(String... params){ 
      try{ 
       URL url = new URL("http://a.argueit.uk/dm/postdata.php"); 

       HttpURLConnection con = (HttpURLConnection)url.openConnection(); 
       String data = "xav"; 
       con.setRequestMethod("POST"); 
       con.setRequestProperty("USER-AGENT", "Mozilla/5.0"); 
       con.setRequestProperty("ACCEPT-LANGUAGE", "en-US,un;0.5"); 
       con.setDoOutput(true); 
       DataOutputStream dStream = new DataOutputStream(con.getOutputStream()); 
       dStream.writeBytes(data); 
       dStream.flush(); 
       dStream.close(); 
       Toast.makeText(getApplicationContext(), "sent", Toast.LENGTH_LONG).show(); 
       int responseCode = con.getResponseCode(); 
      }catch(MalformedURLException e){ 
       e.printStackTrace(); 
       Toast.makeText(getApplicationContext(), "error", Toast.LENGTH_LONG).show(); 
      }catch(IOException e){ 
       e.printStackTrace(); 
       Toast.makeText(getApplicationContext(), "error", Toast.LENGTH_LONG).show(); 
      } 
      return null; 
     } 

    } 




} 

這裏是logcat的:

**03-15 16:21:37.385 16458-16458/? I/art: Late-enabling -Xcheck:jni 
03-15 16:21:37.471 16458-16458/com.mhealth.healthnotation W/System: ClassLoader referenced unknown path: /data/app/com.mhealth.healthnotation-1/lib/arm 
03-15 16:21:37.590 16458-16485/com.mhealth.healthnotation D/OpenGLRenderer: Use EGL_SWAP_BEHAVIOR_PRESERVED: true 
03-15 16:21:37.653 16458-16485/com.mhealth.healthnotation I/Adreno-EGL: <qeglDrvAPI_eglInitialize:379>: EGL 1.4 QUALCOMM build: (I14a17c7611) 
                     OpenGL ES Shader Compiler Version: XE031.06.00.02 
                     Build Date: 12/04/15 Fri 
                     Local Branch: workspace 
                     Remote Branch: 
                     Local Patches: 
                     Reconstruct Branch: 
03-15 16:21:37.655 16458-16485/com.mhealth.healthnotation I/OpenGLRenderer: Initialized EGL, version 1.4 
03-15 16:21:41.220 16458-16718/com.mhealth.healthnotation E/AndroidRuntime: FATAL EXCEPTION: AsyncTask #1 
                      Process: com.mhealth.healthnotation, PID: 16458 
                      java.lang.RuntimeException: An error occurred while executing doInBackground() 
                       at android.os.AsyncTask$3.done(AsyncTask.java:309) 
                       at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:354) 
                       at java.util.concurrent.FutureTask.setException(FutureTask.java:223) 
                       at java.util.concurrent.FutureTask.run(FutureTask.java:242) 
                       at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:234) 
                       at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113) 
                       at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588) 
                       at java.lang.Thread.run(Thread.java:818) 
                      Caused by: java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare() 
                       at android.os.Handler.<init>(Handler.java:200) 
                       at android.os.Handler.<init>(Handler.java:114) 
                       at android.widget.Toast$TN.<init>(Toast.java:345) 
                       at android.widget.Toast.<init>(Toast.java:101) 
                       at android.widget.Toast.makeText(Toast.java:259) 
                       at com.xavware.httptest.MainActivity$LoginTask.doInBackground(MainActivity.java:95) 
                       at com.xavware.httptest.MainActivity$LoginTask.doInBackground(MainActivity.java:72) 
                       at android.os.AsyncTask$2.call(AsyncTask.java:295) 
                       at java.util.concurrent.FutureTask.run(FutureTask.java:237) 
                       at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:234)  
                       at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)  
                       at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)  
                       at java.lang.Thread.run(Thread.java:818)  
03-15 16:21:41.406 16458-16485/com.mhealth.healthnotation E/Surface: getSlotFromBufferLocked: unknown buffer: 0xb9a84920 
03-15 16:21:41.407 16458-16485/com.mhealth.healthnotation D/OpenGLRenderer: endAllActiveAnimators on 0xb9a78780 (RippleDrawable) with handle 0xb9ad8270** 
+1

您可以發佈您logcat的,所以我們可以看到錯誤的堆棧跟蹤 – zgc7009

回答

0

我不認爲這是問題,但首先要確保你確實在清單文件中添加Internet權限。

這裏是POST方法用於異步任務的例子:

private class SendMessageTask extends AsyncTask<String, Void, String> { 

    Graduate targetGraduate; 

    public SendMessageTask(Graduate targetGraduate){ 
     this.targetGraduate = targetGraduate; 

    } 

    @Override 
    protected String doInBackground(String... params) { 
     URL myUrl = null; 
     HttpURLConnection conn = null; 
     String response = ""; 
     String data = params[0]; 

     try { 
      myUrl = new URL("http://your url"); 
      conn = (HttpURLConnection) myUrl.openConnection(); 
      conn.setReadTimeout(10000); 
      conn.setConnectTimeout(15000); 
      conn.setRequestMethod("POST"); 
      conn.setDoInput(true); 
      conn.setDoOutput(true); 

      //one long string, first encode is the key to get the data on your web 
      //page, second encode is the value, keep concatenating key and value. 
      //theres another ways which easier then this long string in case you are 
      //posting a lot of info, look it up. 
      String postData = URLEncoder.encode("TOKEN", "UTF-8") + "=" + 
        URLEncoder.encode(targetGraduate.getToken(), "UTF-8") + "&" + 
        URLEncoder.encode("SENDER_ID", "UTF-8") + "=" + 
        URLEncoder.encode(MainActivity.curretUser.getId(), "UTF-8") + "&" + 
        URLEncoder.encode("MESSAGE_DATA", "UTF-8") + "=" + 
        URLEncoder.encode(data, "UTF-8"); 
      OutputStream os = conn.getOutputStream(); 

      BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(os, "UTF-8")); 
      bufferedWriter.write(postData); 
      bufferedWriter.flush(); 
      bufferedWriter.close(); 

      InputStream inputStream = conn.getInputStream(); 
      BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8")); 
      String line = ""; 
      while ((line = bufferedReader.readLine()) != null) { 
       response += line; 
      } 
      bufferedReader.close(); 
      inputStream.close(); 
      conn.disconnect(); 
      os.close(); 
     } catch (MalformedURLException e) { 
      e.printStackTrace(); 
     } catch (UnsupportedEncodingException e) { 
      e.printStackTrace(); 
     } catch (ProtocolException e) { 
      e.printStackTrace(); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 

     return response; 
    } 

    @Override 
    protected void onPostExecute(String s) { 
     //do what ever you want with the response 
     Log.d("roee", s); 
    } 
} 
+0

感謝您的回答! 2沒有工作,它返回相同的錯誤「無法運行doInBackground」,但謝謝你的例子,它是非常有用的。 –

+0

很高興知道,我會編輯我的答案,您可以繼續搜索,因爲我知道還有其他方式不使用此長字符串。 – Roee