精华内容
下载资源
问答
  • Java发送HTTP 请求
    万次阅读
    2019-03-19 15:29:25

    前言

    请求http的Demo是个人亲测过,目前该方式已经在线上运行着。因为是http请求,所有发送post 和get 请求的demo都有在下方贴出,包括怎么测试,大家可直接 copy到自己的项目中使用。

    正文

    使用须知

    为了避免大家引错包我把依赖和涉及到包路径给大家

    import java.net.HttpURLConnection;
    import java.net.URI;
    
    import org.apache.http.HttpResponse;
    import org.apache.http.HttpStatus;
    import org.apache.http.client.methods.HttpGet;
    import org.apache.http.client.methods.HttpPost;
    import org.apache.http.client.utils.URIBuilder;
    import org.apache.http.entity.StringEntity;
    import org.apache.http.impl.client.CloseableHttpClient;
    import org.apache.http.impl.client.DefaultHttpClient;
    import org.apache.http.impl.client.HttpClients;
    import org.apache.http.util.EntityUtils;
    
    
    import com.fasterxml.jackson.databind.ObjectMapper;
    
            <dependency>
    			<groupId>org.apache.httpcomponents</groupId>
    			<artifactId>httpcore</artifactId>
    			<version>4.4.8</version>
    		</dependency>
    		<dependency>
    			<groupId>org.apache.httpcomponents</groupId>
    			<artifactId>httpclient</artifactId>
    			<version>4.5.3</version>
    		</dependency>

    HTTP 发送 get 请求

    首先我们引入两个包

     

    发送get请求的工具类,可直接 copy 使用即可

    另外,我抛出异常的代码大家改成自己业务的异常,不需要就删除掉。

    参数说明:

    host:ip

    servUri:url

    reString:参数

    public static String getHttpData(String host, String servUri, String reString) throws Exception {
    		StringBuffer sb = new StringBuffer();
    		sb.append("getHttpData:host:" + host + ",servUri:" + servUri + ",reString:" + reString);
    		String strResp = null;
    		try {
    			URI uri = new URIBuilder().setScheme("http").setHost(host).setPath(servUri)
    					.setParameter("strInfo", reString).build();
    			HttpGet httpGet = new HttpGet(uri);
    			CloseableHttpClient client3 = HttpClients.createDefault();
    			HttpResponse resp;
    			resp = client3.execute(httpGet);
    			if (resp.getStatusLine().getStatusCode() == HttpURLConnection.HTTP_OK) {
    				strResp = EntityUtils.toString(resp.getEntity());
    				logger.info("the return result:{}", strResp);
    			} else {
    				logger.info("Error Response:", resp.getStatusLine().toString());
    				throw new CommonBusinessException(CommonConstants.TASK_RELEASE_WCF,
    						CommonConstants.TASK_RELEASE_WCF_DESC);
    			}
    		} catch (Exception e) {
    			logger.error(sb.toString() + ":" + e.getMessage(), e.getCause());
    			throw new CommonBusinessException(CommonConstants.TASK_RELEASE_WCF, CommonConstants.TASK_RELEASE_WCF_DESC);
    		}
    		return strResp;
    	}

     

     

    HTTP 发送 post 请求

    发送post分两种,我分两种的原因是为了让大家方便,想传对象和 json 可以直接复制过用就可以用,不用你们在转了。

    第一种是直接接收json

    参数明说:

    url:url

    json:参数

    public static String doPostData(String url, String json) throws Exception {
    		DefaultHttpClient client = new DefaultHttpClient();
    		HttpPost post = new HttpPost(url);
    		String result = "";
    		HttpResponse res = null;
    		try {
    			StringEntity s = new StringEntity(json.toString(), "UTF-8");
    			s.setContentType("application/json");
    			post.setHeader("Accept", "application/json");
    			post.setHeader("Content-type", "application/json; charset=utf-8");
    			post.setEntity(s);
    			res = client.execute(post);
    			if (res.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
    				result = EntityUtils.toString(res.getEntity());
    				return HttpStatus.SC_OK + "";
    			}
    		} catch (Exception e) {
    			if(res == null) {
    				return "HttpResponse 为 null!";
    			}
    			throw new RuntimeException(e);
    		}
    		if(res == null || res.getStatusLine() == null) {
    			return "无响应";
    		}
    		return res.getStatusLine().getStatusCode() + "";
    	}

    测试

    @Test
        public void test12() throws Exception {
            String HOST = "http://eipwcf.aspirecn.com/SvcEF/Service1.svc/WCF_EF_MSA_GetDataInfo_P";
            HttpClient client = new HttpClient();
            JSONObject json = new JSONObject();
            json.put("msgId", msgId);
            String reslut=client.doPostData(HOST, json);
        }
    

     

    第二种是参数是对象

    参数说明:

    url:url

    tram:对象

    public static String doHttpPostData(String url, TaskReleaseApprovalModel tram)
    			throws Exception {
    		StringBuffer sb = new StringBuffer();
    		sb.append("doHttpPostData:url:" + url + ",tram:" + tram.toString() + ",contentType:" + contentType);
    		logger.info(sb.toString());
    		String tmpString = "";
    		HttpPost request = new HttpPost(url);
    		request.setHeader("Accept", "application/json");
    		request.setHeader("Content-type", "application/json");
    		ObjectMapper mapper = new ObjectMapper();
    		String jsonString;
    		try {
    			jsonString = mapper.writeValueAsString(tram);
    			StringEntity entity = new StringEntity(jsonString, "UTF-8");
    			request.setEntity(entity);
    			CloseableHttpClient client = HttpClients.createDefault();
    			HttpResponse response = client.execute(request);
    			if (response.getStatusLine().getStatusCode() == HttpURLConnection.HTTP_OK) {
    				tmpString = EntityUtils.toString(response.getEntity());
    				logger.info("the post result:tmpString:{}", tmpString);
    			} else {
    				logger.info("the post failure:tmpString:", tmpString);
    				throw new CommonBusinessException(CommonConstants.TASK_RELEASE_WCF,
    						CommonConstants.TASK_RELEASE_WCF_DESC);
    			}
    		} catch (Exception e) {
    			logger.error(sb.toString() + ":" + e.getMessage(), e.getCause());
    			throw new CommonBusinessException(CommonConstants.TASK_RELEASE_POSTWCF,
    					CommonConstants.TASK_RELEASE_POSTWCF_DESC);
    		}
    		return tmpString;
    	}

    这个方法我想不用写测试类大家也会用,传过去对象和地址就可以了,很方便很简单。

     

     

     

     

     

     

     

    更多相关内容
  • 详解Java发送HTTP请求

    2020-08-26 04:10:57
    主要介绍了Java发送HTTP请求,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
  • 本文通过实例代码给大家介绍了Java 发送http请求上传文件功能,需要的朋友参考下吧
  • 主要介绍了JAVA发送HTTP请求,返回HTTP响应内容,应用及实例代码,需要的朋友可以参考下
  • 这是一个java发送get、post请求,并得到返回结果的工具类。
  • Java 发送 HTTP 请求的两种常用方法

    千次阅读 2021-05-16 15:59:56
    本文主要介绍在 Java 编程中发送 HTTP 请求的两种常用方法: JDK 原生的 HttpURLConnection 发送 HTTP 请求 Apache HhttpClient 发送 HTTP 请求 两种方法都可以发送 HTTP 请求,第一种是 Java 原生的,因此使用...

    本文主要介绍在 Java 编程中发送 HTTP 请求的两种常用方法:

    两种方法都可以发送 HTTP 请求,第一种是 Java 原生的,因此使用起来相对麻烦一些,第二种是通过第三方的包来实现,这个包是 Apache 旗下的专门用来发送 HTTP 请求的 HttpClient 包,是对 Java 原生的 HttpURLConnection 扩展,因此功能也更加强大,使用起来也相对简单一些,目前这种方式发送 HTTP 请求应用比较广泛,因此主要学习这种方式。

    Apache HttpClient 官方文档见这里:http://hc.apache.org/httpcomponents-client-5.1.x/

    Talk is cheap. Show me the code. 下面看具体使用代码示例。

    1、JDK 原生的 HttpURLConnection 发送 HTTP 请求 GET/POST

    基于 JDK 原生的 HttpURLConnection 类,简单封装了下 HTTP GET 和 POST 请求方法,重在学习使用。

    package com.example.demo.common.utils;
    /**
     * Created by qianghaohao on 2021/5/16
     */
    
    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;
    
    /**
     * @description: 使用 java 原生 HttpURLConnection 类发送 http 请求
     * @author: qianghaohao
     * @time: 2021/5/16
     */
    public class HttpURLConnectionUtils {
        public static String doGet(String httpUrl) {
            HttpURLConnection connection = null;
            InputStream inputStream = null;
            BufferedReader bufferedReader = 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连接,获取输入流
                if (connection.getResponseCode() == 200) {
                    inputStream = connection.getInputStream();
                    // 封装输入流is,并指定字符集
                    bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
                    // 存放数据
                    StringBuilder sb = new StringBuilder();
                    String temp;
                    while ((temp = bufferedReader.readLine()) != null) {
                        sb.append(temp);
                        sb.append(System.lineSeparator());  // 这里需要追加换行符,默认读取的流没有换行符,需要加上才能符合预期
                    }
                    result = sb.toString();
                }
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                // 关闭资源
                if (null != bufferedReader) {
                    try {
                        bufferedReader.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if (null != inputStream) {
                    try {
                        inputStream.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
    
                if (null != connection) {
                    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);
    
                // 设置传入参数的格式:请求参数应该是 name1=value1&name2=value2 的形式。
                connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
    
                // 通过连接对象获取一个输出流
                os = connection.getOutputStream();
    
                // 通过输出流对象将参数写出去/传输出去,它是通过字节数组写出的
                os.write(param.getBytes());
    
                // 通过连接对象获取一个输入流,向远程读取
                if (connection.getResponseCode() == 200) {
                    is = connection.getInputStream();
                    // 对输入流对象进行包装:charset根据工作项目组的要求来设置
                    br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
                    StringBuilder sb = new StringBuilder();
                    String temp;
                    // 循环遍历一行一行读取数据
                    while ((temp = br.readLine()) != null) {
                        sb.append(temp);
                        sb.append(System.lineSeparator());
                    }
                    result = sb.toString();
                }
            } 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();
                    }
                }
                if (null != connection) {
                    // 断开与远程地址url的连接
                    connection.disconnect();
                }
            }
            return result;
        }
    }
    

    2、Apache HhttpClient 发送 HTTP 请求 GET/POST

    基于 Apache HhttpClient,简单封装了下 HTTP GET 和 POST 请求方法,重在学习使用。

    package com.example.demo.common.utils;
    /**
     * Created by qianghaohao on 2021/5/16
     */
    
    import org.apache.http.HttpEntity;
    import org.apache.http.NameValuePair;
    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;
    
    import java.io.IOException;
    import java.io.UnsupportedEncodingException;
    import java.util.ArrayList;
    import java.util.List;
    import java.util.Map;
    import java.util.Set;
    
    /**
     * @description: 使用 Apache HttpClient 发送 http 请求
     * @author: qianghaohao
     * @time: 2021/5/16
     */
    public class HttpClientUtils {
        public static String doGet(String url) {
            String content = null;
            // 创建 HttpClient 对象
            CloseableHttpClient httpclient = HttpClients.createDefault();
    
            // 创建 Http GET 请求
            HttpGet httpGet = new HttpGet(url);
    
            CloseableHttpResponse response = null;
            try {
                // 执行请求
                response = httpclient.execute(httpGet);
                // 判断返回状态是否为200
                if (response.getStatusLine().getStatusCode() == 200) {
                    //响应体内容
                    content = EntityUtils.toString(response.getEntity(), "UTF-8");
                }
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if (response != null) {
                    try {
                        response.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                try {
                    httpclient.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
    
            return content;
        }
    
        public static String doPost(String url, Map<String, Object> paramMap) {
            CloseableHttpClient httpClient = null;
            CloseableHttpResponse httpResponse = null;
            String result = null;
            // 创建httpClient实例
            httpClient = HttpClients.createDefault();
    
            // 创建httpPost远程连接实例
            HttpPost httpPost = new HttpPost(url);
    
            // 设置请求头
            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<Map.Entry<String, Object>> entrySet = paramMap.entrySet();
                // 循环遍历,获取迭代器
                for (Map.Entry<String, Object> mapEntry : entrySet) {
                    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 (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;
        }
    }
    

    3、上面封装类使用示例

        @Test
        public void httpDoGetTest() {
            // Java 原生 HttpURLConnection 发送 HTTP 请求测试
            String url = "https://httpbin.org/get";
            String result = HttpURLConnectionUtils.doGet(url);
            System.out.println(result);
    
            // Apache HttpClient 发送 http 请求测试
            System.out.println("==============");
            result = HttpClientUtils.doGet(url);
            System.out.println(result);
        }
        
        @Test
        public void httpDoPostTest() {
            // Java 原生 HttpURLConnection 发送 HTTP 请求测试
            String url = "https://httpbin.org/post";
            String urlParameters = "name=Jack&occupation=programmer";
            String result = HttpURLConnectionUtils.doPost(url, urlParameters);
            System.out.println(result);
    
            // Apache HttpClient 发送 http 请求测试
            System.out.println("==============");
            Map<String, Object> params = new HashMap<>();
            params.put("name", "Jack");
            params.put("occupation", "programmer");
            result = HttpClientUtils.doPost(url, params);
            System.out.println(result);
        }
    
    展开全文
  • java发送http请求

    2016-05-09 16:29:51
    java发送http请求的一个小例子 包含get和post两种请求方式
  • java编写了http Post的请求代码,通过发送请求的 URL,获取远程资源的响应结果,入参为json字符串。使用到httpPost,CloseableHttpClient
  • Java发送Http请求,解析html返回
  • Java 发送http请求

    千次阅读 2018-07-04 20:33:48
    发送GET方法的请求 /** * 向指定URL发送GET方法的请求 * * @param url * 发送请求的URL * @param param * 请求参数,格式:name1=value1&amp;amp;name2=value2 * @return String 响应结果 ...

    发送GET方法的请求

        /**
         * 向指定URL发送GET方法的请求
         * @param url  发送请求的URL         
         * @param param   请求参数,格式:name1=value1&name2=value2   
         * @return String 响应结果
         */
        public static String sendGet(String url, String param) {
            String result = "";
            BufferedReader in = null;
            try {
                String urlNameString = url + "?" + param;
                URL realUrl = new URL(urlNameString);
                // 打开和URL之间的连接
                HttpURLConnection connection = (HttpURLConnection)realUrl.openConnection();
                // 设置通用的请求属性
                connection.setRequestProperty("accept", "*/*");
                connection.setRequestProperty("connection", "Keep-Alive");
                connection.setRequestProperty("user-agent",
                        "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
                // 建立实际的连接
                connection.connect();
                // 获取所有响应头字段
                Map<String, List<String>> map = connection.getHeaderFields();
                // 遍历所有的响应头字段
                for (String key : map.keySet()) {
                    System.out.println(key + "--->" + map.get(key));
                }
                // 定义 BufferedReader输入流来读取URL的响应
                in = new BufferedReader(new InputStreamReader(
                        connection.getInputStream()));
                String line;
                while ((line = in.readLine()) != null) {
                    result += line;
                }
            } catch (Exception e) {
                System.out.println("发送GET请求出现异常!" + e);
                e.printStackTrace();
            }
            // 使用finally块来关闭输入流
            finally {
                try {
                    if (in != null) {
                        in.close();
                    }
                } catch (Exception e2) {
                    e2.printStackTrace();
                }
            }
            return result;
        }

    发送POST方法的请求

    /**
         * 向指定 URL 发送POST方法的请求
         * @param url 发送请求的 URL
         * @param param 请求参数,格式: name1=value1&name2=value2
         * @return  响应结果
         */
        public static String sendPost(String url, String param) {
            PrintWriter out = null;
            BufferedReader in = null;
            String result = "";
            try {
                URL realUrl = new URL(url);
                // 打开和URL之间的连接
                URLConnection conn = realUrl.openConnection();
                // 设置通用的请求属性
                conn.setRequestProperty("accept", "*/*");
                conn.setRequestProperty("connection", "Keep-Alive");
                conn.setRequestProperty("user-agent",
                        "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
                // 发送POST请求必须设置如下两行
                conn.setDoOutput(true);
                conn.setDoInput(true);
                // 获取URLConnection对象对应的输出流
                out = new PrintWriter(conn.getOutputStream());
                // 发送请求参数
                out.print(param);
                // flush输出流的缓冲
                out.flush();
                // 定义BufferedReader输入流来读取URL的响应
                in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
                String line;
                while ((line = in.readLine()) != null) {
                    result += line;
                }
            } catch (Exception e) {
                System.out.println("发送 POST 请求出现异常!"+e);
                e.printStackTrace();
            }
            //使用finally块来关闭输出流、输入流
            finally{
                try{
                    if(out!=null){
                        out.close();
                    }
                    if(in!=null){
                        in.close();
                    }
                }
                catch(IOException ex){
                    ex.printStackTrace();
                }
            }
            return result;
        }

    发送参数为json类型的POST请求

    /**
         发送HttpPost请求
         * @param strURL  服务地址
         * @param params  Map类型的参数,再用JSONUtils工具把map转化成json
         * @return 成功:返回json字符串<br/>
         */
        public static String jsonPost(String strURL, Map<String, String> params) {
            try {
                URL url = new URL(strURL);// 创建连接
                HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                connection.setDoOutput(true);
                connection.setDoInput(true);
                connection.setUseCaches(false);
                connection.setInstanceFollowRedirects(true);
                connection.setRequestMethod("POST"); // 设置请求方式
                connection.setRequestProperty("Accept", "application/json"); // 设置接收数据的格式
                connection.setRequestProperty("Content-Type", "application/json"); // 设置发送数据的格式
                connection.connect();
                OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream(), "UTF-8"); // utf-8编码
                out.append(JSONUtils.obj2String(params));
                out.flush();
                out.close();
                int code = connection.getResponseCode();
                InputStream is = null;
                if (code == 200) {
                    is = connection.getInputStream();
                } else {
                    is = connection.getErrorStream();
                }
    
                // 读取响应
                int length = (int) connection.getContentLength();// 获取长度
                if (length != -1) {
                    byte[] data = new byte[length];
                    byte[] temp = new byte[512];
                    int readLen = 0;
                    int destPos = 0;
                    while ((readLen = is.read(temp)) > 0) {
                        System.arraycopy(temp, 0, data, destPos, readLen);
                        destPos += readLen;
                    }
                    String result = new String(data, "UTF-8"); // utf-8编码
                    System.out.println(result);
                    return result;
                }
    
            } catch (IOException e) {
                logger.error("Exception occur when send http post request!", e);
                System.out.println(e);
            }
            return "error"; // 自定义错误信息
        }

    完整代码

    HttpRequest.java

    /**
     * Created by pc on 2018/6/29.
     */
    import java.io.*;
    import java.net.HttpURLConnection;
    import java.net.URL;
    import java.net.URLConnection;
    import java.util.HashMap;
    import java.util.List;
    import java.util.Map;
    
    public class HttpRequest {
        /**
         * 向指定URL发送GET方法的请求
         * @param url  发送请求的URL         
         * @param param   请求参数,格式:name1=value1&name2=value2   
         * @return String 响应结果
         */
        public static String sendGet(String url, String param) {
            String result = "";
            BufferedReader in = null;
            try {
                String urlNameString = url + "?" + param;
                URL realUrl = new URL(urlNameString);
                // 打开和URL之间的连接
                HttpURLConnection connection = (HttpURLConnection)realUrl.openConnection();
                // 设置通用的请求属性
                connection.setRequestProperty("accept", "*/*");
                connection.setRequestProperty("connection", "Keep-Alive");
                connection.setRequestProperty("user-agent",
                        "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
                // 建立实际的连接
                connection.connect();
                // 获取所有响应头字段
                Map<String, List<String>> map = connection.getHeaderFields();
                // 遍历所有的响应头字段
                for (String key : map.keySet()) {
                    System.out.println(key + "--->" + map.get(key));
                }
                // 定义 BufferedReader输入流来读取URL的响应
                in = new BufferedReader(new InputStreamReader(
                        connection.getInputStream()));
                String line;
                while ((line = in.readLine()) != null) {
                    result += line;
                }
            } catch (Exception e) {
                System.out.println("发送GET请求出现异常!" + e);
                e.printStackTrace();
            }
            // 使用finally块来关闭输入流
            finally {
                try {
                    if (in != null) {
                        in.close();
                    }
                } catch (Exception e2) {
                    e2.printStackTrace();
                }
            }
            return result;
        }
    
        /**
         * 向指定 URL 发送POST方法的请求
         * @param url 发送请求的 URL
         * @param param 请求参数,格式: name1=value1&name2=value2
         * @return  响应结果
         */
        public static String sendPost(String url, String param) {
            PrintWriter out = null;
            BufferedReader in = null;
            String result = "";
            try {
                URL realUrl = new URL(url);
                // 打开和URL之间的连接
                URLConnection conn = realUrl.openConnection();
                // 设置通用的请求属性
                conn.setRequestProperty("accept", "*/*");
                conn.setRequestProperty("connection", "Keep-Alive");
                conn.setRequestProperty("user-agent",
                        "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
                // 发送POST请求必须设置如下两行
                conn.setDoOutput(true);
                conn.setDoInput(true);
                // 获取URLConnection对象对应的输出流
                out = new PrintWriter(conn.getOutputStream());
                // 发送请求参数
                out.print(param);
                // flush输出流的缓冲
                out.flush();
                // 定义BufferedReader输入流来读取URL的响应
                in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
                String line;
                while ((line = in.readLine()) != null) {
                    result += line;
                }
            } catch (Exception e) {
                System.out.println("发送 POST 请求出现异常!"+e);
                e.printStackTrace();
            }
            //使用finally块来关闭输出流、输入流
            finally{
                try{
                    if(out!=null){
                        out.close();
                    }
                    if(in!=null){
                        in.close();
                    }
                }
                catch(IOException ex){
                    ex.printStackTrace();
                }
            }
            return result;
        }
    
         /**
         发送HttpPost请求
         * @param strURL  服务地址
         * @param params  传入Map类型的参数,再用JSONUtils工具把map转化成json
         * @return 成功:返回json字符串<br/>
         */
        public static String jsonPost(String strURL, Map<String, String> params) {
            try {
                URL url = new URL(strURL);// 创建连接
                HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                connection.setDoOutput(true);
                connection.setDoInput(true);
                connection.setUseCaches(false);
                connection.setInstanceFollowRedirects(true);
                connection.setRequestMethod("POST"); // 设置请求方式
                connection.setRequestProperty("Accept", "application/json"); // 设置接收数据的格式
                connection.setRequestProperty("Content-Type", "application/json"); // 设置发送数据的格式
                connection.connect();
                OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream(), "UTF-8"); // utf-8编码
                out.append(JSONUtils.obj2String(params));
                out.flush();
                out.close();
                int code = connection.getResponseCode();
                InputStream is = null;
                if (code == 200) {
                    is = connection.getInputStream();
                } else {
                    is = connection.getErrorStream();
                }
    
                // 读取响应
                int length = (int) connection.getContentLength();// 获取长度
                if (length != -1) {
                    byte[] data = new byte[length];
                    byte[] temp = new byte[512];
                    int readLen = 0;
                    int destPos = 0;
                    while ((readLen = is.read(temp)) > 0) {
                        System.arraycopy(temp, 0, data, destPos, readLen);
                        destPos += readLen;
                    }
                    String result = new String(data, "UTF-8"); // utf-8编码
                    System.out.println(result);
                    return result;
                }
    
            } catch (IOException e) {
                System.out.println(e);
            }
            return "error"; // 自定义错误信息
        }
    }

    JSONUtils.java

    package com.chinawayltd.test;
    
    import org.codehaus.jackson.map.DeserializationConfig;
    import org.codehaus.jackson.map.ObjectMapper;
    import org.codehaus.jackson.map.SerializationConfig;
    import org.codehaus.jackson.map.annotate.JsonSerialize.Inclusion;
    import org.codehaus.jackson.type.JavaType;
    
    import java.io.IOException;
    import java.text.SimpleDateFormat;
    
    /**
     * Created by pc on 2018/6/29.
     */
    public class JSONUtils {
        private static ObjectMapper objectMapper = new ObjectMapper();
    
        static {
            // 对象字段全部列入
            objectMapper.setSerializationInclusion(Inclusion.NON_DEFAULT);
    
            // 取消默认转换timestamps形式
            objectMapper.configure(SerializationConfig.Feature.WRITE_DATES_AS_TIMESTAMPS,false);
    
            // 忽略空bean转json的错误
            objectMapper.configure(SerializationConfig.Feature.FAIL_ON_EMPTY_BEANS,false);
    
            // 统一日期格式yyyy-MM-dd HH:mm:ss
            objectMapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
    
            // 忽略在json字符串中存在,但是在java对象中不存在对应属性的情况
            objectMapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES,false);
        }
    
        /**
         * Object转json字符串
         * @param obj
         * @param <T>
         * @return
         */
        public static <T> String obj2String(T obj){
            if (obj == null){
                return null;
            }
            try {
                return obj instanceof String ? (String) obj : objectMapper.writeValueAsString(obj);
            } catch (Exception e) {
                System.out.println("Parse object to String error");
                e.printStackTrace();
                return null;
            }
        }
    
        /**
         * Object转json字符串并格式化美化
         * @param obj
         * @param <T>
         * @return
         */
        public static <T> String obj2StringPretty(T obj){
            if (obj == null){
                return null;
            }
            try {
                return obj instanceof String ? (String) obj : objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(obj);
            } catch (Exception e) {
                System.out.println("Parse object to String error");
                e.printStackTrace();
                return null;
            }
        }
    
        /**
         * string转object 用于转为集合对象
         * @param str json字符串
         * @param collectionClass 被转集合class
         * @param elementClasses 被转集合中对象类型class
         * @param <T>
         * @return
         */
        public static <T> T string2Obj(String str,Class<?> collectionClass,Class<?>... elementClasses){
            JavaType javaType = objectMapper.getTypeFactory().constructParametricType(collectionClass,elementClasses);
            try {
                return objectMapper.readValue(str,javaType);
            } catch (IOException e) {
                System.out.println("Parse String to Object error");
                e.printStackTrace();
                return null;
            }
        }
    }
    
    展开全文
  • 完整的java发送http包工程,可发送get及post请求
  • import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.impl.client.HttpClients; import org.apache.htt
  • JAVA发送HTTP请求方式总结

    万次阅读 多人点赞 2018-05-30 14:40:21
    java 发送HTTP请求方式总结 源代码:http://github.com/lovewenyo/HttpDemo 1. HttpURLConnection 使用JDK原生提供的net,无需其他jar包; HttpURLConnection是URLConnection的子类,提供更多的方法,...

    java 发送HTTP请求方式总结

    源代码:http://github.com/lovewenyo/HttpDemo

    1. HttpURLConnection

    使用JDK原生提供的net,无需其他jar包;

    HttpURLConnection是URLConnection的子类,提供更多的方法,使用更方便。

    package httpURLConnection;
    
    import java.io.BufferedReader;
    import java.io.InputStream;
    import java.io.InputStreamReader;
    
    import java.net.HttpURLConnection;
    import java.net.URL;
    
    public class HttpURLConnectionHelper {
    
        public static String sendRequest(String urlParam,String requestType) {
    
            HttpURLConnection con = null;  
    
            BufferedReader buffer = null; 
            StringBuffer resultBuffer = null;  
    
            try {
                URL url = new URL(urlParam); 
                //得到连接对象
                con = (HttpURLConnection) url.openConnection(); 
                //设置请求类型
                con.setRequestMethod(requestType);  
                //设置请求需要返回的数据类型和字符集类型
                con.setRequestProperty("Content-Type", "application/json;charset=GBK");  
                //允许写出
                con.setDoOutput(true);
                //允许读入
                con.setDoInput(true);
                //不使用缓存
                con.setUseCaches(false);
                //得到响应码
                int responseCode = con.getResponseCode();
    
                if(responseCode == HttpURLConnection.HTTP_OK){
                    //得到响应流
                    InputStream inputStream = con.getInputStream();
                    //将响应流转换成字符串
                    resultBuffer = new StringBuffer();
                    String line;
                    buffer = new BufferedReader(new InputStreamReader(inputStream, "GBK"));
                    while ((line = buffer.readLine()) != null) {
                        resultBuffer.append(line);
                    }
                    return resultBuffer.toString();
                }
    
            }catch(Exception e) {
                e.printStackTrace();
            }
            return "";
        }
        public static void main(String[] args) {
    
            String url ="http://int.dpool.sina.com.cn/iplookup/iplookup.php?ip=120.79.75.96";
            System.out.println(sendRequest(url,"POST"));
        }
    }
    

    2. URLConnection

    使用JDK原生提供的net,无需其他jar包;

    建议使用HttpURLConnection

    package uRLConnection;
    
    import java.io.BufferedReader;
    import java.io.InputStream;
    import java.io.InputStreamReader;
    import java.net.HttpURLConnection;
    import java.net.URL;
    import java.net.URLConnection;
    
    public class URLConnectionHelper {
    
        public static String sendRequest(String urlParam) {
    
            URLConnection con = null;  
    
            BufferedReader buffer = null; 
            StringBuffer resultBuffer = null;  
    
            try {
                 URL url = new URL(urlParam); 
                 con = url.openConnection();  
    
                //设置请求需要返回的数据类型和字符集类型
                con.setRequestProperty("Content-Type", "application/json;charset=GBK");  
                //允许写出
                con.setDoOutput(true);
                //允许读入
                con.setDoInput(true);
                //不使用缓存
                con.setUseCaches(false);
                //得到响应流
                InputStream inputStream = con.getInputStream();
                //将响应流转换成字符串
                resultBuffer = new StringBuffer();
                String line;
                buffer = new BufferedReader(new InputStreamReader(inputStream, "GBK"));
                while ((line = buffer.readLine()) != null) {
                    resultBuffer.append(line);
                }
                return resultBuffer.toString();
    
            }catch(Exception e) {
                e.printStackTrace();
            }
    
            return "";
        }
        public static void main(String[] args) {
            String url ="http://int.dpool.sina.com.cn/iplookup/iplookup.php?ip=120.79.75.96";
            System.out.println(sendRequest(url));
        }
    }
    

    3. HttpClient

    使用方便,我个人偏爱这种方式,但依赖于第三方jar包,相关maven依赖如下:

    <!-- https://mvnrepository.com/artifact/commons-httpclient/commons-httpclient -->
    <dependency>
        <groupId>commons-httpclient</groupId>
        <artifactId>commons-httpclient</artifactId>
        <version>3.1</version>
    </dependency
    

    package httpClient;
    
    import java.io.IOException;
    
    import org.apache.commons.httpclient.HttpClient;
    import org.apache.commons.httpclient.HttpException;
    import org.apache.commons.httpclient.methods.GetMethod;
    import org.apache.commons.httpclient.methods.PostMethod;
    import org.apache.commons.httpclient.params.HttpMethodParams;
    
    public class HttpClientHelper {
        public static String sendPost(String urlParam) throws HttpException, IOException {
            // 创建httpClient实例对象
            HttpClient httpClient = new HttpClient();
            // 设置httpClient连接主机服务器超时时间:15000毫秒
            httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(15000);
            // 创建post请求方法实例对象
            PostMethod postMethod = new PostMethod(urlParam);
            // 设置post请求超时时间
            postMethod.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, 60000);
            postMethod.addRequestHeader("Content-Type", "application/json");
    
            httpClient.executeMethod(postMethod);
    
            String result = postMethod.getResponseBodyAsString();
            postMethod.releaseConnection();
            return result;
        }
        public static String sendGet(String urlParam) throws HttpException, IOException {
            // 创建httpClient实例对象
            HttpClient httpClient = new HttpClient();
            // 设置httpClient连接主机服务器超时时间:15000毫秒
            httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(15000);
            // 创建GET请求方法实例对象
            GetMethod getMethod = new GetMethod(urlParam);
            // 设置post请求超时时间
            getMethod.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, 60000);
            getMethod.addRequestHeader("Content-Type", "application/json");
    
            httpClient.executeMethod(getMethod);
    
            String result = getMethod.getResponseBodyAsString();
            getMethod.releaseConnection();
            return result;
        }
        public static void main(String[] args) throws HttpException, IOException {
            String url ="http://int.dpool.sina.com.cn/iplookup/iplookup.php?ip=120.79.75.96";
            System.out.println(sendPost(url));
            System.out.println(sendGet(url));
        }
    }
    

    4. Socket

    使用JDK原生提供的net,无需其他jar包;

    使用起来有点麻烦。

    package socket;
    import java.io.BufferedInputStream;  
    import java.io.BufferedReader;  
    import java.io.BufferedWriter;  
    import java.io.IOException;  
    import java.io.InputStreamReader;  
    import java.io.OutputStreamWriter;  
    import java.net.Socket;  
    import java.net.URLEncoder;  
    
    import javax.net.ssl.SSLSocket;  
    import javax.net.ssl.SSLSocketFactory;  
    
    public class SocketForHttpTest {  
    
        private int port;  
        private String host;  
        private Socket socket;  
        private BufferedReader bufferedReader;  
        private BufferedWriter bufferedWriter;  
    
        public SocketForHttpTest(String host,int port) throws Exception{  
    
            this.host = host;  
            this.port = port;  
    
            /**  
             * http协议  
             */  
            // socket = new Socket(this.host, this.port);  
    
            /**  
             * https协议  
             */  
            socket = (SSLSocket)((SSLSocketFactory)SSLSocketFactory.getDefault()).createSocket(this.host, this.port);  
    
    
        }  
    
        public void sendGet() throws IOException{  
            //String requestUrlPath = "/z69183787/article/details/17580325";  
            String requestUrlPath = "/";          
    
            OutputStreamWriter streamWriter = new OutputStreamWriter(socket.getOutputStream());    
            bufferedWriter = new BufferedWriter(streamWriter);              
            bufferedWriter.write("GET " + requestUrlPath + " HTTP/1.1\r\n");    
            bufferedWriter.write("Host: " + this.host + "\r\n");    
            bufferedWriter.write("\r\n");    
            bufferedWriter.flush();    
    
            BufferedInputStream streamReader = new BufferedInputStream(socket.getInputStream());    
            bufferedReader = new BufferedReader(new InputStreamReader(streamReader, "utf-8"));    
            String line = null;    
            while((line = bufferedReader.readLine())!= null){    
                System.out.println(line);    
            }    
            bufferedReader.close();    
            bufferedWriter.close();    
            socket.close();  
    
        }  
    
    
        public void sendPost() throws IOException{    
                String path = "/";    
                String data = URLEncoder.encode("name", "utf-8") + "=" + URLEncoder.encode("张三", "utf-8") + "&" +    
                            URLEncoder.encode("age", "utf-8") + "=" + URLEncoder.encode("32", "utf-8");    
                // String data = "name=zhigang_jia";    
                System.out.println(">>>>>>>>>>>>>>>>>>>>>"+data);              
                OutputStreamWriter streamWriter = new OutputStreamWriter(socket.getOutputStream(), "utf-8");    
                bufferedWriter = new BufferedWriter(streamWriter);                  
                bufferedWriter.write("POST " + path + " HTTP/1.1\r\n");    
                bufferedWriter.write("Host: " + this.host + "\r\n");    
                bufferedWriter.write("Content-Length: " + data.length() + "\r\n");    
                bufferedWriter.write("Content-Type: application/x-www-form-urlencoded\r\n");    
                bufferedWriter.write("\r\n");    
                bufferedWriter.write(data);    
    
                bufferedWriter.write("\r\n");    
                bufferedWriter.flush();    
    
                BufferedInputStream streamReader = new BufferedInputStream(socket.getInputStream());    
                bufferedReader = new BufferedReader(new InputStreamReader(streamReader, "utf-8"));    
                String line = null;    
                while((line = bufferedReader.readLine())!= null)    
                {    
                    System.out.println(line);    
                }    
                bufferedReader.close();    
                bufferedWriter.close();    
                socket.close();    
        }    
    
        public static void main(String[] args) throws Exception {  
            /**  
             * http协议测试  
             */  
            //SocketForHttpTest forHttpTest = new SocketForHttpTest("www.baidu.com", 80);  
            /**  
             * https协议测试  
             */  
            SocketForHttpTest forHttpTest = new SocketForHttpTest("www.baidu.com", 443);  
            try {  
                forHttpTest.sendGet();  
            //  forHttpTest.sendPost();  
            } catch (IOException e) {  
    
                e.printStackTrace();  
            }  
        }  
    
    }  
    
    展开全文
  • 下面小编就为大家分享一篇java 发送http和https请求的实例,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
  • 发送Get请求,但是请求参数要放在请求body内,所以经过多方查证后整理出来以下代码。 2.POM依赖 <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>...
  • 下面小编就为大家带来一篇java发送http get请求的两种方法(总结)。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧
  • Java发送Http请求的一般步骤

    千次阅读 2019-04-29 14:51:41
    Java发送Http请求的一般步骤 最近在使用百度地图和百度AI的开发API,经常需要发送http请求,在这里记录一下java发送Http请求的步骤。希望对大家有用。 了解Http报文结构 首先介绍Http协议的结构。请求报文和响应...
  • java模拟网络请求,get post put delete四种模式,请求头处理参数处理。此文件仅供大家参考,稍作修改即可。
  • JAVA发送HTTP请求的几种方式

    千次阅读 2021-06-29 09:14:44
    JAVA发送HTTP请求的几种方式 以下4种分别可发送get和post请求的方法: 第1种:HttpURLConnection、 第2种:URLConnection、 第3种:HttpClient, HttpClient常用HttpGet和HttpPost这两个类,分别对应Get方式和Post...
  • import com.actionsoft.bpms.util.UUIDGener; import ... import org.apache.http.HttpResponse; import org.apache.http.HttpStatus; import org.apache.http.client.HttpClient; import org.a...
  • 主要介绍了Java发送http get/post请求调用接口/方法,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
  • java发送http请求,无需等待返回结果

    千次阅读 2021-02-26 16:31:16
    HttpURLConnection 有个 setReadTimeout 的方法...public static String doGet(String HTTP_URL, Object object) {BufferedReader reader = null;String result = null;StringBuffer httpUrl = new StringBuffer(HT...
  • JAVA发送HTTP请求(https SSL)实现案例

    万次阅读 多人点赞 2018-01-18 19:42:00
    可以用做http工具类,供大家参考,欢迎大家一起交流学习, 下面我直接贴代码,如下: import java.io.BufferedReader; import java.io.ByteArrayOutputStream; import java.io.File; import java.io....
  • 1、有时间的话话,先看下原理: ...2、研究 restTemplate.postForEntity 的请求参数: https://www.cnblogs.com/qq931399960/p/11420121.html 3、然后搞定了,代码放下面了 // 配置基础请求参数 String url ...
  • java发送http请求有三种方式,除了原生连接方式HttpURLConnection,还有另外两种方式:HTTPClient和CloseableHttpClient 下面分别简单介绍使用HTTPClient和CloseableHTTPClient进行Get和Post请求的方式。 详情使用...
  • 是一个Java 发送http put、delete、 post、 get 请求的工具类。可用在与restful service 进行通讯的代码中。
  • Java 发送http请求demo

    千次阅读 2018-06-01 17:55:25
    import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.net.URL; import java.net.URLConnection; import java.util.List; impo...
  • JAVA发送HTTP请求,返回HTTP响应内容

    热门讨论 2011-04-20 16:58:03
    JAVA发送HTTP请求,返回HTTP响应内容 首先让我们先构建一个请求类(HttpRequester)。 该类封装了JAVA实现简单请求的代码。 其次我们来看看响应对象(HttpRespons)。响应对象其实只是一个数据BEAN,由此来封装请求...
  • NULL 博文链接:https://genius.iteye.com/blog/451378

空空如也

空空如也

1 2 3 4 5 ... 20
收藏数 427,951
精华内容 171,180
关键字:

java发送http请求

java 订阅