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

那年仲夏 提交于 2019-12-05 12:42:46

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();

      }

     }

    }

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)

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!

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!