Java实现HttpGet和HttpPost请求

时间:2024-12-21 15:07:14

maven引入JSON处理jar

   <dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.58</version>
</dependency>

maven引入数据源配置,用于log记录

   <dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.0</version>
</dependency>

HttpGet和HttpPost请求


import com.alibaba.druid.support.logging.Log;
import com.alibaba.druid.support.logging.LogFactory;
import com.alibaba.fastjson.JSONObject; import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.sql.SQLOutput;
import java.util.Map; public class ReqHttp { private static final Log logger = LogFactory.getLog(ReqHttp.class); public static JSONObject get(String reqUrl,Map<String,Object> paramMap) throws IOException { StringBuffer param =new StringBuffer(); for(Map.Entry<String,Object> en:paramMap.entrySet()){
param.append(en.getKey()+"="+en.getValue()+"&");
} BufferedReader responseReader = null; String urlPath = ReqStatUrl.DOMAIN_URL + reqUrl+"?"+param.toString();
try {
//建立连接
URL url = new URL(urlPath);
HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
//设置参数
httpConn.setDoOutput(true); //需要输出
httpConn.setDoInput(true); //需要输入
httpConn.setUseCaches(false); //不允许缓存
httpConn.setRequestMethod("GET"); //设置GET方式连接
httpConn.setRequestProperty("Content-Type", "application/json;charset=utf-8");//流信息 可以传输图片音频等信息
httpConn.setRequestProperty("Charset", "UTF-8");
httpConn.setRequestProperty("entCode", ReqStatHeader.entCode);//参数常量
httpConn.setRequestProperty("tokenId", ReqStatHeader.tokenId);//参数常量
httpConn.setConnectTimeout(30000);
httpConn.setReadTimeout(30000); //连接,也可以不用明文connect,使用下面的httpConn.getOutputStream()会自动connect
httpConn.connect(); //获得响应状态
int resultCode = httpConn.getResponseCode();
if (HttpURLConnection.HTTP_OK == resultCode) {
StringBuffer sb = new StringBuffer();
String readLine = new String();
responseReader = new BufferedReader(new InputStreamReader(httpConn.getInputStream(), "UTF-8"));
while ((readLine = responseReader.readLine()) != null) {
sb.append(readLine).append("\n");
} System.out.println(sb.toString());
logger.info(sb.toString());
JSONObject json = JSONObject.parseObject(sb.toString(),JSONObject.class);
return json;
} } catch (Exception e) {
logger.error("get 请求失败:"+urlPath);
} finally { if(null != responseReader) responseReader.close(); }
return null;
} public static JSONObject post(String reqUrl,Map<String,Object> paramMap) throws Exception { BufferedReader responseReader = null;
OutputStream dos= null; String urlPath = ReqStatUrl.DOMAIN_URL + reqUrl;
try {
//建立连接
URL url = new URL(urlPath);
HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
//设置参数
httpConn.setDoOutput(true); //需要输出
httpConn.setDoInput(true); //需要输入
httpConn.setUseCaches(false); //不允许缓存
httpConn.setRequestMethod("POST"); //设置POST方式连接
httpConn.setRequestProperty("Content-Type", "application/json;charset=utf-8");//流信息 可以传输图片音频等信息
httpConn.setRequestProperty("Charset", "UTF-8");
httpConn.setRequestProperty("entCode", ReqStatHeader.entCode);//参数常量
httpConn.setRequestProperty("tokenId", ReqStatHeader.tokenId);//参数常量
httpConn.setConnectTimeout(30000);
httpConn.setReadTimeout(30000); //连接,也可以不用明文connect,使用下面的httpConn.getOutputStream()会自动connect
httpConn.connect();
//建立输入流,向指向的URL传入参数 byte[] jsonObject = JSONObject.toJSONBytes(paramMap); dos = httpConn.getOutputStream();
dos.write(jsonObject);
dos.flush(); //获得响应状态
int resultCode = httpConn.getResponseCode();
if (HttpURLConnection.HTTP_OK == resultCode) {
StringBuffer sb = new StringBuffer();
String readLine = new String();
responseReader = new BufferedReader(new InputStreamReader(httpConn.getInputStream(), "UTF-8"));
while ((readLine = responseReader.readLine()) != null) {
sb.append(readLine).append("\n");
} // System.out.println(sb.toString());
logger.info(sb.toString());
JSONObject json = JSONObject.parseObject(sb.toString(),JSONObject.class);
return json;
} } catch (Exception e) {
logger.error("get 请求失败:"+urlPath);
} finally { if(null != responseReader) responseReader.close();
if(null != dos) dos.close();
}
return null;
} }

常用参数静态引用

public class ReqStatHeader {

    public static String entCode="";
public static String tokenId=""; public static String appCode = "";
public static String secret = ""; }

常用API地址静态引用,便于地址维护

public class ReqStatUrl {

    public static String DOMAIN_URL = "https://www.xxxxx.com/xxxx/xxxx";

    /**
* 认证
*/
public static String AUTH_LOGIN = "/auth/login"; /**
*获取已提交对私报销单据
*/
public static String REPORT_PERSONAL_SUBMITTED= "/report/personal/submitted"; /**
* 获取已提交对私报销单据详情
*/
public static String REPORT_PERSONAL_DETAIL = "/report/personal/detail"; }