/**
*url 请求地址
*jsonStr 请求报文
*timeout 请求该接口超时时间
*/
public static String reqHttpService(String url, String jsonStr ,String timeout) throws Exception{
if(url ==null ){
url ="";
}
if(jsonStr ==null ){
jsonStr ="";
}
long reqTime = System.currentTimeMillis();
// 接口地址
String urlStr = url.trim();
/** 注意:超时时间, 默认为:10000/毫秒*/
if("".equals(timeout)){
timeout = "10000";
}
int readTime ;//超时时间
try{
readTime = Integer.parseInt(timeout);
}catch(Exception a){
readTime =10000;
System.out.println(wsname+",没有超时时间默认设置为:10000,即10秒!");
}
String responseMsg = "";
BufferedReader in =null; // 读取响应输入流
long a = System.currentTimeMillis();
PrintWriter out1 = null;
java.net.HttpURLConnection httpConn = null;
try {
java.net.URL connURL = new java.net.URL(urlStr);
// 打开URL连接
httpConn = (java.net.HttpURLConnection) connURL.openConnection();
// 设置通用属性
httpConn.setRequestProperty("Accept", "*/*");
httpConn.setRequestProperty("Connection", "Keep-Alive");
httpConn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1)");
httpConn.setRequestProperty("content-type", "text/html");
httpConn.setAllowUserInteraction(true);
int callTimeOut = readTime;
// 设置POST方式
httpConn.setRequestMethod("POST");
httpConn.setDoInput(true);
httpConn.setDoOutput(true);
httpConn.setConnectTimeout(callTimeOut);
httpConn.setReadTimeout(callTimeOut);
httpConn.connect();//开始连接请求
// 获取HttpURLConnection对象对应的输出流
out1 = new PrintWriter(httpConn.getOutputStream());
// 发送请求参数
out1.print(jsonStr);
// flush输出流的缓冲
out1.flush();
// 定义BufferedReader输入流来读取URL的响应,设置编码方式
in = new BufferedReader(new InputStreamReader(httpConn.getInputStream(), "UTF-8"));
String line;
// 读取返回的内容
while ((line = in.readLine()) != null) {
responseMsg += line;
}
System.out.println("responseMsg="+responseMsg);
} catch (Exception e) {
responseMsg="";
System.out.println("HTTP方式发送车险报案数据,接口调用异常,错误信息=" + e.toString());
e.printStackTrace();
} finally {
try {
if (out1 != null) {
out1.close();
}
if (in != null) {
in.close();
}
if (httpConn != null) {
httpConn.disconnect();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
long end = System.currentTimeMillis();
System.out.println(DateService.getDateTime()+"接口总用时" + (end -reqTime) / 1000.0 + "秒。");
return responseMsg;
}
POST请求HTTP接口
最新推荐文章于 2024-06-27 16:17:16 发布
![](https://img-home.csdnimg.cn/images/20240711042549.png)