Java发起Http请求

Java发起Http请求

  • 首先引入pom文件
		<!--    Http请求    -->
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.5.5</version>
        </dependency>
        <dependency>
            <groupId>commons-httpclient</groupId>
            <artifactId>commons-httpclient</artifactId>
            <version>3.1</version>
        </dependency>
  • 编写工具类(HttpUtils)
public class HttpUtils {

    public String getUrl(String url, Map<String, String> paramsMap) throws Exception {
        url = url.trim();
        if (paramsMap != null && !paramsMap.isEmpty()) {
            if (!url.contains("?")) {
                url += "?";
            }
            StringBuilder urlBuilder = new StringBuilder(url);
            for (String key : paramsMap.keySet()) {
                urlBuilder.append(key).append("=").append(paramsMap.get(key)).append("&");
            }
            url = urlBuilder.toString();
        }
        if ("&".equals(url.substring(url.length() - 1))) {
            return getUrl(url.substring(0, url.length() - 1));
        }
        return getUrl(url);
    }

    public String getUrl(String url) throws Exception {
        GetMethod getMethod = new GetMethod(URIUtil.encodeQuery(url));
        getMethod.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");

        HttpClient client = new HttpClient();
        int statusCode = client.executeMethod(getMethod);
        if (statusCode != HttpStatus.SC_OK) {
            System.err.println("Method failed: " + getMethod.getStatusLine());
        }
        //从请求返回体获得编码格式
        String responseCharSet = getMethod.getResponseCharSet();

        // 读取内容
        BufferedReader bufferedInputStream = new BufferedReader(new InputStreamReader(getMethod.getResponseBodyAsStream(), responseCharSet));
        // 处理内容
        StringBuilder stringBuffer = new StringBuilder();
        String str;
        while ((str = bufferedInputStream.readLine()) != null) {
            stringBuffer.append(str);
        }
        return stringBuffer.toString();
    }


    public String postUrl(String url, Map<String, String> paramsMap) throws IOException {
        PostMethod postMethod = new PostMethod(url);
        postMethod.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "UTF-8");
        if (paramsMap == null || paramsMap.isEmpty()) {
            paramsMap = new HashMap<>();
        }
        for (String key : paramsMap.keySet()) {
            postMethod.addParameter(key, MapUtils.getString(paramsMap, key));
        }
        HttpClient httpClient = new HttpClient();
        int statusCode = httpClient.executeMethod(postMethod);
        if (statusCode != HttpStatus.SC_OK) {
            return null;
        }
        // 读取内容
        BufferedReader bufferedInputStream = new BufferedReader(new InputStreamReader(postMethod.getResponseBodyAsStream()));
        // 处理内容
        StringBuilder stringBuffer = new StringBuilder();
        String str;
        while ((str = bufferedInputStream.readLine()) != null) {
            stringBuffer.append(str);
        }
        return stringBuffer.toString();
    }

    public String postUrl(String url, String body) {
        try {
            PostMethod postMethod = new PostMethod(url);
            RequestEntity requestEntity = new StringRequestEntity(body, "application/json", "UTF-8");
            postMethod.setRequestEntity(requestEntity);
            HttpClient httpClient = new HttpClient();
        int statusCode = httpClient.executeMethod(postMethod);
        if (statusCode != HttpStatus.SC_OK) {
            return null;
        }
        // 读取内容
        BufferedReader bufferedInputStream = new BufferedReader(new InputStreamReader(postMethod.getResponseBodyAsStream()));
        // 处理内容
        StringBuilder stringBuffer = new StringBuilder();
        String str;
        while ((str = bufferedInputStream.readLine()) != null) {
            stringBuffer.append(str);
        }
            return stringBuffer.toString();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

}
  • 示例(Get)
		//请求
		@GetMapping("/http/{id}")
	    public void testGetHttp(@PathVariable("id") String id, @ModelAttribute TestGetBody testGetBody) {

  		}

		//发起请求
		HashMap<String, String> param = new HashMap<>();
        param.put("name", "张三");
        param.put("age", "23");
        String url = httpUtils.getUrl("http://IP:端口/http/123456", param);
        //或
        String url = httpUtils.getUrl("http://IP:端口/http/123456?name=张三&age=23");
  • for循环N输入N.for即可
	//请求
	@PostMapping("/http")
    public void testPostHttp(@RequestBody TestGetBody testGetBody) {
    
    }
	
	//发起请求
	String body = "{\"name\":\"张三\",\"age\":1}";
    String url = httpUtils.postUrl("http://IP:端口/http", body);
	//请求
	@PostMapping("/http")
    public void testPostHttp(@RequestParam("name") String name,
                             @RequestParam("age") Integer age) {

    }
	
	//发起请求
	HashMap<String, String> param = new HashMap<>();
    param.put("name", "张三");
    param.put("age", "23");
    String url = httpUtils.postUrl("http://IP:端口/http", param);
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值