博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Http请求 post get
阅读量:5077 次
发布时间:2019-06-12

本文共 4558 字,大约阅读时间需要 15 分钟。

package com.sprucetec.tms.utils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; /**  * HttpInvoker.  *  * @author Yinqiang Du  * @date 2016/8/11  */ public class HttpInvokerUtils {
/** * 日志. */ private static final Logger LOGGER = LoggerFactory.getLogger(HttpInvokerUtils.class); /** * 发起http get 请求获取返回结果. * * @param getURL 请求路径 . * @return * @throws Exception */ public static void readContentFromGet(String getURL) throws IOException {
// 拼凑get请求的URL字串,使用URLEncoder.encode对特殊和不可见字符进行编码 URL getUrl = new URL(getURL); // 根据拼凑的URL,打开连接,URL.openConnection函数会根据 URL的类型, // 返回不同的URLConnection子类的对象,这里URL是一个http,因此实际返回的是HttpURLConnection HttpURLConnection connection = (HttpURLConnection) getUrl .openConnection(); // 进行连接,但是实际上get request要在下一句的 connection.getInputStream()函数中才会真正发到 // 服务器 connection.connect(); // 取得输入流,并使用Reader读取 BufferedReader reader = new BufferedReader(new InputStreamReader( connection.getInputStream())); System.out.println(" ============================= "); System.out.println(" Contents of get request "); System.out.println(" ============================= "); String lines; while ((lines = reader.readLine()) != null) {
System.out.println(lines); } reader.close(); // 断开连接 connection.disconnect(); System.out.println(" ============================= "); System.out.println(" Contents of get request ends "); System.out.println(" ============================= "); } /** * 发起http post 请求获取返回结果. * * @param urlStr 请求路径 . * @param requestParamsJson json字符串. * @return * @throws Exception */ public static void sendRequest(String urlStr, String requestParamsJson) throws Exception {
BufferedOutputStream bufOutPut = null; BufferedReader bufferedReader = null; HttpURLConnection httpConn = null; try {
URL url = new URL(urlStr); httpConn = (HttpURLConnection) url.openConnection(); httpConn.setDoInput(true); // 设置是否从httpUrlConnection读入,默认情况下是true; httpConn.setDoOutput(true); // 设置是否向httpUrlConnection输出,因为这个是post请求,参数要放在http正文内,因此需要设为true, 默认情况下是false; httpConn.setRequestMethod("POST");// 设定请求的方法为"POST",默认是GET httpConn.setAllowUserInteraction(false); //是否允许用户交互 httpConn.setUseCaches(false); // Post 请求不能使用缓存 httpConn.setInstanceFollowRedirects(true); httpConn.setRequestProperty("Accept-Charset", "UTF-8"); httpConn.setRequestProperty("Connection", "Keep-Alive");// 维持长连接 httpConn.setRequestProperty("Content-Type", "application/json"); // 设定传送的内容类型是可序列化的java对象 // 此处getOutputStream会隐含的进行connect(即:如同调用上面的connect()方法, bufOutPut = new BufferedOutputStream(httpConn.getOutputStream()); httpConn.connect(); byte[] bdat = requestParamsJson.getBytes("UTF-8");// 解决中文乱码问题 bufOutPut.write(bdat, 0, bdat.length); bufOutPut.flush(); // 根据ResponseCode判断连接是否成功 int responseCode = httpConn.getResponseCode(); if (responseCode != 200) {
LOGGER.error(" Error===" + responseCode); } else {
LOGGER.info("Post Success!"); } // 定义BufferedReader输入流来读取URL的ResponseData bufferedReader = new BufferedReader(new InputStreamReader(httpConn.getInputStream())); String line; while ((line = bufferedReader.readLine()) != null) {
System.out.println(line); } } catch (Exception e) {
LOGGER.error("send post request error!" + e); } finally {
httpConn.disconnect(); // 断开连接 try {
if (bufOutPut != null) {
bufOutPut.close(); } if (bufferedReader != null) {
bufferedReader.close(); } } catch (IOException ex) {
ex.printStackTrace(); } } } }

转载于:https://www.cnblogs.com/duyinqiang/p/5760505.html

你可能感兴趣的文章
OpenNI2安装
查看>>
[Leetcode] Valid Parentheses
查看>>
[8.1] Triple Step
查看>>
JAVA网络编程
查看>>
《DSP using MATLAB》示例Example7.4
查看>>
tcp断开过程
查看>>
手机工作平台的搭建
查看>>
[CareerCup] 9.8 Represent N Cents 组成N分钱
查看>>
POJ - 1330 Nearest Common Ancestors(dfs+ST在线算法|LCA倍增法)
查看>>
MD5,sha1加密工具类
查看>>
zigbee之MAC地址发送
查看>>
第八课 ROS的空间描述和变换
查看>>
文件拷贝
查看>>
Object Builder Application Block
查看>>
hibernate入门--->张国亮总结第二季
查看>>
从Windows迁移SQL Server到Linux
查看>>
IOS开发之实现App消息推送
查看>>
Workspace defines a VM that does not contain a valid jre/lib/rt.jar: C:\Program Files\Java\jre7
查看>>
java多线程有哪些实际的应用场景?
查看>>
动态分配内存-realloc
查看>>