将数据发送到服务器

时间:2017-10-20 13:47:42

标签: android http server outputstream

所以我要将简单的代码发布到我正在编写的程序中。这是我的问题。我想我正在连接到我的服务器就好了(因为我在网上发布我会用假的服务器替换服务器地址)我想知道我是否真的将变量发送到服务器。我使用此字符串将数据发送到PHP服务器(“?systemid = demo& pwd = demo& reason = do%20something& qnumber = A36”)。这是硬编码用于测试目的。我的问题是,我实际上是在发送数据吗?似乎没有send()方法。请原谅我的无知。我是Android的新手。

我的想法是,当我写入OutputStream时,我也在发送数据。请看一下

public class PrintTicketActivity extends AppCompatActivity {

    private static final String TAG2 = "PrintTicketActivity";

    Context mContext;
    Button mButtonA, mButtonB, mButtonC, mButtonD, mButtonE, mButtonF;
    List<Button> mButtons;
    List<PrintJob> mPrintJobs;
    WebView mWebView;
    int printJobNum = 1;

    // here i'm initializing the variables with an arbitrary value so the compiler won't complain
    // that they may have not been initialized in the button's onclick listeners
    // these values are overwritten from sharedPreferences anyway.....the file will always exist unless there is a major problem
    int numA, numB, numC, numD, numE, numF;
    String buttonA, buttonB, buttonC, buttonD, buttonE, buttonF;

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

        mContext = this;
        mButtons = new ArrayList<>();
        mPrintJobs = new ArrayList<>();

        mButtonA = (Button) findViewById(R.id.button_a);
        mButtonB = (Button) findViewById(R.id.button_b);
        mButtonC = (Button) findViewById(R.id.button_c);
        mButtonD = (Button) findViewById(R.id.button_d);
        mButtonE = (Button) findViewById(R.id.button_e);
        mButtonF = (Button) findViewById(R.id.button_f);

        // add the buttons to the list so we can check later to see if any of the buttons has empty text
        // and then hide the button if it is empty
        mButtons.add(mButtonA);
        mButtons.add(mButtonB);
        mButtons.add(mButtonC);
        mButtons.add(mButtonD);
        mButtons.add(mButtonE);
        mButtons.add(mButtonF);


        // check for the start up file
        File file = new File("data/data/com.myDomain.myProgram/shared_prefs/start.xml");

        if (file.exists()) {

            // place text from preferences on the buttons
            updateUI();

        } else {
            Toast.makeText(mContext, "Something went wrong", Toast.LENGTH_SHORT).show();
        }

        mButtonA.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                executeQueue(NUMBER_A, numA, "A", mButtonA);
                new SendQueueToServer().execute();

            }
        });
        mButtonB.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                executeQueue(NUMBER_B, numB, "B", mButtonB);
            }
        });
        mButtonC.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                executeQueue(NUMBER_C, numC, "C", mButtonC);
            }
        });
        mButtonD.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                executeQueue(NUMBER_D, numD, "D", mButtonD);
            }
        });
        mButtonE.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                executeQueue(NUMBER_E, numE, "E", mButtonE);
            }
        });
        mButtonF.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                executeQueue(NUMBER_F, numF, "F", mButtonF);
            }
        });
    }

    private void executeQueue(String prefKey, int num, String category, Button button) {

        printTicket(button.getText().toString(), category + num);

        // increment the number after printing the ticket
        ++num;

        // update the number in the shared preferences
        SharedPreferences.Editor editor = getSharedPreferences(MY_PREFS, MODE_PRIVATE).edit();
        editor.putInt(prefKey, num);
        editor.apply();

        // update the UI to get an updated version of the queue number
        updateUI();
    }

    private void updateUI() {
        SharedPreferences preferences = getSharedPreferences(MY_PREFS, MODE_PRIVATE);
        buttonA = preferences.getString(A, "");
        buttonB = preferences.getString(B, "");
        buttonC = preferences.getString(C, "");
        buttonD = preferences.getString(D, "");
        buttonE = preferences.getString(E, "");
        buttonF = preferences.getString(F, "");
        numA = preferences.getInt(NUMBER_A, 1);
        numB = preferences.getInt(NUMBER_B, 1);
        numC = preferences.getInt(NUMBER_C, 1);
        numD = preferences.getInt(NUMBER_D, 1);
        numE = preferences.getInt(NUMBER_E, 1);
        numF = preferences.getInt(NUMBER_F, 1);

        mButtonA.setText(buttonA);
        mButtonB.setText(buttonB);
        mButtonC.setText(buttonC);
        mButtonD.setText(buttonD);
        mButtonE.setText(buttonE);
        mButtonF.setText(buttonF);

        // if a button doesn't have anything assigned to it, hide the button
        for (Button button : mButtons) {
            if (button.getText().equals("")) {
                button.setVisibility(View.GONE);
            }
        }
    }

    private void printTicket(String queueTitle, String queueCategory) {
        // create a WebView object for printing
        WebView webView = new WebView(mContext);
        webView.setWebViewClient(new WebViewClient() {

            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                return false;
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                Log.i(TAG2, "page finished loading " + url);
                createWebPrintJob(view);
                mWebView = null;
            }
        });

        String html = "<html><body><h2 style=\"text-align:center;font-size:60px\">" + queueTitle + "</h2><h1 style=\"text-align:center" +
                ";font-size:200px\">" +
                queueCategory + "</h1>";
        webView.loadDataWithBaseURL(null, html, "text/HTML", "UTF-8", null);

        // Keep a reference to WebView object until you pass the PrintDocumentAdapter
        // to the PrintManager
        mWebView = webView;
    }

    @SuppressWarnings("deprecation")
    private void createWebPrintJob(WebView webView) {
        PrintManager printManager = (PrintManager) mContext.getSystemService(Context.PRINT_SERVICE);

        // Get a print adapter instance
        PrintDocumentAdapter printAdapter;
        if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            printAdapter = webView.createPrintDocumentAdapter("print_job_num" + printJobNum);
            printJobNum++;
        } else {
            printAdapter = webView.createPrintDocumentAdapter();
            printJobNum++;
        }

        // Create a print job with name and adapter instance
        String jobName = getString(R.string.app_name) + " Document";
        PrintJob printJob = printManager.print(jobName, printAdapter,
                new PrintAttributes.Builder().build());

        // save for status checking later
        mPrintJobs.add(printJob);
    }

    @Override
    protected void onResume() {
        super.onResume();

        updateUI();
    }


//    @Override
//    public void onBackPressed() {
//        // don't add superclass constructor
//        // I am disabling the back button here
//    }


    private class SendQueueToServer extends AsyncTask<String, String, String> {

        @Override
        protected String doInBackground(String... params) {

            OutputStream out = null;
            String urlParameters = "?systemid=demo&pwd=demo&reason=do%20something&qnumber=A36";
            HttpsURLConnection connection = null;

            try {
                URL url = new URL("https://www.example.com/php");
                connection = (HttpsURLConnection) url.openConnection();
                connection.setRequestMethod("POST");
                connection.setDoOutput(true);
                connection.connect();
                out = new DataOutputStream(connection.getOutputStream());

                BufferedWriter writer = new BufferedWriter(
                        new OutputStreamWriter(out, "UTF-8"));

                writer.write(urlParameters);
                writer.flush();
                writer.close();

                Log.d(TAG2, " and the response is: " + connection.getResponseMessage());

                Log.d(TAG2, "you are connected and good to go");

            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                assert connection != null;
                connection.disconnect();
            }
            return null;
        }
    }
}

2 个答案:

答案 0 :(得分:0)

url参数表示您正在尝试发出GET请求,这不是发出HTTP GET请求的正确过程。如果要发出GET请求,则无需向OutputStreamWriter写入任何内容。这是一个相同的模板:

URL url;
HttpURLConnection urlConnection = null;
String urlParameters = "?systemid=demo&pwd=demo&reason=do%20something&qnumber=A36";

try {
    url = new URL("https://www.example.com/php"+urlParameters);

    urlConnection = (HttpURLConnection) url
            .openConnection();

    //use this block of code in case you are looking for some response from your server
    InputStream in = urlConnection.getInputStream();

    InputStreamReader isw = new InputStreamReader(in);

    int data = isw.read();
    while (data != -1) {
        char current = (char) data;
        data = isw.read();
        System.out.print(current);
    }
} catch (Exception e) {
    e.printStackTrace();
} finally {
    if (urlConnection != null) {
        urlConnection.disconnect();
    }    
}

答案 1 :(得分:0)

您可以使用Retrofit Library将数据发送到服务器。使用此库与Server进行通信非常容易。

访问http://square.github.io/retrofit/获取有关如何在Android / Java中使用此库的教程。