2017-04-15 118 views
0

我已经试了几个选项,从Android应用程序发送POST请求到服务器运行PHP文件 我需要发送POST请求,其中以下参数:ID = 0 &余额= 666创建Android应用程序发送POST请求PHP

我有我的应用程序,文下面的代码的应用程序去发送请求的应用程序崩溃

能有人帮助?

ANDROID CODE:

package com.example.hk300.jsonpost; 

import com.google.android.gms.ads.AdListener; 
import com.google.android.gms.ads.AdRequest; 
import com.google.android.gms.ads.InterstitialAd; 

import android.os.AsyncTask; 
import android.os.Bundle; 
import android.support.v7.app.AppCompatActivity; 
import android.util.Log; 
import android.view.Menu; 
import android.view.MenuItem; 
import android.view.View; 
import android.widget.Button; 
import android.widget.TextView; 
import android.widget.Toast; 

import org.json.JSONException; 
import org.json.JSONObject; 

import java.io.DataOutputStream; 
import java.io.IOException; 
import java.io.InputStream; 
import java.io.OutputStream; 
import java.net.HttpURLConnection; 
import java.net.URL; 

import static android.R.id.message; 

public class MainActivity extends AppCompatActivity { 
    // Remove the below line after defining your own ad unit ID. 
    private static final String TOAST_TEXT = "Test ads are being shown. " 
      + "To show live ads, replace the ad unit ID in res/values/strings.xml with your own ad unit ID."; 

    private static final int START_LEVEL = 1; 
    private int mLevel; 
    private Button mNextLevelButton; 
    private InterstitialAd mInterstitialAd; 
    private TextView mLevelTextView; 

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

     // Create the next level button, which tries to show an interstitial when clicked. 
     mNextLevelButton = ((Button) findViewById(R.id.next_level_button)); 
     mNextLevelButton.setEnabled(false); 
     mNextLevelButton.setOnClickListener(new View.OnClickListener() { 
      @Override 
      public void onClick(View view) { 
       showInterstitial(); 
      } 
     }); 

     // Create the text view to show the level number. 
     mLevelTextView = (TextView) findViewById(R.id.level); 
     mLevel = START_LEVEL; 

     // Create the InterstitialAd and set the adUnitId (defined in values/strings.xml). 
     mInterstitialAd = newInterstitialAd(); 
     loadInterstitial(); 

     // Toasts the test ad message on the screen. Remove this after defining your own ad unit ID. 
     Toast.makeText(this, TOAST_TEXT, Toast.LENGTH_LONG).show(); 



    } 


    @Override 
    public boolean onCreateOptionsMenu(Menu menu) { 
     // Inflate the menu; this adds items to the action bar if it is present. 
     getMenuInflater().inflate(R.menu.menu_main, menu); 
     return true; 
    } 

    @Override 
    public boolean onOptionsItemSelected(MenuItem item) { 
     // Handle action bar item clicks here. The action bar will 
     // automatically handle clicks on the Home/Up button, so long 
     // as you specify a parent activity in AndroidManifest.xml. 
     int id = item.getItemId(); 

     if (id == R.id.action_settings) { 
      return true; 
     } 

     return super.onOptionsItemSelected(item); 
    } 

    private InterstitialAd newInterstitialAd() { 
     InterstitialAd interstitialAd = new InterstitialAd(this); 
     interstitialAd.setAdUnitId(getString(R.string.interstitial_ad_unit_id)); 
     interstitialAd.setAdListener(new AdListener() { 
      @Override 
      public void onAdLoaded() { 
       mNextLevelButton.setEnabled(true); 
      } 

      @Override 
      public void onAdFailedToLoad(int errorCode) { 
       mNextLevelButton.setEnabled(true); 
      } 

      @Override 
      public void onAdClosed() { 
       // Proceed to the next level. 
       goToNextLevel(); 
      } 
     }); 
     return interstitialAd; 
    } 

    private void showInterstitial() { 
     // Show the ad if it's ready. Otherwise toast and reload the ad. 
     if (mInterstitialAd != null && mInterstitialAd.isLoaded()) { 
      mInterstitialAd.show(); 
     } else { 
      Toast.makeText(this, "Ad did not load", Toast.LENGTH_SHORT).show(); 
      goToNextLevel(); 
     } 
    } 

    private void loadInterstitial() { 
     // Disable the next level button and load the ad. 
     mNextLevelButton.setEnabled(false); 
     AdRequest adRequest = new AdRequest.Builder() 
       .setRequestAgent("android_studio:ad_template").build(); 
     mInterstitialAd.loadAd(adRequest); 
    } 

    private void goToNextLevel() { 
     // Show the next level and reload the ad to prepare for the level after. 
     mLevelTextView.setText("Level " + (++mLevel)); 
     mInterstitialAd = newInterstitialAd(); 
     loadInterstitial(); 
     new BackgroundTask().execute(); 

    } 

    public class BackgroundTask extends AsyncTask<Void,Void,String> { 

     @Override 
     protected void onPreExecute(){ 
//Do UI operation here and onPostExecute 
      //TextView textview = (TextView)findViewById(R.id.credits); 
      //textview.setText(message); 
     } 
     @Override 
     protected String doInBackground(Void... params) { 
      OutputStream os = null; 
      InputStream is = null; 
      HttpURLConnection conn = null; 
      String contentAsString = null; 
      try { 
       URL url = new URL("https://disjunct-swabs.000webhostapp.com/testapp.php"); 
       JSONObject jsonObject = new JSONObject(); 
       jsonObject.put("id", "0"); 
       jsonObject.put("balance", "666"); 
       String message = jsonObject.toString(); 
       //You cannot perform these UI operation on non-UI thread 

       conn = (HttpURLConnection) url.openConnection(); 
       conn.setReadTimeout(10000 /*milliseconds*/); 
       conn.setConnectTimeout(15000 /* milliseconds */); 
       conn.setRequestMethod("POST"); 
       conn.setDoInput(true); 
       conn.setDoOutput(true); 
       conn.setFixedLengthStreamingMode(message.getBytes().length); 

       conn.setRequestProperty("Content-Type", "application/json;charset=utf-8"); 
       conn.setRequestProperty("X-Requested-With", "XMLHttpRequest"); 

       DataOutputStream wr = new DataOutputStream(conn.getOutputStream()); 

       wr.writeBytes(message); 
       Log.e("JSON Input", message); 
       wr.flush(); 
       wr.close(); 
       conn.connect(); 
       is = conn.getInputStream(); 
       contentAsString = is.toString(); 
      } catch (IOException e) { 
       Log.d("shit", "Shit"); 
      } catch (JSONException e) { 
       Log.d("shit", "Shit"); 
      } finally { 

       conn.disconnect(); 
      } 
      //return response to onPostExecute() 
      return contentAsString; 
     } 

     @Override 
     protected void onPostExecute(String res){ 
      //Do anything with response 

     } 
    } 


} 
+0

什么问题? –

+0

你可以发布错误的细节,比如logcat消息吗? –

+0

logcat只显示:新连接 04-16 17:49:32.709 1609-1609/system_process W/IInputConnectionWrapper:reportFullscreenMode on inexistent InputConnection – hk300

回答

0

你确定你是不是在主UI线程运行此。创建一个新线程或使用AsyncTask来执行网络操作。

public class BackgroundTask extends AsyncTask<String, Void, String> { 

    protected void onPreExecute(){} 

    protected String doInBackground(String... arg0) { 

     try { 

     URL url = new URL("https://disjunct-swabs.000webhostapp.com/testapp.php"); 

     JSONObject postDataParams = new JSONObject(); 
     postDataParams.put("id", "0"); 
     postDataParams.put("balance", "666"); 
     Log.e("params",postDataParams.toString()); 

     HttpURLConnection conn = (HttpURLConnection) url.openConnection(); 
     conn.setReadTimeout(15000 /* milliseconds */); 
     conn.setConnectTimeout(15000 /* milliseconds */); 
     conn.setRequestMethod("POST"); 
     conn.setDoInput(true); 
     conn.setDoOutput(true); 

     OutputStream os = conn.getOutputStream(); 
      BufferedWriter writer = new BufferedWriter(
        new OutputStreamWriter(os, "UTF-8")); 
      writer.write(getPostDataString(postDataParams)); 

      writer.flush(); 
      writer.close(); 
      os.close(); 

      int responseCode=conn.getResponseCode(); 

      if (responseCode == HttpsURLConnection.HTTP_OK) { 

       BufferedReader in=new BufferedReader(new 
         InputStreamReader(
           conn.getInputStream())); 

       StringBuffer sb = new StringBuffer(""); 
       String line=""; 

       while((line = in.readLine()) != null) { 

        sb.append(line); 
        break; 
       } 

       in.close(); 
       return sb.toString(); 

      } 
      else { 
       return new String("false : "+responseCode); 
      } 
     } 
     catch(Exception e){ 
      return new String("Exception: " + e.getMessage()); 
     } 

    } 

    @Override 
    protected void onPostExecute(String result) { 
     Toast.makeText(getApplicationContext(), result, 
       Toast.LENGTH_LONG).show(); 
    } 
} 

public String getPostDataString(JSONObject params) throws Exception { 

    StringBuilder result = new StringBuilder(); 
    boolean first = true; 

    Iterator<String> itr = params.keys(); 

    while(itr.hasNext()){ 

     String key= itr.next(); 
     Object value = params.get(key); 

     if (first) 
      first = false; 
     else 
      result.append("&"); 

     result.append(URLEncoder.encode(key, "UTF-8")); 
     result.append("="); 
     result.append(URLEncoder.encode(value.toString(), "UTF-8")); 

    } 
    return result.toString(); 
} 

} 在上面的线,你不能声明,初始化或任何视图下进行操作(的setText),因为他们必须只在UI线程发生。把在onPreExecute或onPostExecute方法 现在你存运行代码通过

new BackgroundTask().execute(); 

此外,在清单

<uses-permission android:name="android.permission.INTERNET" /> 

添加权限如果您使用的是Android M或以上,则必须运行的过程中要求许可好。这应该是你的goToNextLevel()方法

private void goToNextLevel() { 
    // Show the next level and reload the ad to prepare for the level after. 
    mLevelTextView.setText("Level " + (++mLevel)); 
    mInterstitialAd = newInterstitialAd(); 
    loadInterstitial(); 
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { 
    if (checkSelfPermission(Manifest.permission.INTERNET) != PackageManager.PERMISSION_GRANTED) { 
     requestPermissions(new String[]{ 
       Manifest.permission.INTERNET 
     }, 10); 

    } 
    } 
    new BackgroundTask().execute(); 

} 
+0

心中已经尝试创建一个新的胎面和调用它的应用程序的OnCreate,它停止从崩溃的应用程序,但仍无法将数据发送到PHP。如果它帮助我想要存档的是显示一个admob添加到用户,然后发送到一个数据库(使用PHP文件来处理查询)一些信息(上面的那个),所以基本上我使用的是标准模板从Android工作室admob和实施上面的代码发送的PHP文章。然后我称代码“trycon;”在模板附带的“private void goToNextLevel()”中。 – hk300

+0

我心中已经取代了我的代码与异步任务,但仍然无法正常工作,我甚至去除文本视图的一部分,它不能正常形成现在也许它发布请求,有没有什么办法让我看到POST请求是发送?此外,我已经尝试运行在一个新的Java类的代码,并在主要活动的java – hk300

+0

检查编辑答案 –