Android HTTP mode request network

Keywords: Java Apache Android network

There are many ways to use Http to access the network, but the most common way is POST and GET. The project is just useful, so I wrote a tool class for later use.
Generate a construction parameter with handler in HttpUtil class. The reason to generate a construction parameter with handler is that after Android 4.0, when requesting network in activity, it cannot be placed in the main thread. Therefore, after getting the result through the tool class, the result is returned to the interface through the handler.
Code above:

package com.szh.speechdemo.ui;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;

/**
 * http Tool class, access method is post or get
 * @author gh
 */
public class HttpUtil {

    private Handler mHandler;

    public HttpUtil(Handler handler) {
        mHandler = handler;
    }

    public void getData(Map<String, Object> param, String type, String url) {
        try {
            if ("get".equals(type)) {
                try {
                    getDataByGet(url);
                } catch (Throwable e) {
                    e.printStackTrace();
                }
            } else {
                getDataByPost(param, url);
            }
        } catch (Exception e) {

        }
    }

    /**
     * Get network data by post request
     * 
     * @param param
     * @param url
     */
    private void getDataByPost(final Map<String, Object> param, final String url) {
        new Thread(new Runnable() {

            @Override
            public void run() {
                String data = "";
                Message message = new Message();
                Bundle bundle = new Bundle();
                try{
                    HttpClient httpClient = new DefaultHttpClient();
                    HttpPost httpPost = new HttpPost(url);
                    List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>();
                    if(param != null){
                        for(Map.Entry<String, Object> entry :param.entrySet()){
                            nameValuePair.add(new BasicNameValuePair(entry.getKey(), entry.getValue().toString()));
                        }
                        httpPost.setEntity(new UrlEncodedFormEntity(nameValuePair, "utf-8"));
                        // Perform the operation and get the result
                        HttpResponse response = httpClient.execute(httpPost);
                        // Get result entity
                        HttpEntity entity = (HttpEntity) response.getEntity();
                        if(entity != null){
                            data = EntityUtils.toString(entity,"utf-8");
                        }
                        entity.consumeContent();
                        bundle.putString("data", data);
                    }
                }catch(Exception e){
                    e.printStackTrace();
                    data = "Server connection exception";
                    bundle.putString("data", data);
                }
                message.setData(bundle);
                mHandler.sendMessage(message);
            }
        }).start();
    }

    /**
     * Get network data by get request
     * 
     * @param url
     */
    private void getDataByGet(final String url_path) throws Throwable{

        new Thread(new Runnable() {
            @Override
            public void run() {
                String jsonString = "";
                Message message =new Message();
                Bundle bundle = new Bundle();
                URL url = null;
                try{
                    url = new URL(url_path);
                    HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
                    httpURLConnection.setConnectTimeout(6000);
                    httpURLConnection.setRequestMethod("GET");
                    // Get data from server
                    httpURLConnection.setDoOutput(true);
                    if(httpURLConnection.getResponseCode() == HttpURLConnection.HTTP_OK){
                        // Indicates that the connection to the server is successful
                        jsonString = ChangeInputStream(httpURLConnection.getInputStream(),"utf-8");
                        // Deliver the message to the main interface and return the verification result
                        bundle.putString("data",jsonString);
                    } else {
                        jsonString = "Failed to connect to server";
                        bundle.putString("data", jsonString);
                    }
                }catch(Exception e){
                    jsonString = "Abnormal connection to server";
                    bundle.putString("data", jsonString);
                }
                message.setData(bundle);
                mHandler.sendMessage(message);
            }
        }).start();
    }

    /**
     * The obtained data results are transformed into json
     * @param inputStream
     * @param string
     * @return
     */
    protected String ChangeInputStream(InputStream inputStream, String encode) {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        byte[] data = new byte[1024];
        int len = 0;
        String jsonString = "";
        if(inputStream != null){
            try{
                while((len = inputStream.read(data)) != -1){
                    outputStream.write(data, 0, len);
                }
                jsonString = new String(outputStream.toByteArray(),encode);
            }catch(Exception e){
                e.printStackTrace();
            }
        }
        return jsonString;
    }

}

As you can see from the code, there are POST and GET requests. As for specific usage, for example:

package com.szh.speechdemo.activity;

import java.util.HashMap;
import java.util.Map;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import com.szh.speechdemo.ui.HttpUtil;

public class HttpRequestTest extends Activity{

    private Handler mHandler = new Handler(){
        public void handleMessage(android.os.Message msg) {
            String data = msg.getData().getString("data");
        };
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        String url = "Write your own request path";
        // Create httputil object
        HttpUtil httpUtil = new HttpUtil(mHandler);
        Map<String ,Object> map = new HashMap<String,Object>();
        map.put("id","");
        // Get data. If it is a get request method, the map parameter can be null
        httpUtil.getData(map, "post", url);
    }
}

Posted by devassocx on Thu, 16 Apr 2020 09:04:45 -0700