手记

JAVA实现HTTP请求的方法

目前JAVA实现HTTP请求的方法用的最多的有两种:

    第一种是java原生HttpURLConnection

import java.io.BufferedReader;import java.io.IOException;import java.io.InputStream;import java.io.InputStreamReader;import java.io.OutputStream;import java.net.HttpURLConnection;import java.net.MalformedURLException;import java.net.URL;public class HttpClient {    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;    }    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(15000);            // 设置读取主机服务器返回数据超时时间:60000毫秒            connection.setReadTimeout(60000);            // 默认值为: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  httpClient4.5

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

有时候我们在使用post请求时,可能传入的参数是json或者其他格式,此时我们则需要更改请求头及参数的设置信息,以httpClient4.5为例,更改下面两列配置:httpPost.setEntity(new StringEntity("你的json串"));      httpPost.addHeader("Content-Type", "application/json")。

0人推荐
随时随地看视频
慕课网APP