Android 不推荐的方法,如何用新方法替换它

Android 不推荐的方法,如何用新方法替换它,android,apache,http,Android,Apache,Http,我对一些不推荐的方法有一个问题,特别是我在这里发布的这个方法 我想要的很简单:使用http post将数据发送到服务器-->使用从客户端接收的数据进行查询-->发送回复 我正在尝试使用API6.0开发一个Android应用程序,但是我所有的方法都被弃用了,我必须改变什么才能用新的API转换我的代码 public class ReadServer extends Activity { String result; public String readserver(String id_data,

我对一些不推荐的方法有一个问题,特别是我在这里发布的这个方法

我想要的很简单:使用http post将数据发送到服务器-->使用从客户端接收的数据进行查询-->发送回复

我正在尝试使用API6.0开发一个Android应用程序,但是我所有的方法都被弃用了,我必须改变什么才能用新的API转换我的代码

public class ReadServer extends Activity {
 String result;
 public String readserver(String id_data, String data){
 try{
  HttpClient httpclient = new DefaultHttpClient();
  HttpPost httpPost = new HttpPost("myurl/queryMobile.php");
  StringBuilder builder = new StringBuilder();
  String json = "";
  //Build jsonObject
  JSONObject jsonObject = new JSONObject();
  jsonObject.accumulate(id_data, data);
  //Convert JSONObject to JSON to String
  json = jsonObject.toString();

  //Set json to StringEntity
  StringEntity se = new StringEntity(json);
  //Set httpPost Entity
  httpPost.setEntity(se);
  //Set some headers to inform server about the type of the content
  httpPost.setHeader("Accept", "application/json");
  httpPost.setHeader("Content-type", "application/json");

  //Execute POST request to the given URL
  HttpResponse httpResponse = httpclient.execute(httpPost);
  //Receive response as inputStream
  StatusLine statusLine = httpResponse.getStatusLine();
  int statusCode = statusLine.getStatusCode();
  //Convert input stream to string
  AlertDialog.Builder alertDialog;

  switch(statusCode){
  case 200:
  HttpEntity entity = httpResponse.getEntity();
  InputStream content = entity.getContent();
  BufferedReader reader = new BufferedReader(new InputStreamReader(content));
  String line="";
  try{
  while ((line = reader.readLine()) != null) {
  builder.append(line);
  result = builder.toString();
  }
  }catch(Exception e){
  alertDialog = new AlertDialog.Builder(this);
  alertDialog.setTitle("400 Bad Request");
  alertDialog.setMessage("Non è stato possibile soddisfare la tua richiesta, riprova più tardi.");
  alertDialog.show();
  }
  break;

  case 500:
  alertDialog = new AlertDialog.Builder(this);
  alertDialog.setTitle("500 Internal Server Error");
  alertDialog.setMessage("Non è stato possibile soddisfare la tua richiesta, riprova più tardi.");
  alertDialog.show();
  break;

  case 503:
  alertDialog = new AlertDialog.Builder(this);
  alertDialog.setTitle("503 Service Unavailable");
  alertDialog.setMessage("Il server di ....non è al momento disponibile, riprova più tardi.");
  alertDialog.show();
  break;

  case 504:
  alertDialog = new AlertDialog.Builder(this);
  alertDialog.setTitle("504 Gateway Timeout");
  alertDialog.setMessage("Il server di ....è momentaneamente sovraccarico, riprova più tardi.");
  alertDialog.show();
  break;

  default:
  alertDialog = new AlertDialog.Builder(this);
  alertDialog.setTitle("Si è verificato un errore");
  alertDialog.setMessage("Errore 001" +"\n"+"Non è stato possibile soddisfare la tua richiesta, riprova più tardi.");
  alertDialog.show();
  break;
  }
  }catch(Exception e){
  AlertDialog.Builder alertDialog = new AlertDialog.Builder(this);
  alertDialog.setTitle("Si è verificato un errore");
  alertDialog.setMessage("Errore 001" + "\n" + "Non è stato possibile soddisfare la tua richesta, riprova più tardi.");
  alertDialog.show();
  }
  return result; 
 }
}
我试图更改某些方法,但不知道如何转换某些过程,例如:

setEntity、HttpResponse、StatusLine

我绝对需要用new更改不推荐使用的方法,我无法更改所有代码

编辑1: 例如,在我的主要活动中:

 ReadServer read = new ReadServer();
 String result = read.readserver("list_news","homepage");
我的类ReadServer输入两个参数:

public String readserver(String id_data, String data){
...
jsonObject.accumulate(id_data, data); // in a jsonObject i put two params
...
}
我发了一个Http帖子,我的数据被发送到我的服务器(我的php页面)

在这一点上,我得到了我的数据,我可以进行查询:

if (isset($list_news)) {
 switch($list_news){
  case "homepage":
   $q = "SELECT 
         FROM 
         WHERE ";

我认为您可以参考我的以下示例代码,然后将其逻辑用于您的应用程序:

private class POSTRequest extends AsyncTask<Void, Void, String> {

        @Override
        protected String doInBackground(Void... voids) {
            String address = "http://192.16.1.100:24780/api/token";
            HttpURLConnection urlConnection;
            String requestBody;
            Uri.Builder builder = new Uri.Builder();
            Map<String, String> stringMap = new HashMap<>();
            stringMap.put("grant_type", "password");
            stringMap.put("username", "bnk");
            stringMap.put("password", "bnkpwd");

            Iterator entries = stringMap.entrySet().iterator();
            while (entries.hasNext()) {
                Map.Entry entry = (Map.Entry) entries.next();
                builder.appendQueryParameter(entry.getKey().toString(), entry.getValue().toString());
                entries.remove();
            }
            requestBody = builder.build().getEncodedQuery();

            try {
                URL url = new URL(address);
                urlConnection = (HttpURLConnection) url.openConnection();
                urlConnection.setDoInput(true);
                urlConnection.setDoOutput(true);
                // urlConnection.setRequestMethod("POST");
                urlConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
                OutputStream outputStream = new BufferedOutputStream(urlConnection.getOutputStream());
                BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outputStream, "utf-8"));
                writer.write(requestBody);
                writer.flush();
                writer.close();
                outputStream.close();

                JSONObject jsonObject = new JSONObject();
                InputStream inputStream;
                // get stream
                if (urlConnection.getResponseCode() < HttpURLConnection.HTTP_BAD_REQUEST) {
                    inputStream = urlConnection.getInputStream();
                } else {
                    inputStream = urlConnection.getErrorStream();
                }
                // parse stream
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
                String temp, response = "";
                while ((temp = bufferedReader.readLine()) != null) {
                    response += temp;
                }
                // put into JSONObject
                jsonObject.put("Content", response);
                jsonObject.put("Message", urlConnection.getResponseMessage());
                jsonObject.put("Length", urlConnection.getContentLength());
                jsonObject.put("Type", urlConnection.getContentType());

                return jsonObject.toString();
            } catch (IOException | JSONException e) {
                return e.toString();
            }
        }

        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);
            Log.i(LOG_TAG, "POST\n" + result);
        }
    }
你可以在网站上阅读更多

其他好的解决方案供您参考:


希望这有帮助

@BKN:在你的解决方案中,我可以看到你正在使用hashmap将数据发送到你的“服务器”,在我的项目中,我只需要发送两个字符串“id data”和“data”,例如:id_data=“weather”和data=“rainy”。如何避免使用hashmap?谢谢你告诉我你为什么不喜欢使用hashmap?当然,我的服务器上有一个无法修改的.php文件,当我从我的android设备发出HTTP请求时,我需要发送两个字符串,你可以在我的编辑中看到我的php代码的一小部分。对不起,我不熟悉php,但是看起来你需要一个字符串体,例如,天气=下雨?你能发布你使用一些工具(如邮递员)发送请求的截图吗?
private class POSTRequest extends AsyncTask<Void, Void, String> {

        @Override
        protected String doInBackground(Void... voids) {
            String address = "http://192.16.1.100:24780/api/token";
            HttpURLConnection urlConnection;
            String requestBody;
            Uri.Builder builder = new Uri.Builder();
            Map<String, String> stringMap = new HashMap<>();
            stringMap.put("grant_type", "password");
            stringMap.put("username", "bnk");
            stringMap.put("password", "bnkpwd");

            Iterator entries = stringMap.entrySet().iterator();
            while (entries.hasNext()) {
                Map.Entry entry = (Map.Entry) entries.next();
                builder.appendQueryParameter(entry.getKey().toString(), entry.getValue().toString());
                entries.remove();
            }
            requestBody = builder.build().getEncodedQuery();

            try {
                URL url = new URL(address);
                urlConnection = (HttpURLConnection) url.openConnection();
                urlConnection.setDoInput(true);
                urlConnection.setDoOutput(true);
                // urlConnection.setRequestMethod("POST");
                urlConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
                OutputStream outputStream = new BufferedOutputStream(urlConnection.getOutputStream());
                BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outputStream, "utf-8"));
                writer.write(requestBody);
                writer.flush();
                writer.close();
                outputStream.close();

                JSONObject jsonObject = new JSONObject();
                InputStream inputStream;
                // get stream
                if (urlConnection.getResponseCode() < HttpURLConnection.HTTP_BAD_REQUEST) {
                    inputStream = urlConnection.getInputStream();
                } else {
                    inputStream = urlConnection.getErrorStream();
                }
                // parse stream
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
                String temp, response = "";
                while ((temp = bufferedReader.readLine()) != null) {
                    response += temp;
                }
                // put into JSONObject
                jsonObject.put("Content", response);
                jsonObject.put("Message", urlConnection.getResponseMessage());
                jsonObject.put("Length", urlConnection.getContentLength());
                jsonObject.put("Type", urlConnection.getContentType());

                return jsonObject.toString();
            } catch (IOException | JSONException e) {
                return e.toString();
            }
        }

        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);
            Log.i(LOG_TAG, "POST\n" + result);
        }
    }
...
                JSONObject json = new JSONObject();
                json.put("key1", "sample value...");
                requestBody = json.toString();
                URL url = new URL(address);
                urlConnection = (HttpURLConnection) url.openConnection();
                urlConnection.setDoInput(true);
                urlConnection.setDoOutput(true);
                urlConnection.setRequestProperty("Content-Type", "application/json");
                OutputStream outputStream = new BufferedOutputStream(urlConnection.getOutputStream());
                BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outputStream, "utf-8"));
                writer.write(requestBody);
                writer.flush();
                writer.close();
                outputStream.close();
...