【问题标题】:Keep connection open to mysql server with use of Json使用 Json 保持与 mysql 服务器的连接打开
【发布时间】:2017-08-11 09:56:09
【问题描述】:

我在树莓派服务器上的 MySQL 中有一个数据库,我在其中存储有关具有多个属性的机器的数据。我想连接到这个数据库并执行 CRUD(创建、读取、更新、删除)操作。
我使用这些 java 文件连接到一个 PHP 文件,该文件又返回一个 JSON 对象。

public class JSONParser {

String charset = "UTF-8";
HttpURLConnection conn;
DataOutputStream wr;
StringBuilder result;
URL urlObj;
JSONObject jObj = null;
StringBuilder sbParams;
String paramsString;

public JSONObject makeHttpRequest(String url, String method,
                                  HashMap<String, String> params) {

    sbParams = new StringBuilder();
    int i = 0;
    for (String key : params.keySet()) {
        try {
            if (i != 0){
                sbParams.append("&");
            }
            sbParams.append(key).append("=")
                    .append(URLEncoder.encode(params.get(key), charset));

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        i++;
    }

    if (method.equals("POST")) {
        // request method is POST
        try {
            urlObj = new URL(url);

            conn = (HttpURLConnection) urlObj.openConnection();

            conn.setDoOutput(true);

            conn.setRequestMethod("POST");

            conn.setRequestProperty("Accept-Charset", charset);

            conn.setReadTimeout(10000);
            conn.setConnectTimeout(15000);

            conn.connect();

            paramsString = sbParams.toString();

            wr = new DataOutputStream(conn.getOutputStream());
            wr.writeBytes(paramsString);
            wr.flush();
            wr.close();

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    else if(method.equals("GET")){
        // request method is GET

        if (sbParams.length() != 0) {
            url += "?" + sbParams.toString();
        }

        try {
            urlObj = new URL(url);

            conn = (HttpURLConnection) urlObj.openConnection();

            conn.setDoOutput(false);

            conn.setRequestMethod("GET");

            conn.setRequestProperty("Accept-Charset", charset);

            conn.setConnectTimeout(15000);

            conn.connect();

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

    }

    try {
        //Receive the response from the server
        InputStream in = new BufferedInputStream(conn.getInputStream());
        BufferedReader reader = new BufferedReader(new InputStreamReader(in));
        result = new StringBuilder();
        String line;
        while ((line = reader.readLine()) != null) {
            result.append(line);
        }

        Log.d("JSON Parser", "result: " + result.toString());

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

    conn.disconnect();

    // try parse the string to a JSON object
    try {
        jObj = new JSONObject(result.toString());
    } catch (JSONException e) {
        Log.e("JSON Parser", "Error parsing data " + e.toString());
    }

    // return JSON Object
    return jObj;
}
}

然后是我调用这个 JSON 解析器的主类

public class MainActivity extends FragmentActivity{

private static String url_import = "http://192.168.8.100/import.php";
private ProgressDialog progressDialog;
JSONParser Jsonparser = new JSONParser();
String text;
boolean Ohoh;

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

    Button btn = (Button) findViewById(R.id.button);
    btn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            EditText editText = (EditText) findViewById(R.id.editText);
            text = editText.getText().toString();
            new CreateNewProduct().execute();
        }
    });
}

class CreateNewProduct extends AsyncTask <String, String, String> {

    //Show progress dialog
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        progressDialog = new ProgressDialog(MainActivity.this);
        progressDialog.setMessage("WAIT...");
        progressDialog.setIndeterminate(false);
        progressDialog.setCancelable(false);
        progressDialog.show();

    }

    protected String doInBackground(String... args){

        HashMap<String, String> params = new HashMap<>();
        params.put("Name", text);
        params.put("Company", "EDP");
        params.put("Phone Number", "+00856554");

        Log.d("request", "starting");
        //JSON
        JSONObject json =Jsonparser.makeHttpRequest(url_import, "POST", params);

        if(json != null){Ohoh = true;} else{Ohoh = false;}
        return null;
    }

    protected void onPostExecute(String url_link){
        if(Ohoh) {
            TextView itworkd = (TextView) findViewById(R.id.textView);
            itworkd.setText("it workd");
        }
        progressDialog.dismiss();
    }

}

}

我的 PHP 文件非常基本,我只打开连接并发送基本查询。

当我想要进行另一个查询(即使在另一个活动中)时,如何保持此连接打开,以便我不需要再次连接到数据库(需要很长时间对用户不利)?

【问题讨论】:

  • 摆脱 PHP 垃圾并使用带有连接池的 servlet。

标签: android mysql json database


【解决方案1】:

你可以使用改造,这是一种解析Json数据的简单方法,它在你需要数据时保持连接。

public class ApiClint {
    public static final String BASE_URL = "http://192.168.0.105:8080/";
    public static Retrofit retrofit = null;


    public static Retrofit getClient(){
        Gson gson = new GsonBuilder()
                .setLenient()
                .create();
        if (retrofit==null){
            retrofit = new Retrofit.Builder()
                    .baseUrl(BASE_URL)
                    .addConverterFactory(GsonConverterFactory.create(gson))
                    .build();
        }
        return retrofit;
    }
}

并使用 apiservice

public interface ApiService {

    @GET("app/con_get_data.php")
    Call<UserList> getAllDataFood();
    @FormUrlEncoded
    @POST("app/insert.php")
    Call<Response> insert(
            @Field("table_no") String table_no,
            @Field("ordered_item_name") String ordered_item_name,
            @Field("item_quantity") String item_quantity,
            @Field("total_bill_per_item") String total_bill_per_item,
            @Field("total_after_discount") String total_after_discount

    );
}

【讨论】:

  • 我不明白 ApiService 在做什么:s
  • 它是一个接口类。在这里您声明结果集的方法(从您的 url json 字符串获取)...并在您的活动中回调该方法。
猜你喜欢
  • 1970-01-01
  • 2013-12-19
  • 2012-01-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-01-17
  • 1970-01-01
  • 2019-10-16
相关资源
最近更新 更多