Send and receive data from the server using the 6.0 API (Android)

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

The operation is as follows:

In action, I perform an HTTP POST for the PHP file on the server, the โ€œPHP fileโ€ receives the data that I send (typically a string), and executes the request using parameters sent via http.

Example:

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

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

ps all data uses JSON format

The problem is this: I always used the function (this works fine), but now all the methods are outdated, I can not find alternatives to the latest API methods.

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; 
+4
source share
2 answers

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(); } } } 
+1
source

Perhaps this is the time when you start using a volley. This is a great library and is designed to solve your problems.

I do not know anything about a volley. Well do not worry. Here is a great video to tell you what a salvo is capable of. It includes all the steps to include it in your project (although this is nothing more than a mention of the gradle dependency)

I also mention an 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); } } 

Source code (and tutorial) is available here .

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

0
source

Source: https://habr.com/ru/post/1244144/


All Articles