java 发送 http 请求 , 发送文件 或者 json 数据

java 发送 http 请求

  • pom依赖
  • java 发送 http 无参 get 请求
  • java 发送 http 文件 post
  • java 发送 http json 参数 Post请求

java 发送 http请求后, 返回值 为 json 串, 点击查看处理json串

pom依赖

<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpcore</artifactId>
    <version>4.4.13</version>
</dependency>
<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
    <version>4.5.12</version>
</dependency>
<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpmime</artifactId>
    <version>4.5.12</version>
</dependency>
<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
</dependency>

java 发送 http 无参 get 请求

//url 为 http 地址
public static String doGet(String url) {
    CloseableHttpClient httpClient = null;
    CloseableHttpResponse response = null;
    String result = "";
    try {
        // 通过址默认配置创建一个httpClient实例
        httpClient = HttpClients.createDefault();
        // 创建httpGet远程连接实例
        HttpGet httpGet = new HttpGet(url);
        // 设置配置请求参数
        RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(35000)// 连接主机服务超时时间
                .setConnectionRequestTimeout(35000)// 请求超时时间
                .setSocketTimeout(60000)// 数据读取超时时间
                .build();
        // 为httpGet实例设置配置
        httpGet.setConfig(requestConfig);
        // 执行get请求得到返回对象
        response = httpClient.execute(httpGet);
        // 通过返回对象获取返回数据
        HttpEntity entity = response.getEntity();
        // 通过EntityUtils中的toString方法将结果转换为字符串
        result = EntityUtils.toString(entity);
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        // 关闭资源
        if (null != response) {
            try {
                response.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (null != httpClient) {
            try {
                httpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    return result;
}

java 发送 http 文件 post

请求通过httpClient上传文件

/**
 * 通过httpClient上传文件
 * @param fileName
 * @param path
 * @return 外部域名的返回值
 */
public static String UploadFileByHttpClient(String fileName,String path, String url, String token) {

    String result = "";
    CloseableHttpClient httpClient = HttpClients.createDefault();
    CloseableHttpResponse response = null;
    try {
        HttpPost httpPost = new HttpPost(url);
        //HttpMultipartMode.RFC6532参数的设定是为避免文件名为中文时乱码
        MultipartEntityBuilder builder = MultipartEntityBuilder.create().setMode(HttpMultipartMode.RFC6532);
        httpPost.addHeader("header1", "zip");//头部放文件上传的head可自定义
        httpPost.setHeader("dist_token", token);

        File file = new File(path+fileName); //上传文件的路径
        builder.addBinaryBody("file", file, ContentType.MULTIPART_FORM_DATA, fileName);
        //builder.addTextBody("params1", "json");//其余参数,可自定义
        //builder.addTextBody("params2", "2");
        HttpEntity entity = builder.build();
        httpPost.setEntity(entity);
        response = httpClient.execute(httpPost);// 执行提交
        HttpEntity responseEntity = response.getEntity();//接收调用外部接口返回的内容
        // 通过EntityUtils中的toString方法将结果转换为字符串
        result = EntityUtils.toString(responseEntity);

    }catch(Exception e) {
        logger.error("上传文件失败:",e);
    }finally {//处理结束后关闭httpclient的链接
        try {
            if(httpClient != null){
                httpClient.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return result;
}

java 发送 http json 参数 Post请求

public static String doPostJson(String url,String json) throws IOException {
    // 创建连接池
    CloseableHttpClient httpClient = HttpClients.createDefault();
    // ResponseHandler responseHandler = new BasicResponseHandler();

    // 声明呀一个字符串用来存储response
    String result;
    // 创建httppost对象
    HttpPost httpPost = new HttpPost(url);
    // 给httppost对象设置json格式的参数
    StringEntity httpEntity = new StringEntity(json,"utf-8");
    // 设置请求格式
    httpPost.setHeader("Content-type","application/json");
    // 传参
    httpPost.setEntity(httpEntity);
    // 发送请求,并获取返回值
    CloseableHttpResponse response = httpClient.execute(httpPost);
    try {
        // 通过返回对象获取返回数据
        HttpEntity entity = response.getEntity();
        // 通过EntityUtils中的toString方法将结果转换为字符串
        result = EntityUtils.toString(entity);
        return result;

    } catch (Exception e) {
        e.printStackTrace();
    }finally {
        // 关闭资源
        if (null != response) {
            try {
                response.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (null != httpClient) {
            try {
                httpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    return "error";
}

你可能感兴趣的:(java,http)