httpExchange写的http post接口,通过get一个url,返回json,再通过接口返回。在本地都能用postman通过,但是放到服务器上就不通。
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import java.io.OutputStream;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
/**
* 处理/myserver路径请求的处理器类
*/
public class jbxx implements HttpHandler {
@Override
public void handle(HttpExchange httpExchange) {
try {
StringBuilder responseText = new StringBuilder();
responseText.append(getRequestParam(httpExchange));
handleResponse(httpExchange, responseText.toString());
} catch (Exception ex) {
ex.printStackTrace();
}
}
/**
* 获取请求参数
* @param httpExchange
* @throws Exception
*/
private JSONObject getRequestParam(HttpExchange httpExchange) throws Exception {
String paramStr = "";
paramStr = httpExchange.getRequestURI().getQuery();
String[] s1=paramStr.split("=");
JSONObject obj4=null;
if(s1[0].equals("sfz")){
tool tool = new tool();
String url ="";
String timeStamp = Long.toString(System.currentTimeMillis() / 100000);
String param ="appId=8&appName=DExchange&timeStamp="+timeStamp;
String a = tool.sendGet(url,param);
JSONObject obj= JSON.parseObject(a);
String appcode =obj.getString("data");
String url2=url;
String bm = tool.bm(s1[1]);
String param2 ="zjhm="+bm+"&appCode="+appcode+"" +
"&apiToken=88";
String b = tool.sendGet(url2,param2);
JSONObject obj2= JSON.parseObject(b);
JSONArray obj3= JSON.parseArray(obj2.getString("data"));
if (obj3.size() == 0) {
String resultMsg ="{\"resultMsg\":\"没有查询到对应的信息\"}";
obj4= JSON.parseObject(resultMsg);
}else {
obj4 = JSON.parseObject(obj3.getString(0));
}
}
return obj4;
}
/**
* 处理响应
* @param httpExchange
* @param responsetext
* @throws Exception
*/
private void handleResponse(HttpExchange httpExchange, String responsetext) throws Exception {
//生成html
StringBuilder responseContent = new StringBuilder();
responseContent.append(responsetext);
String responseContentStr = responseContent.toString();
byte[] responseContentByte = responseContentStr.getBytes("utf-8");
//设置响应头,必须在sendResponseHeaders方法之前设置!
httpExchange.getResponseHeaders().add("Content-Type:application/x-www-form-urlencoded", "text/html;charset=utf-8");
//设置响应码和响应体长度,必须在getResponseBody方法之前调用!
httpExchange.sendResponseHeaders(200, responseContentByte.length);
OutputStream out = httpExchange.getResponseBody();
out.write(responseContentByte);
out.flush();
out.close();
}
}