java进行http-get|post请求调用

java进行http-get|post请求调用

package com.dpzs.utils;

import java.io.IOException;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;

public class SendRequestUtil
{
    /**
     * 发送get请求信息
     * @param url 请求地址
     * @return
     */
    public static String sendRequest(String url){
        String resultString=null;
        CloseableHttpClient httpClient = null;  
        try {  
            HttpClientBuilder httpClientBuilder=HttpClientBuilder.create();
            httpClient = httpClientBuilder.build();  
            HttpGet get=new HttpGet(url);
            CloseableHttpResponse response=httpClient.execute(get);
            HttpEntity entity=response.getEntity();
            if(entity!=null){
                resultString = EntityUtils.toString(entity,"utf-8");  
            }
        } catch (Exception e) {
            e.printStackTrace();
            return e.getMessage();
        } finally {  
            try {
                httpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }  
        }
        return resultString;
    }
    
    
    /**
     * 发送post请求信息
     * @param url 请求地址
     * @return
     */
    public static String sendRequestByPost(String url,String param){
        String resultString=null;
        CloseableHttpClient httpClient = null;
        try {
//            HttpClientBuilder httpClientBuilder=HttpClientBuilder.create();
            httpClient = HttpClients.createDefault();
//            se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,"application/json"));
            HttpPost post=new HttpPost(url);
            post.addHeader("Content-Type","application/json");
            //参数设置
            StringEntity se=new StringEntity(param,"utf-8");
            post.setEntity(se);
            CloseableHttpResponse response=httpClient.execute(post);
            HttpEntity entity=response.getEntity();
            if(entity!=null){
                resultString = EntityUtils.toString(entity,"utf-8");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return e.getMessage();
        } finally {
            try {
                httpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return resultString;
    }
}

posted @ 2021-07-11 13:58  幸运刘  阅读(360)  评论(0)    收藏  举报