Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;

import android.net.Uri;

import android.util.Log;

import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.BufferedWriter;

import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;

public class Main {
    private static String IP_ADDRESS = "192.168.43.235";

    public static String UdatePlayerBT(String userName, String device) {

        String retStr = "";

        try {
            URL url = new URL("http://" + IP_ADDRESS + "/RiddleQuizApp/ServerSide/PostaviBTdevice.php");

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

            Log.e("http", "por1");

            JSONObject data = new JSONObject();

            data.put("username", userName);
            data.put("bt_device", device);

            Log.e("http", "por3");

            Uri.Builder builder = new Uri.Builder().appendQueryParameter("action", data.toString());
            String query = builder.build().getEncodedQuery();

            Log.e("http", "por4");

            OutputStream os = conn.getOutputStream();
            BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
            bw.write(query);
            Log.e("http", "por5");
            bw.flush();
            bw.close();
            os.close();
            int responseCode = conn.getResponseCode();

            Log.e("http", String.valueOf(responseCode));
            if (responseCode == HttpURLConnection.HTTP_OK) {
                retStr = inputStreamToString(conn.getInputStream());
            } else
                retStr = String.valueOf("Error: " + responseCode);

            Log.e("http", retStr);

        } catch (Exception e) {
            Log.e("http", "greska");
        }
        return retStr;
    }

    private static String inputStreamToString(InputStream is) {
        String line = "";
        StringBuilder total = new StringBuilder();
        BufferedReader bf = new BufferedReader(new InputStreamReader(is));
        try {
            while ((line = bf.readLine()) != null) {
                total.append(line);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return total.toString();
    }
}