Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/353.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/jquery-ui/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 创建向PHP发送POST请求的android应用程序_Java_Php_Android_Json_Http Post - Fatal编程技术网

Java 创建向PHP发送POST请求的android应用程序

Java 创建向PHP发送POST请求的android应用程序,java,php,android,json,http-post,Java,Php,Android,Json,Http Post,我已经尝试了几个选项,从android应用程序向运行PHP文件的服务器发送post请求 我需要发送一个POST请求,其中包含以下参数:id=0&balance=666 我的应用程序上有以下代码,应用程序将发送请求,应用程序将崩溃 有人能帮忙吗 ANDROID代码: package com.example.hk300.jsonpost; import com.google.android.gms.ads.AdListener; import com.google.android.gms.ads.

我已经尝试了几个选项,从android应用程序向运行PHP文件的服务器发送post请求 我需要发送一个POST请求,其中包含以下参数:id=0&balance=666

我的应用程序上有以下代码,应用程序将发送请求,应用程序将崩溃

有人能帮忙吗

ANDROID代码:

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

        }
    }


}
package com.example.hk300.jsonpost;
导入com.google.android.gms.ads.AdListener;
导入com.google.android.gms.ads.AdRequest;
导入com.google.android.gms.ads.alad;
导入android.os.AsyncTask;
导入android.os.Bundle;
导入android.support.v7.app.AppActivity;
导入android.util.Log;
导入android.view.Menu;
导入android.view.MenuItem;
导入android.view.view;
导入android.widget.Button;
导入android.widget.TextView;
导入android.widget.Toast;
导入org.json.JSONException;
导入org.json.JSONObject;
导入java.io.DataOutputStream;
导入java.io.IOException;
导入java.io.InputStream;
导入java.io.OutputStream;
导入java.net.HttpURLConnection;
导入java.net.URL;
导入静态android.R.id.message;
公共类MainActivity扩展了AppCompatActivity{
//定义您自己的广告单元ID后,删除下面的行。
私有静态最终字符串TOAST\u TEXT=“正在显示测试广告。”
+“若要显示实时广告,请将res/values/strings.xml中的广告单元ID替换为您自己的广告单元ID。”;
专用静态最终int START_级别=1;
私人内部水平;
私有按钮mNextLevelButton;
私人间质;
私有文本视图mLevelTextView;
@凌驾
创建时受保护的void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//创建下一级按钮,单击该按钮时尝试显示间隙。
mNextLevelButton=((按钮)findViewById(R.id.next_level_按钮));
mNextLevelButton.setEnabled(false);
mNextLevelButton.setOnClickListener(新视图.OnClickListener(){
@凌驾
公共void onClick(视图){
showInterstitial();
}
});
//创建文本视图以显示标高编号。
mLevelTextView=(TextView)findViewById(R.id.level);
mLevel=开始水平;
//创建InterstitualAD并设置adUnitId(在values/strings.xml中定义)。
minterstitalad=newinterstitalad();
加载间隙();
//在屏幕上烘烤测试广告消息。在定义自己的广告单元ID后删除此消息。
Toast.makeText(this,Toast_TEXT,Toast.LENGTH_LONG).show();
}
@凌驾
公共布尔onCreateOptions菜单(菜单){
//为菜单充气;这会将项目添加到操作栏(如果存在)。
getMenuInflater().充气(右菜单菜单菜单主菜单);
返回true;
}
@凌驾
公共布尔值onOptionsItemSelected(菜单项项){
//处理操作栏项目单击此处。操作栏将
//自动处理Home/Up按钮上的点击,只要
//在AndroidManifest.xml中指定父活动时。
int id=item.getItemId();
if(id==R.id.action\u设置){
返回true;
}
返回super.onOptionsItemSelected(项目);
}
私人间质新间质(){
interstitalad interstitalad=新的interstitalad(本);
interstitularad.setAdUnitId(getString(R.string.interstitular_ad_unit_id));
interstituralad.setAdListener(新的AdListener(){
@凌驾
已加载的公共无效(){
mNextLevelButton.setEnabled(真);
}
@凌驾
在失败的TOLOAD上公开无效(int错误代码){
mNextLevelButton.setEnabled(真);
}
@凌驾
已关闭的()上的公共无效{
//进入下一个层次。
goToNextLevel();
}
});
返回间隙翼;
}
私人间隙{
//如果广告准备好了,则显示广告。否则,敬酒并重新加载广告。
if(minterstitalad!=null&&minterstitalad.isload()){
minterstitalad.show();
}否则{
Toast.makeText(此“广告未加载”,Toast.LENGTH_SHORT.show();
goToNextLevel();
}
}
私有void loadinterstitual(){
//禁用下一级按钮并加载广告。
mNextLevelButton.setEnabled(false);
AdRequest AdRequest=新建AdRequest.Builder()
.setRequestAgent(“android_studio:ad_模板”).build();
Minterstitalad.loadAd(地址);
}
私有void goToNextLevel(){
//显示下一个关卡,并重新加载广告,为之后的关卡做好准备。
setText(“级别”+(++mLevel));
minterstitalad=newinterstitalad();
加载间隙();
新建BackgroundTask().execute();
}
公共类BackgroundTask扩展了AsyncTask{
@凌驾
受保护的void onPreExecute(){
//在此处执行UI操作,然后执行onPostExecute
//TextView TextView=(TextView)findViewById(R.id.credits);
//textview.setText(消息);
}
@凌驾
受保护字符串doInBackground(无效…参数){
OutputStream os=null;
InputStream=null;
HttpURLConnection conn=null;
字符串contentAsString=null;
试一试{
URL=新URL(“https://disjunct-swabs.000webhostapp.com/testapp.php");
JSONObject JSONObject=新的JSONObject();
jsonObject.put(“id”,“0”);
jsonObject.put(“余额”、“666”);
字符串消息=jsonObject.toString();
//您不能在非UI线程上执行这些UI操作
骗局
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();
}
new BackgroundTask().execute();
<uses-permission android:name="android.permission.INTERNET" />
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();

}