package com.doumee.core.utils;
|
|
import com.alibaba.fastjson.JSONObject;
|
import org.apache.commons.codec.binary.Hex;
|
//import org.apache.commons.httpclient.HttpClient;
|
//import org.apache.commons.httpclient.NameValuePair;
|
//import org.apache.commons.httpclient.methods.PostMethod;
|
//import org.apache.commons.httpclient.params.HttpMethodParams;
|
import org.apache.http.HttpEntity;
|
import org.apache.http.HttpResponse;
|
import org.apache.http.HttpStatus;
|
import org.apache.http.client.methods.HttpPost;
|
import org.apache.http.entity.StringEntity;
|
import org.apache.http.impl.client.*;
|
import org.apache.http.util.EntityUtils;
|
|
import java.io.*;
|
import java.lang.reflect.Field;
|
import java.net.HttpURLConnection;
|
import java.net.URL;
|
import java.net.URLConnection;
|
import java.security.MessageDigest;
|
import java.security.NoSuchAlgorithmException;
|
import java.util.HashMap;
|
import java.util.Map;
|
import java.util.UUID;
|
|
public class HttpUtil {
|
public static final String UTF8 = "UTF-8";
|
|
/**
|
* @param urlpath
|
* @throws IOException
|
* @throws UnsupportedEncodingException
|
*/
|
public static String postRequestConn(String urlpath) throws UnsupportedEncodingException, IOException {
|
String sendString = "";
|
|
// 创建url对象
|
URL url = new URL(urlpath);
|
|
// 打开url连接
|
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
|
connection.setRequestProperty("Content-Type", "application/octet-stream");
|
// 设置url请求方式 ‘get’ 或者 ‘post’
|
connection.setRequestMethod("POST");
|
connection.setDoOutput(true);
|
connection.setDoInput(true);
|
connection.setUseCaches(true);
|
connection.setConnectTimeout(3000);
|
connection.setReadTimeout(10000);
|
connection.setRequestProperty("Charset", "UTF-8");
|
int responseCode = connection.getResponseCode();
|
if (HttpURLConnection.HTTP_OK == responseCode) {
|
String readLine;
|
BufferedReader responseReader;
|
StringBuffer sb = new StringBuffer();
|
responseReader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
|
while ((readLine = responseReader.readLine()) != null) {
|
sb.append(readLine).append("\n");
|
}
|
responseReader.close();
|
sendString = sb.toString();
|
// httpConn.disconnect();
|
} else {
|
System.out.println("error");
|
}
|
|
return sendString;
|
}
|
|
/**
|
* @param urlPath
|
* @param json
|
* @throws IOException
|
* @throws UnsupportedEncodingException
|
*/
|
public static String postRequestConn(String urlPath, String json,String tokenStr) throws UnsupportedEncodingException, IOException {
|
String sendString = "";
|
// try {
|
URL url;
|
url = new URL(urlPath);
|
HttpURLConnection httpConn;
|
httpConn = (HttpURLConnection) url.openConnection();
|
// httpConn.connect();
|
httpConn.setDoOutput(true);
|
httpConn.setDoInput(true);
|
httpConn.setRequestMethod("POST");
|
httpConn.setUseCaches(false);
|
httpConn.setInstanceFollowRedirects(true);
|
httpConn.setRequestProperty("Content-Type", "application/json");
|
httpConn.setRequestProperty("accept", "application/json");
|
httpConn.setRequestProperty("X-Judge-Server-Token",getSHA256Str(tokenStr));
|
httpConn.setConnectTimeout(10000);
|
httpConn.setReadTimeout(10000);
|
httpConn.connect();
|
OutputStream out = httpConn.getOutputStream();
|
byte[] data = (json.toString()).getBytes("UTF-8");
|
out.write(data, 0, data.length);
|
out.flush();
|
out.close();
|
int responseCode = httpConn.getResponseCode();
|
if (HttpURLConnection.HTTP_OK == responseCode) {
|
String readLine;
|
BufferedReader responseReader;
|
StringBuffer sb = new StringBuffer();
|
responseReader = new BufferedReader(new InputStreamReader(httpConn.getInputStream(), "UTF-8"));
|
while ((readLine = responseReader.readLine()) != null) {
|
sb.append(readLine);
|
}
|
responseReader.close();
|
sendString = sb.toString();
|
// httpConn.disconnect();
|
} else {
|
System.out.println("error");
|
}
|
return sendString;
|
}
|
|
public static String doPost(String url,JSONObject json,String token) {
|
DefaultHttpClient client = new DefaultHttpClient();
|
HttpPost post = new HttpPost(url);
|
String response = null;
|
try {
|
post.addHeader("Content-Type", "application/json; charset=utf-8");
|
post.addHeader("X-Judge-Server-Token",getSHA256Str(token));
|
StringEntity s = new StringEntity(json.toString());
|
s.setContentEncoding("UTF-8");
|
s.setContentType("application/json");//发送json数据需要设置contentType
|
post.setEntity(s);
|
HttpResponse res = client.execute(post);
|
if (res.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
|
HttpEntity entity = res.getEntity();
|
response = EntityUtils.toString(entity);// 返回json格式:
|
}
|
} catch (Exception e) {
|
throw new RuntimeException(e);
|
}
|
// System.out.print(response);
|
return response;
|
}
|
|
//java对象转map
|
public static Map<String, Object> objectToMap(Object obj) throws Exception {
|
if (obj == null) {
|
return null;
|
}
|
Map<String, Object> map = new HashMap<>();
|
Field[] declaredFields = obj.getClass().getDeclaredFields();
|
for (Field field : declaredFields) {
|
field.setAccessible(true);
|
map.put(field.getName(), field.get(obj));
|
}
|
return map;
|
}
|
// public static String doFormPost(String url,JSONObject json) throws Exception{
|
// String response = null;
|
// HttpClient client = new HttpClient();
|
// PostMethod postMethod = new PostMethod(url);
|
// postMethod.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET,"utf-8");
|
// Map<String, Object> params =objectToMap(json);
|
// if(params !=null && params.get("map") !=null ){
|
// HashMap<String,String> map = (HashMap<String, String>) params.get("map");
|
// if(map !=null && !map.isEmpty()){
|
// NameValuePair[] data = new NameValuePair[map.size()];
|
// int i =0;
|
// for(Map.Entry<String,String> entry : map.entrySet()){
|
// data[i] = new NameValuePair(entry.getKey(),entry.getValue());
|
// i++;
|
// }
|
// postMethod.setRequestBody(data);
|
// }
|
// }
|
// try {
|
// client.executeMethod(postMethod);
|
// if(postMethod.getStatusCode() == HttpStatus.SC_OK){
|
// response = postMethod.getResponseBodyAsString();
|
// }
|
// }catch (Exception e){
|
// e.printStackTrace();
|
// }
|
// return response;
|
// }
|
|
|
public static void main(String[] args) throws IOException {
|
// "language_config": sub_config["config"],
|
// "src": code,
|
// "max_cpu_time": self.problem.time_limit,
|
// "max_memory": 1024 * 1024 * self.problem.memory_limit,
|
// "test_case_id": self.problem.test_case_id,
|
// "output": False,
|
// "spj_version": self.problem.spj_version,
|
// "spj_config": spj_config.get("config"),
|
// "spj_compile_config": spj_config.get("compile"),
|
// "spj_src": self.problem.spj_code,
|
// "io_mode": self.problem.io_mode
|
/*
|
{
|
"template": "" ,
|
|
"compile": {
|
"src_name": "main.cpp",
|
"exe_name": "main",
|
"max_cpu_time": 10000,
|
"max_real_time": 20000,
|
"max_memory": 1024 * 1024 * 1024,
|
"compile_command": "/usr/bin/g++ -DONLINE_JUDGE -O2 -w -fmax-errors=3 -std=c++14 {src_path} -lm -o {exe_path}",
|
},
|
"run": {
|
"command": "{exe_path}",
|
"seccomp_rule": {ProblemIOMode.standard: "c_cpp", ProblemIOMode.file: "c_cpp_file_io"},
|
"env": default_env
|
}
|
|
{"config": _cpp_lang_config, "spj": {"compile": _cpp_lang_spj_compile, "config": _cpp_lang_spj_config},
|
"name": "C++", "description": "G++ 5.4", "content_type": "text/x-c++src"},*/
|
JSONObject json =new JSONObject();
|
JSONObject j = new JSONObject();
|
JSONObject spj = new JSONObject();
|
JSONObject sc = new JSONObject();
|
sc.put("src_name","spj-{spj_version}.cpp");
|
sc.put("exe_name","spj-{spj_version}");
|
sc.put("max_cpu_time",10000);
|
sc.put("max_real_time",20000);
|
sc.put("max_memory",1024 * 1024 * 1024);
|
sc.put("compile_command","/usr/bin/g++ -DONLINE_JUDGE -O2 -w -fmax-errors=3 -std=c++14 {src_path} -lm -o {exe_path}");
|
spj.put("compile",sc);
|
JSONObject scc = new JSONObject();
|
scc.put("exe_name","spj-{spj_version}");
|
scc.put("command","{exe_path} {in_file_path} {user_out_file_path}");
|
scc.put("seccomp_rule","c_cpp");
|
spj.put("config",scc);
|
JSONObject compile = new JSONObject();
|
compile.put("src_name", "main.cpp");
|
compile.put("exe_name", "main");
|
compile.put("max_cpu_time", 10000);
|
compile.put("max_real_time", 20000);
|
compile.put("max_memory",1024 * 1024 * 1024);
|
compile.put("compile_command", "/usr/bin/g++ -DONLINE_JUDGE -O2 -w -fmax-errors=3 -std=c++14 {src_path} -lm -o {exe_path}");
|
JSONObject run = new JSONObject();
|
JSONObject sr = new JSONObject();
|
sr.put("Standard IO","c_cpp");
|
sr.put("File IO","c_cpp_file_io");
|
run.put("command", "{exe_path}");
|
run.put("seccomp_rule", sr);
|
run.put("env",new String[]{"LANG=en_US.UTF-8", "LANGUAGE=en_US:en", "LC_ALL=en_US.UTF-8"});
|
JSONObject config = new JSONObject();
|
config.put("template","//PREPEND BEGIN\n" +
|
"#include <iostream>\n" +
|
"//PREPEND END\n" +
|
"\n" +
|
"//TEMPLATE BEGIN\n" +
|
"int add(int a, int b) {\n" +
|
" // Please fill this blank\n" +
|
" return ___________;\n" +
|
"}\n" +
|
"//TEMPLATE END\n" +
|
"\n" +
|
"//APPEND BEGIN\n" +
|
"int main() {\n" +
|
" std::cout << add(1, 2);\n" +
|
" return 0;\n" +
|
"}\n" +
|
"//APPEND END");
|
config.put("run",run);
|
config.put("compile",compile);
|
|
j.put("name","C++");
|
j.put("description","G++ 5.4");
|
j.put("content_type","text/x-c++src");
|
j.put("config",config);
|
j.put("spj",spj);
|
|
json.put("language_config",j.get("config"));
|
json.put("src","#include <stdio.h> // puts \n" +
|
"int main(){\n" +
|
" puts(\"Hello,World!\");// 输出\n" +
|
"}");
|
json.put("max_cpu_time",1000);
|
json.put("max_memory",1024*1024*64);
|
json.put("test_case_id","2b7e2f6a801b6c00388e717ae11b6f57");
|
// json.put("output",Boolean.FALSE);
|
// json.put("spj_version","");
|
// json.put("spj_config","");
|
// json.put("spj_compile_config","");
|
// json.put("spj_src","");
|
// json.put("io_mode","{\"input\": \"input.in\", \"output\": \"output.out\", \"io_mode\": \"Standard IO\"}");
|
|
System.out.println(json.toJSONString());
|
System.out.println(postRequestConn("http://47.100.55.21:8080/judge",json.toJSONString(),"3c8e8bd79d66259c46d8a3d057278dc8"));
|
}
|
|
public static String getSHA256Str(String str) {
|
MessageDigest messageDigest;
|
String encdeStr = "";
|
try {
|
messageDigest = MessageDigest.getInstance("SHA-256");
|
byte[] hash = messageDigest.digest(str.getBytes("UTF-8"));
|
encdeStr = Hex.encodeHexString(hash);
|
} catch (NoSuchAlgorithmException e) {
|
e.printStackTrace();
|
} catch (UnsupportedEncodingException e) {
|
e.printStackTrace();
|
}
|
return encdeStr;
|
}
|
|
|
|
/**
|
* 下载二维码图片文件,
|
*
|
* @param urlString
|
* @return 临时文件夹地址
|
* @throws Exception
|
*/
|
|
public static String downloadQrcode(String urlString) throws Exception {
|
String savePath = System.getProperty("java.io.tmpdir");
|
String nfix = ".jpg";// 文件后缀名
|
String tempName = UUID.randomUUID().toString() + nfix;// 临时文件名
|
|
// ----------------图片下载开始---------------
|
// 构造URL
|
URL url = new URL(urlString);
|
// 打开连接
|
URLConnection con = url.openConnection();
|
// 设置请求超时为5s
|
con.setConnectTimeout(5 * 1000);
|
// 输入流
|
InputStream is = con.getInputStream();
|
|
// 1K的数据缓冲
|
byte[] bs = new byte[1024];
|
// 读取到的数据长度
|
int len;
|
// 输出的文件流
|
File sf = new File(savePath);
|
if (!sf.exists()) {
|
sf.mkdirs();
|
}
|
String tempFilePath = sf.getPath() + "\\" + tempName;
|
OutputStream os = new FileOutputStream(tempFilePath);
|
// 开始读取
|
while ((len = is.read(bs)) != -1) {
|
os.write(bs, 0, len);
|
}
|
// 完毕,关闭所有链接
|
os.close();
|
is.close();
|
// -------------------图片下载完毕------------------
|
|
return tempFilePath;
|
}
|
}
|