Android——HttpClient(get&post)

Keywords: encoding SDK network Android

To avoid the tedious configuration of HttpUrlConnection, SDK provides HttpClient. The GET method link is encapsulated into the HttpGet class, and the POST method is encapsulated into the HttpPost class.

get connection

The steps of get connection are as follows:
1. New url
2. New get request
3. New Http Client
4. Use client to execute requests
5. Processing the returned results

post connection

The difference between a post connection and a get connection is the passing of parameters, which requires the NameValuePair class.
The steps of post connection are as follows:
1. New HttpPost type requests
2. New data structure for saving parameters
3. Setting the encoding mode for parameters
4. Add parameters to the request
5. New Http Client
6. Use client to execute requests
7. Processing response

HttpClient instance

Note: Network request operation after Android 4.0 must not run in the main thread. Therefore, get and post methods are invoked by the new build thread. The data from the secondary thread is transmitted to the main thread through handler receiving message.
In addition, INTERNET permissions need to be added to the registration file.

public class MainActivity extends Activity {
    TextView tv;
    Button get;
    Button post;
    Handler handler;//Processor receives messages

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

        tv=(TextView)findViewById(R.id.textView2);
        get=(Button)findViewById(R.id.get);
        post=(Button)findViewById(R.id.post);
        //Accept the message and display it
         handler = new Handler() {  

                public void handleMessage(Message msg) {  
                    switch (msg.what) { //msg.what is a message label that identifies each message 
                    case 1:  
                        //Here you can do UI operations  
                        //String mandatory conversion of msg.obj  
                        String string=(String)msg.obj;  
                        tv.setText(string);  
                        break;  
                    case 2:
                        String string2=(String)msg.obj;  
                        tv.setText(string2);  
                        break;
                    default:  
                        break;  
                    }  
                }  

            };  
        OnClickListener listener=new OnClickListener() {

            @Override
            public void onClick(View v) {
                // Method stub for TODO automatic generation
                int id=v.getId();
                if(id==R.id.get){
                    //New thread invocation method
                    Thread thread=new Thread(new Runnable() {

                        @Override
                        public void run() {
                            // Method stub for TODO automatic generation
                            doGet();
                        }
                    });
                    thread.start();
                }
                else
                {
                  Thread thread=new Thread(new Runnable() {

                        @Override
                        public void run() {
                            // Method stub for TODO automatic generation
                            doPost();
                        }
                    });
                    thread.start();

                }
            }
        };
        get.setOnClickListener(listener);
        post.setOnClickListener(listener);
    }

    public void doGet(){
        String url="http://www.baidu.com";
        //New get request
        HttpGet httpRequest=new HttpGet(url);
        //New Http Client
        HttpClient httpClient=new DefaultHttpClient();
        try
        {
            //Execute the request and return the result
            HttpResponse httpResponse=httpClient.execute(httpRequest);
            //Judging the state of the result
            if(httpResponse.getStatusLine().getStatusCode()==HttpStatus.SC_OK)
            {
                //Get results
                String result=EntityUtils.toString(httpResponse.getEntity());
                //send message
                Message message = new Message();  
                message.what = 1;  
                message.obj=result;  
                handler.sendMessage(message); 
            //  tv.setText(result);
            }
            else
            {
                return;
            }
        }
        catch(ClientProtocolException e)
        {
            e.printStackTrace();
        }
        catch (IOException e) {
            // TODO: handle exception
            e.printStackTrace();
        }   
    }
    public void doPost(){
        String url="http://www.baidu.com";
        //New post type request
        HttpPost httpRequest=new HttpPost(url);
        //New Data Structures for Transferring Parameters
        List<NameValuePair> params=new ArrayList<NameValuePair>();
        //New key-value pairs
        BasicNameValuePair pair1=new BasicNameValuePair("param", "AaBb");
        params.add(pair1);
        try{
            //Setting the encoding mode
            HttpEntity entity=new UrlEncodedFormEntity(params, HTTP.UTF_8);
            httpRequest.setEntity(entity);
            //New http client
            HttpClient client=new DefaultHttpClient();
            //Response to execution request
            HttpResponse httpResponse=client.execute(httpRequest);
            if(httpResponse.getStatusLine().getStatusCode()==HttpStatus.SC_OK);
            {
                String result=EntityUtils.toString(httpResponse.getEntity());
                Message message=new Message();
                message.what=2;
                message.obj=result;
                handler.sendMessage(message);
            }
        }
        catch (UnsupportedEncodingException e)
        {
            e.printStackTrace();
        }
        catch (ClientProtocolException e) {
            // TODO: handle exception
            e.printStackTrace();
        }
        catch (IOException e) {
            // TODO: handle exception
            e.printStackTrace();
        }
    }
}


get mode


post mode

Posted by webwalker00 on Thu, 14 Feb 2019 11:03:18 -0800