- 通过URL发送Json格式的Http请求
/**
* @Auther: LiuY
* @Date: 2018/5/21 08 48
* @Desc:
* @Version 1.0
*/
import com.alibaba.fastjson.JSONObject;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;
import java.util.Map;
public class HttpSender {
public static String JsonPost(String urlStr,JSONObject obj){
String result = "";
try {
URL url = new URL(urlStr);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setUseCaches(false);
conn.setRequestMethod("POST");
conn.setRequestProperty("contentType", "application/json");
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("Charset", "UTF-8");
byte[] data = (obj.toString()).getBytes();
conn.setRequestProperty("Content-Length", String.valueOf(data.length));
conn.connect();
OutputStream out = conn.getOutputStream();
out.write((obj.toString()).getBytes());
out.flush();
out.close();
if (conn.getResponseCode() == 200) {
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
try {
String line;
while ((line = in.readLine()) != null) {
result += line;
}
} catch (Exception e1) {
e1.printStackTrace();
}
} else {
System.err.println("request: "+urlStr+" param: "+obj.toJSONString()+" failed: "+conn.getResponseCode());
}
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
}
- 遍历时间段调度请求(这里以天为单位,是可以调的)
import com.alibaba.fastjson.JSONObject;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
/**
* @Auther: LiuY
* @Date: 2018/5/21 08 51
* @Desc:
* @Version 1.0
*/
public class TestHttpSender {
public static String URL = "http://localhost:8080//schedule/scheduleService/syncLotteryStaticss";
public static void main(String[] args) {
Calendar start = Calendar.getInstance();
start.set(2018, 0, 1);
Long startTIme = start.getTimeInMillis();
Calendar end = Calendar.getInstance();
end.set(2018, 4, 22);
Long endTime = end.getTimeInMillis();
Long oneDay = 1000 * 60 * 60 * 24l;
Long time = startTIme;
while (time <= endTime) {
Date d = new Date(time);
DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
String date = df.format(d);
JSONObject jsonObject = new JSONObject();
jsonObject.put("date",date);
String result = HttpSender.JsonPost(URL,jsonObject);
String text = "failed";
if("null".equals(result)){
text="success";
}
System.out.println(date+": "+text);
time += oneDay;
}
}
}