-4

我試圖創建一個應用程序,它會發送一些數據到網絡服務器,當一個按鈕被點擊,數據將從窗體中。數據類型是名,姓和其他。我是一名初學者開發人員,並嘗試使用OKHTTPFClient插件從應用程序發送HTTP請求。 我需要的是點擊表單數據將被髮送到PHP,然後PHP會給出一個成功的響應,然後應用程序會得到,然後活動將被重定向到感謝您的活動。下面是我現在想要的代碼 -HTTP請求無法正常工作?

submitRequest.setOnClickListener(new View.OnClickListener() { 
     public void onClick(View v) { 
      if (firstName.getText().toString().length() == 0) { 
       firstName.setError("Please enter your first name!"); 
      } 
      if (firstName.getText().toString().length() != 0) { 

       Toast.makeText(getApplicationContext(), firstName.getText().toString(), Toast.LENGTH_SHORT).show(); 

       requestHTTP(firstName.getText().toString()); 

      } else { 

      } 
     } 
    }); 

這裏是OKHTTPClient方法 -

private void requestHTTP(String first_name) { 
    OkHttpClient httpClient = new OkHttpClient(); 
    String url = "https://www.example.com/action.php"; 

    RequestBody formBody = new FormBody.Builder() 
      .add("first_name", first_name) 
      .build(); 
    Request request = new Request.Builder() 
      .url(url) 
      .post(formBody) 
      .build(); 
    Response response = null; 
    try { 
     response = httpClient.newCall(request).execute(); 
     if (response.isSuccessful()) { 
      Toast.makeText(getApplicationContext(), firstName.getText().toString(), Toast.LENGTH_SHORT).show(); 
     } 

    } catch (IOException e) { 

    } 
} 

UPDATE:

這裏是展示在Android上運行段錯誤 -

E/AndroidRuntime: FATAL EXCEPTION: main 
       Process: com.example.androidapp, PID: 11592 
       android.os.NetworkOnMainThreadException 
        at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1303) 
        at java.net.Inet6AddressImpl.lookupHostByName(Inet6AddressImpl.java:86) 
        at java.net.Inet6AddressImpl.lookupAllHostAddr(Inet6AddressImpl.java:74) 
        at java.net.InetAddress.getAllByName(InetAddress.java:752) 
        at okhttp3.Dns$1.lookup(Dns.java:39) 
        at okhttp3.internal.connection.RouteSelector.resetNextInetSocketAddress(RouteSelector.java:185) 
        at okhttp3.internal.connection.RouteSelector.nextProxy(RouteSelector.java:149) 
        at okhttp3.internal.connection.RouteSelector.next(RouteSelector.java:84) 
        at okhttp3.internal.connection.StreamAllocation.findConnection(StreamAllocation.java:213) 
        at okhttp3.internal.connection.StreamAllocation.findHealthyConnection(StreamAllocation.java:134) 
        at okhttp3.internal.connection.StreamAllocation.newStream(StreamAllocation.java:113) 
        at okhttp3.internal.connection.ConnectInterceptor.intercept(ConnectInterceptor.java:42) 
        at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:147) 
        at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:121) 
        at okhttp3.internal.cache.CacheInterceptor.intercept(CacheInterceptor.java:93) 
        at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:147) 
        at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:121) 
        at okhttp3.internal.http.BridgeInterceptor.intercept(BridgeInterceptor.java:93) 
        at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:147) 
        at okhttp3.internal.http.RetryAndFollowUpInterceptor.intercept(RetryAndFollowUpInterceptor.java:125) 
        at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:147) 
        at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:121) 
        at okhttp3.RealCall.getResponseWithInterceptorChain(RealCall.java:200) 
        at okhttp3.RealCall.execute(RealCall.java:77) 
        at org.goldenfs.payoffcalculator.advisor.requestHTTP(advisor.java:220) 
        at org.goldenfs.payoffcalculator.advisor.access$000(advisor.java:38) 
        at org.goldenfs.payoffcalculator.advisor$4.onClick(advisor.java:188) 
        at android.view.View.performClick(View.java:6261) 
        at android.widget.TextView.performClick(TextView.java:11180) 
        at android.view.View$PerformClick.run(View.java:23748) 
        at android.os.Handler.handleCallback(Handler.java:751) 
        at android.os.Handler.dispatchMessage(Handler.java:95) 
        at android.os.Looper.loop(Looper.java:154) 
        at android.app.ActivityThread.main(ActivityThread.java:6776) 
        at java.lang.reflect.Method.invoke(Native Method) 
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1520) 
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1410) 

終止應用程序。

請幫我解決這個問題。我真的很感謝你的幫助...... :)

+0

print'response.body()。string()'if IF condition –

+0

讓我從控制檯添加錯誤! – eatherpro

+0

爲什麼不使用AsyncTask? –

回答

2

android.os.NetworkOnMainThreadException 在android.os.StrictMode $ AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1303)

您應該使用THREAD

//A thread is a thread of execution in a program. 
    // The Java Virtual Machine allows an application to have multiple threads of execution running concurrently. 
    Thread thread = new Thread(new Runnable() { 

     @Override 
     public void run() { 
      try 
      { 

          OkHttpClient httpClient = new OkHttpClient(); 
          String url = "https://www.example.com/action.php"; 

          RequestBody formBody = new FormBody.Builder() 
            .add("first_name", first_name) 
            .build(); 
          Request request = new Request.Builder() 
            .url(url) 
            .post(formBody) 
            .build(); 
          Response response = null; 
          try { 
           response = httpClient.newCall(request).execute(); 
           if (response.isSuccessful()) { 
            Toast.makeText(getApplicationContext(), firstName.getText().toString(), Toast.LENGTH_SHORT).show(); 
           } 

          } catch (IOException e) { 

          } 

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

    thread.start(); 

OkHttp

+0

'W/System.err:java.lang.RuntimeException:無法在未調用Looper.prepare()的線程中創建處理程序 W/System .err:在android.os.Handler。 (Handler。java:200) W/System.err:在android.os.Handler。 (Handler.java:114) W/System.err:在android.widget.Toast $ TN。 (Toast.java:625) W/System.err:在android.widget.Toast。 (Toast.java:138) W/System.err:at android.widget.Toast.makeText(Toast.java:388) W/System.err:at org.goldenfs.payoffcalculator.advisor $ 4 $ 1.run (advisor.java:209) W/System.err:at java.lang.Thread.run(Thread.java:762)' – eatherpro

+0

@EatherAhmed https://stackoverflow.com/questions/3875184/cant-create-handler -inside-thread-that-has-not-called-looper-準備 –

+0

@EatherAhmed https://stackoverflow.com/a/27599969/3395198 –

2

它會拋出錯誤,因爲你正在嘗試在MainThread上執行網絡操作,不應該這樣做。請在下面添加線條和嘗試,

public void onViewCreated(View view, Bundle savedInstanceState) 
    { 
     int SDK_INT = android.os.Build.VERSION.SDK_INT; 
     if (SDK_INT > 8) 
     { 
      StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder() 
        .permitAll().build(); 
      StrictMode.setThreadPolicy(policy); 
      //your codes here 

     } 
    } 

OR 你可以打電話給你的方法AsyncTask不上MainThread運行。

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

     String data; 
     public YourAsyncTaskName(String data){ 
      this.data= data; 
     } 

     @Override 
     protected String doInBackground(String... params) { 
      requestHTTP(data); 
      return null; 
     } 

     @Override 
     protected void onPostExecute(String result) { 
     } 

     @Override 
     protected void onPreExecute() { 
     } 

     @Override 
     protected void onProgressUpdate(Void... values) { 
     } 
    } 

現在執行你的AsyncTask

submitRequest.setOnClickListener(new View.OnClickListener() { 
     public void onClick(View v) { 
      if (firstName.getText().toString().length() == 0) { 
       firstName.setError("Please enter your first name!"); 
      } 
      if (firstName.getText().toString().length() != 0) { 

       Toast.makeText(getApplicationContext(), firstName.getText().toString(), Toast.LENGTH_SHORT).show(); 

       new YourAsyncTaskName(firstName.getText().toString()).execute(); 


      } else { 

      } 
     } 
    }); 
+0

你可以請分享如何在AsyncTask上運行該方法嗎?這對我和其他初學者會有很大的幫助! – eatherpro

+0

@EatherAhmed現在檢查 – Kuls

+0

@EatherAhmed如果它確實幫助你,那麼你可以將它標記爲答案並接受它。這對其他人很有用。 – Kuls