Java实现Http请求的常用方式-程序员宅基地

转载 https://www.cnblogs.com/sinosoft/p/10556993.html

一、使用Java自带的java.io和java.net包。

  实现方式如下:

 

public class HttpClient {     //1、doGet方法 

    public static String doGet(String httpurl) {

        HttpURLConnection connection = null;

        InputStream is = null;

        BufferedReader br = null;

        String result = null;// 返回结果字符串

        try {

            // 创建远程url连接对象

            URL url = new URL(httpurl);

            // 通过远程url连接对象打开一个连接,强转成httpURLConnection类

            connection = (HttpURLConnection) url.openConnection();

            // 设置连接方式:get

            connection.setRequestMethod("GET");

            // 设置连接主机服务器的超时时间:15000毫秒

            connection.setConnectTimeout(15000);

            // 设置读取远程返回的数据时间:60000毫秒

            connection.setReadTimeout(60000);

            // 发送请求

            connection.connect();

            // 通过connection连接,获取输入流

            if (connection.getResponseCode() == 200) {

                is = connection.getInputStream();

                // 封装输入流is,并指定字符集

                br = new BufferedReader(new InputStreamReader(is, "UTF-8"));

                // 存放数据

                StringBuffer sbf = new StringBuffer();

                String temp = null;

                while ((temp = br.readLine()) != null) {

                    sbf.append(temp);

                    sbf.append("\r\n");

                }

                result = sbf.toString();

            }

        catch (MalformedURLException e) {

            e.printStackTrace();

        catch (IOException e) {

            e.printStackTrace();

        finally {

            // 关闭资源

            if (null != br) {

                try {

                    br.close();

                catch (IOException e) {

                    e.printStackTrace();

                }

            }

 

            if (null != is) {

                try {

                    is.close();

                catch (IOException e) {

                    e.printStackTrace();

                }

            }

 

            connection.disconnect();// 关闭远程连接

        }

 

        return result;

    }

     //2、doPost方法

    public static String doPost(String httpUrl, String param) {

 

        HttpURLConnection connection = null;

        InputStream is = null;

        OutputStream os = null;

        BufferedReader br = null;

        String result = null;

        try {

            URL url = new URL(httpUrl);

            // 通过远程url连接对象打开连接

            connection = (HttpURLConnection) url.openConnection();

            // 设置连接请求方式

            connection.setRequestMethod("POST");

            // 设置连接主机服务器超时时间:15000毫秒

            connection.setConnectTimeout(150000);

            // 设置读取主机服务器返回数据超时时间:60000毫秒

            connection.setReadTimeout(600000);

 

            // 默认值为:false,当向远程服务器传送数据/写数据时,需要设置为true

            connection.setDoOutput(true);

            // 默认值为:true,当前向远程服务读取数据时,设置为true,该参数可有可无

            connection.setDoInput(true);

            // 设置传入参数的格式:请求参数应该是 name1=value1&name2=value2 的形式。

            connection.setRequestProperty("Content-Type",

                    "application/x-www-form-urlencoded");

            // 设置鉴权信息:Authorization: Bearer da3efcbf-0845-4fe3-8aba-ee040be542c0

            connection.setRequestProperty("Authorization",

                    "Bearer da3efcbf-0845-4fe3-8aba-ee040be542c0");

            // 通过连接对象获取一个输出流

            os = connection.getOutputStream();

            // 通过输出流对象将参数写出去/传输出去,它是通过字节数组写出的

            os.write(param.getBytes());

            // 通过连接对象获取一个输入流,向远程读取

            if (connection.getResponseCode() == 200) {

                is = connection.getInputStream();

                // 对输入流对象进行包装:charset根据工作项目组的要求来设置

                br = new BufferedReader(new InputStreamReader(is, "UTF-8"));

 

                StringBuffer sbf = new StringBuffer();

                String temp = null;

                // 循环遍历一行一行读取数据

                while ((temp = br.readLine()) != null) {

                    sbf.append(temp);

                    sbf.append("\r\n");

                }

                result = sbf.toString();

            }

        catch (MalformedURLException e) {

            e.printStackTrace();

        catch (IOException e) {

            e.printStackTrace();

        finally {

            // 关闭资源

            if (null != br) {

                try {

                    br.close();

                catch (IOException e) {

                    e.printStackTrace();

                }

            }

            if (null != os) {

                try {

                    os.close();

                catch (IOException e) {

                    e.printStackTrace();

                }

            }

            if (null != is) {

                try {

                    is.close();

                catch (IOException e) {

                    e.printStackTrace();

                }

            }

            // 断开与远程地址url的连接

            connection.disconnect();

        }

        return result;

    }

 

二、使用Apache的HttpClient-4.x.Jar包。

  Jar包Maven下载地址:https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient

  实现方式如下:

 

package com.test.http;

 

import java.io.IOException;

import java.io.UnsupportedEncodingException;

import java.util.ArrayList;

import java.util.Iterator;

import java.util.List;

import java.util.Map;

import java.util.Map.Entry;

import java.util.Set;

 

import org.apache.http.HttpEntity;

import org.apache.http.NameValuePair;

import org.apache.http.client.ClientProtocolException;

import org.apache.http.client.config.RequestConfig;

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;

 

public class HttpClient4 {

 

    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);

            // 设置请求头信息,鉴权

            httpGet.setHeader("Authorization",

                    "Bearer da3efcbf-0845-4fe3-8aba-ee040be542c0");

            // 设置配置请求参数

            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;

    }

 

    public static String doPost(String url, Map<String, Object> paramMap) {

        CloseableHttpClient httpClient = null;

        CloseableHttpResponse httpResponse = null;

        String result = "";

        // 创建httpClient实例

        httpClient = HttpClients.createDefault();

        // 创建httpPost远程连接实例

        HttpPost httpPost = new HttpPost(url);

        // 配置请求参数实例

        RequestConfig requestConfig = RequestConfig.custom()

                .setConnectTimeout(35000)// 设置连接主机服务超时时间

                .setConnectionRequestTimeout(35000)// 设置连接请求超时时间

                .setSocketTimeout(60000)// 设置读取数据连接超时时间

                .build();

        // 为httpPost实例设置配置

        httpPost.setConfig(requestConfig);

        // 设置请求头

        httpPost.addHeader("Content-Type""application/x-www-form-urlencoded");

        // 封装post请求参数

        if (null != paramMap && paramMap.size() > 0) {

            List<NameValuePair> nvps = new ArrayList<NameValuePair>();

            // 通过map集成entrySet方法获取entity

            Set<Entry<String, Object>> entrySet = paramMap.entrySet();

            // 循环遍历,获取迭代器

            Iterator<Entry<String, Object>> iterator = entrySet.iterator();

            while (iterator.hasNext()) {

                Entry<String, Object> mapEntry = iterator.next();

                nvps.add(new BasicNameValuePair(mapEntry.getKey(), mapEntry

                        .getValue().toString()));

            }

 

            // 为httpPost设置封装好的请求参数

            try {

                httpPost.setEntity(new UrlEncodedFormEntity(nvps, "UTF-8"));

            catch (UnsupportedEncodingException e) {

                e.printStackTrace();

            }

        }

        try {

            // httpClient对象执行post请求,并返回响应参数对象

            httpResponse = httpClient.execute(httpPost);

            // 从响应对象中获取响应内容

            HttpEntity entity = httpResponse.getEntity();

            result = EntityUtils.toString(entity);

        catch (ClientProtocolException e) {

            e.printStackTrace();

        catch (IOException e) {

            e.printStackTrace();

        finally {

            // 关闭资源

            if (null != httpResponse) {

                try {

                    httpResponse.close();

                catch (IOException e) {

                    e.printStackTrace();

                }

            }

            if (null != httpClient) {

                try {

                    httpClient.close();

                catch (IOException e) {

                    e.printStackTrace();

                }

            }

        }

        return result;

    }

}

 

三、使用Apache的HttpClient-3.x.Jar包。

  Jar包Maven下载地址:https://mvnrepository.com/artifact/commons-httpclient/commons-httpclient

  实现方式如下

package com.powerX.httpClient;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
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;

public class HttpClient4 {

    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);
            // 设置请求头信息,鉴权
            httpGet.setHeader("Authorization", "Bearer da3efcbf-0845-4fe3-8aba-ee040be542c0");
            // 设置配置请求参数
            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;
    }

    public static String doPost(String url, Map<String, Object> paramMap) {
        CloseableHttpClient httpClient = null;
        CloseableHttpResponse httpResponse = null;
        String result = "";
        // 创建httpClient实例
        httpClient = HttpClients.createDefault();
        // 创建httpPost远程连接实例
        HttpPost httpPost = new HttpPost(url);
        // 配置请求参数实例
        RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(35000)// 设置连接主机服务超时时间
                .setConnectionRequestTimeout(35000)// 设置连接请求超时时间
                .setSocketTimeout(60000)// 设置读取数据连接超时时间
                .build();
        // 为httpPost实例设置配置
        httpPost.setConfig(requestConfig);
        // 设置请求头
        httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded");
        // 封装post请求参数
        if (null != paramMap && paramMap.size() > 0) {
            List<NameValuePair> nvps = new ArrayList<NameValuePair>();
            // 通过map集成entrySet方法获取entity
            Set<Entry<String, Object>> entrySet = paramMap.entrySet();
            // 循环遍历,获取迭代器
            Iterator<Entry<String, Object>> iterator = entrySet.iterator();
            while (iterator.hasNext()) {
                Entry<String, Object> mapEntry = iterator.next();
                nvps.add(new BasicNameValuePair(mapEntry.getKey(), mapEntry.getValue().toString()));
            }

            // 为httpPost设置封装好的请求参数
            try {
                httpPost.setEntity(new UrlEncodedFormEntity(nvps, "UTF-8"));
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }
        try {
            // httpClient对象执行post请求,并返回响应参数对象
            httpResponse = httpClient.execute(httpPost);
            // 从响应对象中获取响应内容
            HttpEntity entity = httpResponse.getEntity();
            result = EntityUtils.toString(entity);
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 关闭资源
            if (null != httpResponse) {
                try {
                    httpResponse.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (null != httpClient) {
                try {
                    httpClient.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return result;
    }
}

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/u012339179/article/details/102460497

智能推荐

C++ 创建文件夹与子文件夹_::access 和 ::mkdir-程序员宅基地

文章浏览阅读2.2w次,点赞4次,收藏15次。C++中fopen函数是没有创建文件夹功能的,也就是说如果‍‍".\\1\\2\\3\\"这个目录不存在,那么下面的代码是运行报错的。char *fileName=".\\1\\2\\3\\a.txt";FILE *ftest=fopen(fileName,"w");fprintf(ftest,"test\naldf\naldkf\m\n");fclose(ftest);要预防_::access 和 ::mkdir

XGB 训练的时候添加自定义eval_metric:f1、准确率,并对样本、特征加权训练_xgb eval_metric-程序员宅基地

文章浏览阅读5k次,点赞7次,收藏23次。文章目录XGB 训练的时候添加自定义eval_metric:f1、准确率,并对样本、特征加权训练随机搜索XGB 训练的时候添加自定义eval_metric:f1、准确率,并对样本、特征加权训练以下demo重点说明:eval_metric:用以训练的时候评估,必须要指定验证集,本博文分享自定义准确率、f1verbose:训练的时候对验证集评估是否打印,True和1等价,比如verbose=10,就会打印n_estimators // 10次feature_weights:特征加权训练,给一个sof_xgb eval_metric

matlab fhog,fhog.m · wycjl/kcf_matlab_apce - Gitee.com-程序员宅基地

文章浏览阅读320次。function H = fhog( I, binSize, nOrients, clip, crop )% Efficiently compute Felzenszwalb's HOG (FHOG) features.%% A fast implementation of the HOG variant used by Felzenszwalb et al.% in their work on ..._fhog matlab

java方法用泛函_Java泛型那些事儿-程序员宅基地

文章浏览阅读222次。1泛值明显有很大的重复以及各种硬编码(hard code):public void saveStudentA() {// TODO pseudo code// insert A into table Student}public void saveStudentB() {// TODO pseudo code// insert B into table Student}所谓的“泛”,就是特殊到一..._java function 泛型

http://codeforces.com/problemset/problem/265/B_codeforces problemset-程序员宅基地

文章浏览阅读277次。被题意秀了一脸,实际上第三个操作只能往后面的树去跳。#include &lt;iostream&gt;#include &lt;cstdio&gt;#include &lt;list&gt;#include &lt;stack&gt;#include &lt;queue&gt;#include &lt;cstdlib&gt;#include &lt;set&gt;#includ_codeforces problemset

QT Windows和Linux下,Qt Creator创建动态库和调用动态库(.dll 和 .so)_qt编写既能在linux又能在windows下面使用的库文件-程序员宅基地

文章浏览阅读6.8k次,点赞2次,收藏55次。简述Windows下动态链接库是.dll文件,静态链接库文件是.lib文件。Linux下动态库是.so文件。Qt嵌套在visual studio时,编译器是MSVC,而Qt Creator的编译器是MinGW,针对MSVC和MinGW这两种编译器,作个简单的介绍:MSVC是指微软的VC编译器。 MinGW是指是Minimalist GNU on Windows的缩写。它是一个可自由使..._qt编写既能在linux又能在windows下面使用的库文件

随便推点

【内网安全】——CS操作指南(一)_cs使用教程-程序员宅基地

文章浏览阅读8.2k次,点赞12次,收藏67次。cs基础教程(一),cs的安装和启动_cs使用教程

供应商关系管理系统SRM-程序员宅基地

文章浏览阅读3.5k次。供应商关系管理系统SRM是面向供应链前端,用来改善主机厂与其供应链上游供应商关系的系统,旨在改变主机厂传统的供应商管理模式,建立双方合作共赢的战略伙伴关系,并通过信息手段控制优化双方之间的信息流、物流和资金流,降低主机厂采购..._srm系统原型

el-input 指定宽度-程序员宅基地

文章浏览阅读4.6k次,点赞2次,收藏4次。在使用 el-input 组件时,可以通过设置 style 或 class 属性来指定其宽度。使用 style 属性设置宽度:<el-input placeholder="请输入内容" style="width: 200px;"></el-input>..._el-input设置宽度

【PTA题目】7-3 计算分段函数[3] (10 分)-程序员宅基地

文章浏览阅读5.7k次。本题目要求计算下列分段函数f(x)的值:输入格式:输入在一行中给出实数x。输出格式:在一行中按“f(x) = result”的格式输出,其中x与result都保留一位小数。输入样例1:10结尾无空行输出样例1:f(10.0) = 0.1结尾无空行输入样例2:234输出样例2:f(234.0) = 234.0#include<stdio.h>int main(void){ float x, y; scan

Requirement already satisfied的解决方案_requirement already satisfied: pip in-程序员宅基地

文章浏览阅读9.6k次,点赞2次,收藏14次。Requirement already satisfied 的解决办法_requirement already satisfied: pip in

数据库上机实验八(视图)_向视图中插入如下3条记录,并观看视图v_college和基本表stuinfo中的数据-程序员宅基地

文章浏览阅读745次。使用源码查询1中的user表完成如下操作:首先建立user表,sql语言为:CREATE TABLE user(id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,name VARCHAR(20) NOT NULL UNIQUE COMMENT '编号',age TINYINT UNSIGNED NOT NULL DEFAULT 18 COMMENT '年龄',sex ENUM('男','女','保密') NOT NULL DEFAULT '保密' COM_向视图中插入如下3条记录,并观看视图v_college和基本表stuinfo中的数据

推荐文章

热门文章

相关标签