天天看點

Java工具類--通過HttpClient發送http請求

在寫網絡程式的時候,經常會有從網址擷取資料的需求,本文介紹一種Java發送http請求的工具–HttpClient。

HttpClient的介紹

      HttpClient最基本的功能就是執行http方法,執行http方法包括了一次或者幾次HTTP請求和相應的變化,通常也是通過HttpClient來處理的。隻要使用者提供一個request的對象,HttpClient就會将使用者的請求發送到目标伺服器上,并且傳回一個respone對象,如果沒有執行成功将抛出一個異常。通過文檔的介紹我們可以知道,發送HTTP請求一般可以分為以下步驟:

1.取得HttpClient對象
2.封裝http請求
3.執行http請求
4.處理結果
           

  其中可以發送的請求類型有GET, HEAD, POST, PUT, DELETE, TRACE 和 OPTIONS

官方文檔中的示例

//1.獲得一個httpclient對象
CloseableHttpClient httpclient = HttpClients.createDefault();
//2.生成一個get請求
HttpGet httpget = new HttpGet("http://localhost/");
//3.執行get請求并傳回結果
CloseableHttpResponse response = httpclient.execute(httpget);
try {
    //4.處理結果
} finally {
    response.close();
}
           

介紹一下最常用的HttpGet和HttpPost。 

RESTful提倡,通過HTTP請求對應的POST、GET、PUT、DELETE來完成對應的CRUD操作。 

是以本文介紹一下通過GET擷取資料和POST送出資料的實作方法。

發送HttpGet

先介紹發送HttpGet請求

    /**
     * 發送HttpGet請求
     * @param url
     * @return
     */
    public static String sendGet(String url) {
        //1.獲得一個httpclient對象
        CloseableHttpClient httpclient = HttpClients.createDefault();
        //2.生成一個get請求
        HttpGet httpget = new HttpGet(url);
        CloseableHttpResponse response = null;
        try {
            //3.執行get請求并傳回結果
            response = httpclient.execute(httpget);
        } catch (IOException e1) {
            e1.printStackTrace();
        }
        String result = null;
        try {
            //4.處理結果,這裡将結果傳回為字元串
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                result = EntityUtils.toString(entity);
            }
        } catch (ParseException | IOException e) {
            e.printStackTrace();
        } finally {
            try {
                response.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return result;
    }
           

發送HttpPost

發送HttpPost的方法和發送HttpGet很類似,隻是将請求類型給位HttpPost即可。 

代碼如下

/**
     * 發送不帶參數的HttpPost請求
     * @param url
     * @return
     */
    public static String sendPost(String url) {
        //1.獲得一個httpclient對象
        CloseableHttpClient httpclient = HttpClients.createDefault();
        //2.生成一個post請求
        HttpPost httppost = new HttpPost(url);
        CloseableHttpResponse response = null;
        try {
            //3.執行get請求并傳回結果
            response = httpclient.execute(httppost);
        } catch (IOException e) {
            e.printStackTrace();
        }
        //4.處理結果,這裡将結果傳回為字元串
        HttpEntity entity = response.getEntity();
        String result = null;
        try {
            result = EntityUtils.toString(entity);
        } catch (ParseException | IOException e) {
            e.printStackTrace();
        }
        return result;
    }
           

帶參數的HttpPost,發送帶參數的HttpPost

HttpClient通過UrlEncodedFormEntity,來送出帶參數的請求

将需要送出的參數放在map裡 

代碼如下

  /**
     * 發送HttpPost請求,參數為map
     * @param url
     * @param map
     * @return
     */
    public static String sendPost(String url, Map<String, String> map) {
        CloseableHttpClient httpclient = HttpClients.createDefault();
        List<NameValuePair> formparams = new ArrayList<NameValuePair>();
        for (Map.Entry<String, String> entry : map.entrySet()) {
            //給參數指派
            formparams.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
        }
        UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams, Consts.UTF_8);
        HttpPost httppost = new HttpPost(url);
        httppost.setEntity(entity);
        CloseableHttpResponse response = null;
        try {
            response = httpclient.execute(httppost);
        } catch (IOException e) {
            e.printStackTrace();
        }
        HttpEntity entity1 = response.getEntity();
        String result = null;
        try {
            result = EntityUtils.toString(entity1);
        } catch (ParseException | IOException e) {
            e.printStackTrace();
        }
        return result;
    }
           

完成代碼如下,用到的jar包有httpclient-4.5.1.jar,httpcore-4.4.3.jar,

依賴的jar有commons-logging-1.2.jar 

注意是Apache HttpClient,不是commons-httpclient

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
/**
 * @author GWCheng
 *
 */
public class HttpUtil {

    private static final CloseableHttpClient httpclient = HttpClients.createDefault();

    /**
     * 發送HttpGet請求
     * @param url
     * @return
     */
    public static String sendGet(String url) {

        HttpGet httpget = new HttpGet(url);
        CloseableHttpResponse response = null;
        try {
            response = httpclient.execute(httpget);
        } catch (IOException e1) {
            e1.printStackTrace();
        }
        String result = null;
        try {
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                result = EntityUtils.toString(entity);
            }
        } catch (ParseException | IOException e) {
            e.printStackTrace();
        } finally {
            try {
                response.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return result;
    }

    /**
     * 發送HttpPost請求,參數為map
     * @param url
     * @param map
     * @return
     */
    public static String sendPost(String url, Map<String, String> map) {
        List<NameValuePair> formparams = new ArrayList<NameValuePair>();
        for (Map.Entry<String, String> entry : map.entrySet()) {
            formparams.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
        }
        UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams, Consts.UTF_8);
        HttpPost httppost = new HttpPost(url);
        httppost.setEntity(entity);
        CloseableHttpResponse response = null;
        try {
            response = httpclient.execute(httppost);
        } catch (IOException e) {
            e.printStackTrace();
        }
        HttpEntity entity1 = response.getEntity();
        String result = null;
        try {
            result = EntityUtils.toString(entity1);
        } catch (ParseException | IOException e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 發送不帶參數的HttpPost請求
     * @param url
     * @return
     */
    public static String sendPost(String url) {
        HttpPost httppost = new HttpPost(url);
        CloseableHttpResponse response = null;
        try {
            response = httpclient.execute(httppost);
        } catch (IOException e) {
            e.printStackTrace();
        }
        HttpEntity entity = response.getEntity();
        String result = null;
        try {
            result = EntityUtils.toString(entity);
        } catch (ParseException | IOException e) {
            e.printStackTrace();
        }
        return result;
    }

}
           

測試用例

伺服器端代碼

@Controller
@RequestMapping("/test")
// /test/**
public class TestController {
    // /test/view post 送出資料,模拟表單
    @RequestMapping(value = "/view", method = RequestMethod.POST)
    public void viewTest(PrintWriter out, HttpServletResponse response, @RequestParam("param1") String param1,
            @RequestParam("param2") String param2) {
        response.setContentType("application/json;charset=UTF-8");
        Gson gson = new GsonBuilder().create();
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("param1", param1);
        map.put("param2", param2);
        System.out.println(gson.toJson(map));
        out.print(gson.toJson(map));
    }

    // /test/view?param1=aaa&param2=bbb get 
        @RequestMapping(value = "/view", method = RequestMethod.GET)
        public void viewTest3(PrintWriter out, HttpServletResponse response, @RequestParam("param1") String param1,
                @RequestParam("param2") String param2) {
            response.setContentType("application/json;charset=UTF-8");
            Gson gson = new GsonBuilder().create();
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("param1", param1);
            map.put("param2", param2);
            System.out.println(gson.toJson(map));
            out.print(gson.toJson(map));
        }

    // /test/view2/{courseId}
    @RequestMapping(value = "/view2/{param}", method = RequestMethod.GET)
    public void viewTest1(PrintWriter out, HttpServletResponse response, @PathVariable("param") String param) {
        response.setContentType("application/json;charset=UTF-8");
        Gson gson = new GsonBuilder().create();
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("param", param);
        out.print(gson.toJson(map));
    }

    // /test/view3
    @RequestMapping(value = "/view3", method = RequestMethod.POST)
    public void viewTest2(PrintWriter out, HttpServletResponse response) {
        response.setContentType("application/json;charset=UTF-8");
        Gson gson = new GsonBuilder().create();
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("status", "success");
        out.print(gson.toJson(map));
    }

}
           

測試代碼

public class HttpClientTest {

    @Test
    public void testGet() {
        //百度天氣的api
        //String url1 = "http://api.map.baidu.com/telematics/v3/weather?location=%E5%8C%97%E4%BA%AC&output=json&ak=W69oaDTCfuGwzNwmtVvgWfGH";
        String url1 = "http://localhost:8080/wechat/test/view2/你好世界";
        String result1 = HttpUtil.sendGet(url1);
        System.out.println(result1);
        //輸出{"param":"你好世界"}
    }
    @Test
    public void testPost() throws UnsupportedEncodingException{
        String url = "http://localhost:8080/wechat/test/view";
        Map<String,String> map = new HashMap<String,String>();
        map.put("param1", "你好世界");
        map.put("param2", "哈哈");
        String result = HttpUtil.sendPost(url, map);
        System.out.println(result);
        //輸出結果{"param1":"你好世界","param2":"哈哈"}

    }

    @Test
    public void testPost1() throws UnsupportedEncodingException{
        String url = "http://localhost:8080/wechat/test/view3";
        String result = HttpUtil.sendPost(url);
        System.out.println(result);
        //輸出結果{"status":"success"}

    }

}
           

建議通過HttpGet擷取資訊,HttpPost送出資訊,

而HttpGet擷取資訊時需要送出的參數一般會在url中展現,

或者以?傳參,或者在url中傳參,是以就沒寫HttpGet帶參數的。

也希望大家能遵循Http的設計原則,通過HttpGet, HttpPost, HttpPut, HttpDelete,

來實作擷取資料,送出資料,修改資料,和删除資料的方法。

---------------------

本文來自 GW_Cheng 的CSDN 部落格 ,全文位址請點選:https://blog.csdn.net/frankcheng5143/article/details/50070591

繼續閱讀