精华内容
下载资源
问答
  • java发送http请求

    2016-05-09 16:29:51
    java发送http请求的一个小例子 包含get和post两种请求方式
  • java 发送http请求

    2014-11-11 10:51:21
    java发送http请求 最常用的Http请求无非是get和post,get请求可以获取静态页面,也可以把参数放在URL字串后面,传递给servlet。post与get的不同之处在于post的参数不是放在URL字串里面,而是放在http请求...
    java发送http请求 




    最常用的Http请求无非是get和post,get请求可以获取静态页面,也可以把参数放在URL字串后面,传递给servlet。post与get的不同之处在于post的参数不是放在URL字串里面,而是放在http请求的正文内。
    在Java中可以使用HttpURLConnection发起这两种请求,了解此类,对于了解soap,和编写servlet的自动测试代码都有很大的帮助。
    下面的代码简单描述了如何使用HttpURLConnection发起这两种请求,以及传递参数的方法:
    1. package com.service;



    2. import java.io.BufferedReader;

    3. import java.io.DataOutputStream;

    4. import java.io.IOException;

    5. import java.io.InputStreamReader;

    6. import java.net.HttpURLConnection;

    7. import java.net.URL;

    8. import java.net.URLEncoder;



    9. public class HttpInvoker {



    10. public static final String GET_URL = " http://localhost:8080/demo/ ";


    11. public static final String POST_URL = " http://localhost:8080/demo/ ";


    12. public static void readContentFromGet() throws IOException {

    13. // 拼凑get请求的URL字串,使用URLEncoder.encode对特殊和不可见字符进行编码

    14. String getURL = GET_URL + " ?username= "

    15. + URLEncoder.encode("fat man", " utf-8 ");

    16. URL getUrl = new URL(getURL);

    17. // 根据拼凑的URL,打开连接,URL.openConnection()函数会根据 URL的类型,返回不同的URLConnection子类的对象,在这里我们的URL是一个http,因此它实际上返回的是HttpURLConnection

    18. HttpURLConnection connection = (HttpURLConnection) getUrl.openConnection();

    19. // 建立与服务器的连接,并未发送数据

    20. connection.connect();

    21. // 发送数据到服务器并使用Reader读取返回的数据

    22. BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));

    23. System.out.println(" ============================= ");

    24. System.out.println(" Contents of get request ");

    25. System.out.println(" ============================= ");

    26. String lines;

    27. while ((lines = reader.readLine()) != null) {

    28. System.out.println(lines);

    29. }

    30. reader.close();

    31. // 断开连接

    32. connection.disconnect();

    33. System.out.println(" ============================= ");

    34. System.out.println(" Contents of get request ends ");

    35. System.out.println(" ============================= ");

    36. }



    37. public static void readContentFromPost() throws IOException {

    38. // Post请求的url,与get不同的是不需要带参数

    39. URL postUrl = new URL(POST_URL);

    40. // 打开连接

    41. HttpURLConnection connection = (HttpURLConnection) postUrl.openConnection();

    42. //打开读写属性,默认均为false

    43. connection.setDoOutput(true);

    44.         connection.setDoInput(true);

    45. // 设置请求方式,默认为GET

    46. connection.setRequestMethod(" POST ");

    47. // Post 请求不能使用缓存

    48. connection.setUseCaches(false);

    49. // URLConnection.setFollowRedirects是static 函数,作用于所有的URLConnection对象。

    50. // connection.setFollowRedirects(true);

    51. //URLConnection.setInstanceFollowRedirects 是成员函数,仅作用于当前函数

    52. connection.setInstanceFollowRedirects(true);

    53. // 配置连接的Content-type,配置为application/x- www-form-urlencoded的意思是正文是urlencoded编码过的form参数,下面我们可以看到我们对正文内容使用URLEncoder.encode进行编码

    54. connection.setRequestProperty(" Content-Type ",

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

    56. // 连接,从postUrl.openConnection()至此的配置必须要在 connect之前完成,

    57. // 要注意的是connection.getOutputStream()会隐含的进行调用 connect(),所以这里可以省略

    58. //connection.connect();

    59. DataOutputStream out = new DataOutputStream(connection

    60. .getOutputStream());

    61. //正文内容其实跟get的URL中'?'后的参数字符串一致

    62. String content = " firstname= "+URLEncoder.encode(" 一个大肥人 ", " utf-8 ");

    63. // DataOutputStream.writeBytes将字符串中的16位的 unicode字符以8位的字符形式写道流里面

    64. out.writeBytes(content);

    65. out.flush();

    66. out.close(); // flush and close

    67. BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));

    68. String line;

    69. System.out.println(" ============================= ");

    70. System.out.println(" Contents of post request ");

    71. System.out.println(" ============================= ");

    72. while ((line = reader.readLine()) != null) {

    73. System.out.println(line);

    74. }

    75. System.out.println(" ============================= ");

    76. System.out.println(" Contents of post request ends ");

    77. System.out.println(" ============================= ");

    78. reader.close();

    79. //connection.disconnect();

    80. }



    81. public static void main(String[] args) {

    82. // TODO Auto-generated method stub

    83. try {

    84. readContentFromGet();

    85. readContentFromPost();

    86. } catch (IOException e) {

    87. // TODO Auto-generated catch block

    88. e.printStackTrace();

    89. }

    90. }

    91. }
    复制代码
    上面的readContentFromGet() 函数产生了一个get请求,传给servlet一个username参数,值为"fat man"。
    readContentFromPost() 函数产生了一个post请求,传给servlet一个firstname参数,值为"一个大肥人"。
    HttpURLConnection.connect函数,实际上只是建立了一个与服务器的 tcp连接,并没有实际发送http请求。无论是post还是get,http请求实际上直到 HttpURLConnection .getInputStream()这个函数里面才正式发送出去。

    在 readContentFromPost() 中,顺序是重中之重,对connection对象的一切配置(那一堆set函数)都必须要在connect()函数执行之前完成。而对 outputStream的写操作,又必须要在inputStream的读操作之前。这些顺序实际上是由http请求的格式决定的。

    http请求实际上由两部分组成,一个是 http头(head),所有关于此次http请求的配置都在http头里面定义,一个是正文(content),在connect()函数里面,会根据 HttpURLConnection对象的配置值生成http头,因此在调用connect函数之前,就必须把所有的配置准备好。

    紧接着http头的是http请求的正文,正文的内容通过outputStream写入,实际上outputStream不是一个网络流,充其量是个字符串流,往里面写入的东西不会立即发送到网络,而是在流关闭后,根据输入的内容生成http正文。

    至此,http请求的东西已经准备就绪。在 getInputStream()函数调用的时候,就会把准备好的http请求正式发送到服务器了,然后返回一个输入流,用于读取服务器对于此次http 请求的返回信息。由于http请求在getInputStream的时候已经发送出去了(包括http头和正文),因此在 getInputStream()函数之后对connection对象进行设置(对http头的信息进行修改)或者写入outputStream(对正文进行修改)都是没有意义的了,甚至执行这些操作可能会导致异常的发生
    展开全文
  • Java发送HTTP请求

    2019-12-26 20:17:14
    Java实现发送HTTP请求,包含GET、POST、POST(json格式参数) package com.chenyi.quickstart.common; import java.io.*; import java.net.HttpURLConnection; import java.net.URL; import java.util.Map; /** *...

    Java实现发送HTTP请求,包含GET、POST、POST(json格式参数)

    package com.chenyi.quickstart.common;
    
    import java.io.*;
    import java.net.HttpURLConnection;
    import java.net.URL;
    import java.util.Map;
    
    /**
     * HTTP请求工具类
     * GET、POST、POST(JSON格式参数)
     *
     * @author chenyi
     * date: create on 2019/4/27
     */
    public class HttpUtil {
        /**
         * 发送GET请求
         *
         * @param requestUrl 发送请求的URL
         * @param params     param1=value1&param2=value2
         * @return 远程资源响应结果 local-Error:本地请求错误
         */
        public static String getRequest(String requestUrl, String params) {
            requestUrl = requestUrl + "?" + params;
            return HttpUtil.getGeneralUrl(requestUrl);
        }
    
        /**
         * 发送 POST 请求 JSON格式
         *
         * @param requestUrl 请求地址
         * @param jsonParams 请求参数 JSON格式
         * @return 远程资源响应结果 local-Error:本地请求错误
         */
        public static String postJson(String requestUrl, String jsonParams) {
            // 字符集
            String encoding = "utf-8";
            //数据格式
            String contentType = "application/json";
            return HttpUtil.postGeneralUrl(requestUrl, contentType, jsonParams, encoding);
        }
    
        /**
         * 发送POST请求
         *
         * @param requestUrl 请求URL地址
         * @param params     Map类型的参数
         * @return 远程资源响应结果 local-Error:本地请求错误
         */
        public static String postRequest(String requestUrl, Map<String, String> params) {
            String contentType = "application/x-www-form-urlencoded";
            String encoding = "utf-8";
            String paramsStr = packParams(params);
            return HttpUtil.postGeneralUrl(requestUrl, contentType, paramsStr, encoding);
        }
    
        /**
         * 发送POST请求
         *
         * @param requestUrl 请求URL地址
         * @param params     param1=value1&param2=value2
         * @return 远程资源响应结果 local-Error:本地请求错误
         */
        public static String postRequest(String requestUrl, String params) {
            String contentType = "application/x-www-form-urlencoded";
            String encoding = "utf-8";
            return HttpUtil.postGeneralUrl(requestUrl, contentType, params, encoding);
        }
    
        /**
         * 拼接参数 Http参数
         */
        private static String packParams(Map<String, String> paramMap) {
            //参数
            StringBuilder params = new StringBuilder();
            //遍历添加参数
            for (Map.Entry<String, String> entry : paramMap.entrySet()) {
                params.append(entry.getKey()).append("=").append(entry.getValue()).append("&");
            }
            return params.toString().substring(0, params.length() - 1);
        }
    
        /**
         * 通用的GET请求
         *
         * @param generalUrl 发送请求的URL
         * @return 远程资源响应结果
         */
        private static String getGeneralUrl(String generalUrl) {
            InputStreamReader inputStreamReader = null;
            BufferedReader bufferedReader = null;
            try {
                URL url = new URL(generalUrl);
                // 打开和URL之间的连接
                HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                // 设置通用的请求属性
                connection.setRequestProperty("Connection", "Keep-Alive");
                // 建立实际的连接
                connection.connect();
                inputStreamReader = new InputStreamReader(connection.getInputStream(), "utf-8");
                bufferedReader = new BufferedReader(inputStreamReader);
                StringBuilder result = new StringBuilder();
                String textLine;
                while ((textLine = bufferedReader.readLine()) != null) {
                    result.append(textLine);
                }
                return result.toString();
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                //关闭输出流、输入流
                if (bufferedReader != null) {
                    try {
                        bufferedReader.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if (inputStreamReader != null) {
                    try {
                        inputStreamReader.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
            return "local-Error";
        }
    
        /**
         * 通用的POST请求
         *
         * @param generalUrl  请求地址
         * @param contentType 请求类型
         * @param params      参数
         * @param encoding    字符编码
         * @return 远程资源响应结果 local-Error:本地请求错误
         */
        private static String postGeneralUrl(String generalUrl, String contentType, String params, String encoding) {
            OutputStreamWriter out = null;
            InputStreamReader inputStreamReader = null;
            BufferedReader bufferedReader = null;
            try {
                URL url = new URL(generalUrl);
                // 打开和URL之间的连接
                HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                //设置请求方式为POST
                connection.setRequestMethod("POST");
                // 设置通用的请求属性
                //POST请求的Content-Type 为: application/x-www-form-urlencoded
                connection.setRequestProperty("Content-Type", contentType);
                connection.setRequestProperty("Connection", "Keep-Alive");
                connection.setUseCaches(false);
                // 发送POST请求必须设置如下两行
                connection.setDoOutput(true);
                connection.setDoInput(true);
                // 得到请求的输出流对象
                // 获取URLConnection对象对应的输出流
                out = new OutputStreamWriter(connection.getOutputStream(), "UTF-8");
                // 发送请求参数
                out.write(params);
                // flush输出流的缓冲
                out.flush();
                // 建立实际的连接
                connection.connect();
                inputStreamReader = new InputStreamReader(connection.getInputStream(), encoding);
                bufferedReader = new BufferedReader(inputStreamReader);
                StringBuilder result = new StringBuilder();
                String textLine;
                while ((textLine = bufferedReader.readLine()) != null) {
                    result.append(textLine);
                }
                return result.toString();
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                //关闭输出流、输入流
                if (bufferedReader != null) {
                    try {
                        bufferedReader.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if (inputStreamReader != null) {
                    try {
                        inputStreamReader.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if (out != null) {
                    try {
                        out.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
            return "local-Error";
        }
    }
    
    
    展开全文
  • Java发送HTTP 请求

    千次阅读 2019-03-19 15:29:25
    因为是http请求,所有发送post 和get 请求的demo都有在下方贴出,包括怎么测试,大家可直接 copy到自己的项目中使用。 正文 使用须知 为了避免大家引错包我把依赖和涉及到包路径给大家 import java.net....

    前言

    请求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请求

    千次阅读 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请求

    2021-01-21 17:12:33
     下面为大家提供一个Java发送http请求的工具类 HttpRequest.java package org.javahttp.test; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java....

空空如也

空空如也

1 2 3 4 5 ... 20
收藏数 7,298
精华内容 2,919
关键字:

java发送http请求

java 订阅