使用6.0 API(Android)从服务器发送和接收数据

时间:2022-09-25 16:09:15

I'm really confused, i'm trying to develop a simple function that allow me to send and receive data from a server.

我真的很困惑,我正在尝试开发一个简单的功能,允许我从服务器发送和接收数据。

The operation is as follows:

操作如下:

In an activity I execute an HTTP POST to a PHP file on a server, the "PHP file" gets the data that i send (tipically a string), and executes a query using the parameters sent over http.

在一个活动中,我对服务器上的PHP文件执行HTTP POST,“PHP文件”获取我发送的数据(通常是一个字符串),并使用通过http发送的参数执行查询。

Example:

My android app send a string with this value "PIPPO", in the PHP file there is a query, for example:

我的android应用程序发送一个字符串,其值为“PIPPO”,在PHP文件中有一个查询,例如:

$value = PIPPO /* data received from android app*/ Select * from characters where(characters.name=".$value.")

$ value = PIPPO / *从android app收到的数据* /从*中选择*(characters.name =“。$ value。”)

p.s. all data use JSON format

附:所有数据都使用JSON格式

The problem is: i always used a function (that works fine) but now all methods are deprecated, I can't find an alternative to the methods for the newest API.

问题是:我总是使用一个函数(工作正常)但现在所有的方法都被弃用了,我找不到最新API方法的替代方法。

This is my code:

这是我的代码:

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;

2 个解决方案

#1


1  

Just try this code. :)

试试这个代码。 :)

    public class MainActivity extends AppCompatActivity {

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


     //AsyncTask 
     class Test extends AsyncTask < String, Void, String > {

      @Override
      protected String doInBackground(String...params) {
       InputStream in = null;
       String queryResult = "";
       URL url = new URL("http://www.android.com/");
       HttpURLConnection urlConnection = (HttpURLConnection)          url.openConnection();

      //add parameters
      urlConnection.setReadTimeout(10000);
      urlConnection.setConnectTimeout(15000);
      urlConnection.setRequestMethod("POST");
      urlConnection.setDoInput(true);
      urlConnection.setDoOutput(true);

     List<NameValuePair> params = new ArrayList<NameValuePair>();
     params.add(new BasicNameValuePair("firstParam", paramValue1));
     params.add(new BasicNameValuePair("secondParam", paramValue2));
     params.add(new BasicNameValuePair("thirdParam", paramValue3));
       try {
    //write OutputStream
    OutputStream os = urlConnection.getOutputStream();
    BufferedWriter writer = new BufferedWriter(
            new OutputStreamWriter(os, "UTF-8"));
    writer.write(getQuery(params));
    writer.flush();
    writer.close();
    os.close();


        InputStream in = new     BufferedInputStream(urlConnection.getInputStream());
        queryResult = readStream( in );
       } finally {
        urlConnection.disconnect();
       }
       return queryResult;

      }
      private String readStream(InputStream iStream) throws IOException {

       //Buffered reader allows us to read line by line
       try (BufferedReader bReader =
        new BufferedReader(new InputStreamReader(iStream))) {
        StringBuilder builder = new StringBuilder();
        String line;
        while ((line = bReader.readLine()) != null) { //Read till end
         builder.append(line);
        }
        return builder.toString();
       }
      }
    private String getQuery(List<NameValuePair> params) throws   UnsupportedEncodingException
    {
        StringBuilder result = new StringBuilder();
        boolean first = true;

        for (NameValuePair pair : params)
        {
            if (first)
                first = false;
            else
                result.append("&");

            result.append(URLEncoder.encode(pair.getName(), "UTF-8"));
            result.append("=");
            result.append(URLEncoder.encode(pair.getValue(), "UTF-8"));
        }

        return result.toString();
    }
      protected void onPostExecute(String data) {
       // do further things 
       Toast toast = Toast.makeText(getApplicationContext(), data,
        Toast.LENGTH_SHORT);
       toast.show();

      }

     }

    }

#2


0  

Maybe its the time you start using volley. It's a great library and made just for to solve your purpose.

也许是你开始使用凌空的时候了。这是一个很棒的图书馆,只是为了解决你的目的。

Don't know anything about volley. Well don't worry. Here is a perfect video to tell you what volley is capable of. It includes all the steps to include it in your project (although it is nothing more than mentioning gradle dependency)

对排球一无所知。好吧别担心。这是一个完美的视频,告诉你凌空的能力。它包括将它包含在项目中的所有步骤(尽管它只不过是提到gradle依赖)

I am also mentioning a sample example of how you can use it in your code.

我还提到了一个示例,说明如何在代码中使用它。

public class MainActivity extends Activity {
    private TextView txtDisplay;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);
         setContentView(R.layout.activity_main);
         txtDisplay = (TextView) findViewById(R.id.txtDisplay);

         RequestQueue queue = Volley.newRequestQueue(this);
         String url = "myurl/queryMobile.php";

         JSONObject params = new JSONObject();
         params.put("name", "Dexter");

         JsonObjectRequest jsObjRequest = 
                 new JsonObjectRequest(Request.Method.POST,
                          url,
                          param,
                          new Response.Listener<JSONObject>() {
                              @Override
                              public void onResponse(JSONObject response) {
                              // TODO Auto-generated method stub
                              txtDisplay.setText("Response => "+response.toString());
                              findViewById(R.id.progressBar1).setVisibility(View.GONE);
}}, 
                         new Response.ErrorListener() {
                              @Override
                              public void onErrorResponse(VolleyError error) {
                              // TODO Auto-generated method stub
                              }
                         });
  queue.add(jsObjRequest);
  }
}

The original code (and tutorial) is available here.

原始代码(和教程)可在此处获得。

Believe me someday you will have to move to volley, why not today!

相信我有一天你将不得不采取截击,为什么不今天!

#1


1  

Just try this code. :)

试试这个代码。 :)

    public class MainActivity extends AppCompatActivity {

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


     //AsyncTask 
     class Test extends AsyncTask < String, Void, String > {

      @Override
      protected String doInBackground(String...params) {
       InputStream in = null;
       String queryResult = "";
       URL url = new URL("http://www.android.com/");
       HttpURLConnection urlConnection = (HttpURLConnection)          url.openConnection();

      //add parameters
      urlConnection.setReadTimeout(10000);
      urlConnection.setConnectTimeout(15000);
      urlConnection.setRequestMethod("POST");
      urlConnection.setDoInput(true);
      urlConnection.setDoOutput(true);

     List<NameValuePair> params = new ArrayList<NameValuePair>();
     params.add(new BasicNameValuePair("firstParam", paramValue1));
     params.add(new BasicNameValuePair("secondParam", paramValue2));
     params.add(new BasicNameValuePair("thirdParam", paramValue3));
       try {
    //write OutputStream
    OutputStream os = urlConnection.getOutputStream();
    BufferedWriter writer = new BufferedWriter(
            new OutputStreamWriter(os, "UTF-8"));
    writer.write(getQuery(params));
    writer.flush();
    writer.close();
    os.close();


        InputStream in = new     BufferedInputStream(urlConnection.getInputStream());
        queryResult = readStream( in );
       } finally {
        urlConnection.disconnect();
       }
       return queryResult;

      }
      private String readStream(InputStream iStream) throws IOException {

       //Buffered reader allows us to read line by line
       try (BufferedReader bReader =
        new BufferedReader(new InputStreamReader(iStream))) {
        StringBuilder builder = new StringBuilder();
        String line;
        while ((line = bReader.readLine()) != null) { //Read till end
         builder.append(line);
        }
        return builder.toString();
       }
      }
    private String getQuery(List<NameValuePair> params) throws   UnsupportedEncodingException
    {
        StringBuilder result = new StringBuilder();
        boolean first = true;

        for (NameValuePair pair : params)
        {
            if (first)
                first = false;
            else
                result.append("&");

            result.append(URLEncoder.encode(pair.getName(), "UTF-8"));
            result.append("=");
            result.append(URLEncoder.encode(pair.getValue(), "UTF-8"));
        }

        return result.toString();
    }
      protected void onPostExecute(String data) {
       // do further things 
       Toast toast = Toast.makeText(getApplicationContext(), data,
        Toast.LENGTH_SHORT);
       toast.show();

      }

     }

    }

#2


0  

Maybe its the time you start using volley. It's a great library and made just for to solve your purpose.

也许是你开始使用凌空的时候了。这是一个很棒的图书馆,只是为了解决你的目的。

Don't know anything about volley. Well don't worry. Here is a perfect video to tell you what volley is capable of. It includes all the steps to include it in your project (although it is nothing more than mentioning gradle dependency)

对排球一无所知。好吧别担心。这是一个完美的视频,告诉你凌空的能力。它包括将它包含在项目中的所有步骤(尽管它只不过是提到gradle依赖)

I am also mentioning a sample example of how you can use it in your code.

我还提到了一个示例,说明如何在代码中使用它。

public class MainActivity extends Activity {
    private TextView txtDisplay;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);
         setContentView(R.layout.activity_main);
         txtDisplay = (TextView) findViewById(R.id.txtDisplay);

         RequestQueue queue = Volley.newRequestQueue(this);
         String url = "myurl/queryMobile.php";

         JSONObject params = new JSONObject();
         params.put("name", "Dexter");

         JsonObjectRequest jsObjRequest = 
                 new JsonObjectRequest(Request.Method.POST,
                          url,
                          param,
                          new Response.Listener<JSONObject>() {
                              @Override
                              public void onResponse(JSONObject response) {
                              // TODO Auto-generated method stub
                              txtDisplay.setText("Response => "+response.toString());
                              findViewById(R.id.progressBar1).setVisibility(View.GONE);
}}, 
                         new Response.ErrorListener() {
                              @Override
                              public void onErrorResponse(VolleyError error) {
                              // TODO Auto-generated method stub
                              }
                         });
  queue.add(jsObjRequest);
  }
}

The original code (and tutorial) is available here.

原始代码(和教程)可在此处获得。

Believe me someday you will have to move to volley, why not today!

相信我有一天你将不得不采取截击,为什么不今天!