Android發送網絡請求(post,get)工具類

     前幾天,由於開發需求,研究了一下各種HTTP發送post,get方法,封裝成工具類,記錄一下,供後續用到方便查看。

package com.fh.loginauth.util;

import android.content.Context;
import android.util.Log;
import android.widget.Toast;

import com.fh.loginauth.HttpCallbackListener;
import com.fh.loginauth.MainActivity;
import com.fh.loginauth.MyCallback;
import com.zhy.http.okhttp.OkHttpUtils;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import javax.net.ssl.HttpsURLConnection;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class HttpUtil {

    private static String urlAddress = "http://10.96.156.89:6060/aaa/index.jsp";

    /**
     * 發送HTTP請求
     * @param address 地址
     * @param listener 回調
     */
    public static void sendHttpRequest(final String address, final
        HttpCallbackListener listener) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                //               HttpsURLConnection connection = null;
                HttpURLConnection connection = null;
                try {
                    URL url = new URL(address);
                    //                   connection = (HttpsURLConnection) url.openConnection();
                    connection = (HttpURLConnection) url.openConnection();
                    connection.setRequestMethod("GET");
                    //設置請求報文頭,設定請求數據類型
//                    connection.setRequestProperty("Content-Type",
//                            "application/json");
                    connection.setConnectTimeout(8000);
                    connection.setReadTimeout(8000);
                    connection.setDoInput(true);
                    connection.setDoOutput(true);
                    InputStream in = connection.getInputStream();
                    BufferedReader reader = new BufferedReader(new InputStreamReader(in));
                    StringBuilder response = new StringBuilder();
                    String line;
                    while ((line = reader.readLine()) != null) {
                        response.append(line);
                    }
                    if (listener != null) {
                        //回調onFinish()方法
                        listener.onFinish(response.toString());
                    }
                } catch (Exception e) {
                    if (listener != null) {
                        listener.onError(e);
                    }
                } finally {
                    if (connection != null) {
                        connection.disconnect();
                    }
                }
            }
        }).start();
    }

    /**
     * 發送Http post請求
     * @param urlAddress
     */
    public static void sendRequestWithHttpURLConnection(final String urlAddress){
        new Thread(new Runnable() {
            @Override
            public void run() {
                HttpURLConnection connection = null;
                BufferedReader reader = null;
                try {
                    URL url = new URL(urlAddress);
                    connection = (HttpURLConnection) url.openConnection();
//                    connection.setRequestMethod("GET");
                    //發送POST請求
                    connection.setRequestMethod("POST");
                    //設置請求報文頭,設定請求數據類型
                    connection.setRequestProperty("Content-Type",
                            "application/json");
                    DataOutputStream out = new DataOutputStream(connection.getOutputStream());
                    out.writeBytes("identity=C84029B714D2");
                    connection.setConnectTimeout(8000);
                    connection.setReadTimeout(8000);
                    InputStream in = connection.getInputStream();
                    //對獲取到的地輸入流進行讀取
                    reader = new BufferedReader(new InputStreamReader(in));
                    StringBuilder responses = new StringBuilder();
                    String line;
                    while ((line = reader.readLine())!= null){
                        responses.append(line);
                    }
                    Log.d("HttpUtil", "--responses--"+responses.toString());
                } catch (Exception e) {
                    e.printStackTrace();
                }finally {
                    if ( reader != null){
                        try {
                            reader.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    if (connection != null){
                        connection.disconnect();
                    }
                }
            }
        }).start();
    }

    /**
     * 發送OK HTTP請求
     * @param address
     * @param callback
     */
    public static void sendOkHttpRequest(String address, okhttp3.Callback callback) {
        OkHttpClient client = new OkHttpClient();

        Request request = new Request.Builder()
                .url(address)
                .build();
        client.newCall(request).enqueue(callback);
    }

    //doGet
    public static void doGet(String s) {
        final String getUrl = urlAddress + s;
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    URL url = new URL(getUrl);
                    try {
                        HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
                        httpURLConnection.connect();
                        if (httpURLConnection.getResponseCode() == httpURLConnection.HTTP_OK) {
                            InputStream inputStream = httpURLConnection.getInputStream();
                            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
                            StringBuffer stringBuffer = new StringBuffer();
                            String readLine = "";
                            while ((readLine = bufferedReader.readLine()) != null) {
                                stringBuffer.append(readLine);
                            }
                            inputStream.close();
                            bufferedReader.close();
                            httpURLConnection.disconnect();
                            Log.d("TAG", stringBuffer.toString());
                        } else {
                            Log.d("TAG", "fail");
                            Log.d("TAG", "---httpURLConnection.getResponseCode()-----"+
                                    httpURLConnection.getResponseCode());
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                } catch (MalformedURLException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    /**
     * 以OK HTTP發送post請求
     * @param url
     * @param object
     */
    public void postString(String url, JSONObject object) {
//        JSONObject map = new JSONObject();
//        try {
//            map.put("identity", "C84029B714D2");
//        } catch (JSONException e) {
//            e.printStackTrace();
//        }
        OkHttpUtils.postString().url(url)
                .content(object.toString())
                .mediaType(MediaType.parse("application/json; charset=utf-8"))
                .build().execute(new MyCallback());
    }

    /**
     * 獲取post請求的結果,注意此爲耗時操作
     */
    public static void sendPostOkHttpRequest(String address, JSONObject object, okhttp3.Callback callback) {
        try {
            OkHttpClient client = new OkHttpClient();
            MediaType mediaType = MediaType.parse("application/json");
            String requestBody = object.toString();
            Request request = new Request.Builder()
                    .url(address)
                    .post(RequestBody.create(mediaType, requestBody))
                    .build();
            client.newCall(request).enqueue(callback);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    private void doPost(){
        OkHttpClient client = new OkHttpClient.Builder()
                .build();
        Request request = new Request.Builder()
                .url("http://10.96.156.89:6060/aaa/services/rest/V2/AAA/AutoConfig")
                .post(RequestBody.create(MediaType.parse("application/json"), "aaa".getBytes()))
                .build();
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.d("HttpUtil", "------"+e);
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                Log.d("HttpUtil", "---res>>---"+response.body().string());
                String resData = response.body().string();
                try {
                    Toast.makeText(MyApplication.getContext(), "---onResponse Success---",       Toast.LENGTH_LONG).show();
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        });

    }

}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章