配置

<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpmime</artifactId>
    <version>4.3.2</version>
</dependency>

Get请求

/**
 * 发送Get请求
 *
 * @param url    请求的接口
 * @param token  用于验证身份,登录时设为null即可
 * @param params 用于传递文本信息
 * @return 请求得到的文本
 */
public static String get(String url, String token, Map<String, String> params) {
    CloseableHttpClient httpclient = HttpClients.createDefault();
    try {
        //拼接url
        if (params != null) {
            StringBuilder urlBuilder = new StringBuilder(url + "?");
            for (Map.Entry<String, String> param : params.entrySet()) {
                urlBuilder.append(param.getKey()).append("=").append(param.getValue()).append("&");
            }
            url = urlBuilder.toString();
            url = url.substring(0, url.length() - 1);
        }

        System.out.println(url);
        HttpGet httpGet = new HttpGet(url);

        //设置token
        httpGet.setHeader("Token", token);

        //System.out.println("executing request " + httpGet.getRequestLine());
        //建立连接
        try (CloseableHttpResponse response = httpclient.execute(httpGet)) {
            //System.out.println("----------------------------------------");
            //System.out.println(response.getStatusLine());
            //判断连接是否成功
            if (response.getStatusLine().getStatusCode() != 200) {
                return "";
            }
            HttpEntity resEntity = response.getEntity();
            if (resEntity != null) {
                String answer = EntityUtils.toString(resEntity);
                //System.out.println("返回数据: " + answer);
                EntityUtils.consume(resEntity);
                return answer;
            }
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            if (httpclient != null) httpclient.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return "";
}

Post请求

  • 只需传文本数据
/**
 * 发送post请求
 *
 * @param url    请求接口
 * @param token  token,用于验证身份
 * @param params 用于传递文本信息,Map<String,String>形式
 * @return 返回请求得到的文本
 */
public static String post(String url, String token, Map<String, String> params) {
    //初始化连接
    CloseableHttpClient httpClient = HttpClients.createDefault();
    //声明post请求
    HttpPost post = new HttpPost(url);

    List<NameValuePair> pairs = new ArrayList<>();
    //建造一个装有数据的实体对象
    HttpEntity entity = null;
    try {
        //填充参数
        if (params != null && params.size() > 0) {
            for (Map.Entry<String, String> param : params.entrySet()) {
                pairs.add(new BasicNameValuePair(param.getKey(), param.getValue()));
            }
        }
        entity = new UrlEncodedFormEntity(pairs, "UTF-8");
    } catch (Exception e) {
        e.printStackTrace();
    }

    //为post装配数据
    post.setEntity(entity);
    //设置token
    post.addHeader("Token", token);
    CloseableHttpResponse response = null;
    try {
        response = httpClient.execute(post);
        if (response.getStatusLine().getStatusCode() != 200) {
            System.out.println("请求错误: " + response.getStatusLine().getReasonPhrase());
            return "";
        }
        HttpEntity responseEntity = response.getEntity();
        if (responseEntity != null) {
            String result = EntityUtils.toString(responseEntity, "UTF-8");
            EntityUtils.consume(responseEntity);
            return result;
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            if (httpClient != null) {
                httpClient.close();
            }
            if (response != null) {
                response.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return "";
}
  • 需要上传图片的post方法
/**
 * 发送post请求
 *
 * @param url    请求接口
 * @param token  token,用于验证身份
 * @param params 用于传递文本信息,Map<String,String>形式
 * @param files  用于传递文件,Map<String, File>形式
 * @return 返回请求得到的文本
 */
public String post(String url, String token, Map<String, String> params, Map<String, File> files) {
    CloseableHttpClient httpClient = HttpClients.createDefault();
    try {
        HttpPost post = new HttpPost(url);
        //装配请求参数
        MultipartEntityBuilder builder = MultipartEntityBuilder.create();
        if (files != null) {
            for (Map.Entry<String, File> file : files.entrySet()) {
                builder.addPart(file.getKey(), new FileBody(file.getValue()));
            }
        }
        if (params != null) {
            for (Map.Entry<String, String> param : params.entrySet()) {
                System.out.println(param.getKey());
                //builder.addPart(param.getKey(), new StringBody(param.getValue(), ContentType.APPLICATION_JSON));
                builder.addTextBody(param.getKey(), param.getValue(), ContentType.APPLICATION_JSON);
            }
        }

        //创建请求的entity
        HttpEntity requestEntity = builder.build();

        post.setEntity(requestEntity);
        //设置token
        post.setHeader("Token", token);

        System.out.println("executing request " + post.getRequestLine());

        try (CloseableHttpResponse response = httpClient.execute(post)) {
            //System.out.println("----------------------------------------");
            //System.out.println(response.getStatusLine());
            //判断连接是否成功
            if (response.getStatusLine().getStatusCode() != 200) {
                System.out.println("请求失败: " + response.getStatusLine());
                return ;
            }
            HttpEntity responseEntity = response.getEntity();
            if (responseEntity != null) {
                String answer = EntityUtils.toString(responseEntity);
                EntityUtils.consume(responseEntity);
                //System.out.println("返回数据: " + answer);
                return answer;
            }
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            if (httpClient != null) httpClient.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return null;
}

测试方法

//此main方法用于测试作为样例
public static void main(String[] args) {
    String url = "http://localhost:8080/shop/addGood";
    String token = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJleHAiOjE1ODY4MzcxNTAsInVzZXJJZCI6IjEwIn0.Z66KTYG25voU5pRxQAHx5DVaQcbytj45w52427kzX1U";

    Map<String, String> params = new HashMap<>();
    params.put("goodName", "dwfe");

    File file = new File("F:\\others\\Pictures\\MY\\24.jpg");
    Map<String, File> files = new HashMap<>();
    files.put("pic", file);

//        String ans = new Test2().get(url, token, params);
    String ans = new Test2().post(url, token, params, files);
    System.out.println("getAnswer:  " + ans);
}

另一种Post/Get请求

public static String post(String generalUrl, String params)
        throws IOException {
    URL url = new URL(generalUrl);
    // 打开和URL之间的连接
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    connection.setRequestMethod("POST");//可改为GET
    // 设置通用的请求属性
    connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
    connection.setRequestProperty("Connection", "Keep-Alive");
    connection.setUseCaches(false);
    connection.setDoOutput(true);
    connection.setDoInput(true);

    // 得到请求的输出流对象
    DataOutputStream out = new DataOutputStream(connection.getOutputStream());
    out.write(params.getBytes("UTF-8"));
    out.flush();
    out.close();

    // 建立实际的连接
    connection.connect();
    // 获取所有响应头字段
    Map<String, List<String>> headers = connection.getHeaderFields();
    // 遍历所有的响应头字段
    for (String key : headers.keySet()) {
        System.err.println(key + "--->" + headers.get(key));
    }
    // 定义 BufferedReader输入流来读取URL的响应
    BufferedReader in = null;
    in = new BufferedReader(
            new InputStreamReader(connection.getInputStream(), "UTF-8"));
    String result = "";
    String getLine;
    while ((getLine = in.readLine()) != null) {
        result += getLine;
    }
    in.close();
    System.err.println("result:" + result);
    return result;
}
  • 上述方法的测试
public static void main(String[] args) throws Exception {
    String url = BaseValue.load;
    String ans = ttppUtil.post(url, "userName=tom&password=123");
    System.out.println(ans);
}

hhhhh