oracle10g的oralceJVM支撑java1.4. 这让我们能用java做一些ps/sql不容易处理的任务,比如访问http资源等。这篇文章写个实例。首先创建java源码,所有method必须是static public:
CREATE OR REPLACE AND RESOLVE JAVA SOURCE NAMED WORKSUPPORT."zgdx/tool/Util" AS
package zgdx.tool;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
public class Util {
static public String post(String s, String content) throws UnsupportedEncodingException {
try{
URL url= new URL(s);
HttpURLConnection uconn = null;
uconn = (HttpURLConnection)url.openConnection();
uconn.setRequestMethod("POST");
//uconn.setConnectTimeout(4000); //1.5
//uconn.setRequestProperty("Connection", "close");
uconn.setRequestProperty("Content-type", "application/x-www-form-urlencoded"); // text/plain;charset=\"utf-8\"
uconn.setRequestProperty("user-agent", "Mozilla/5.0 (Windows; U; Windows NT 5.1; zh-CN; rv:1.8.1.8) Gecko/20071008 Firefox/2.0.0.8");
//Content-type: text/xml;charset="utf-8"Soapaction: ""Accept: text/xml, multipart/related, text/html, image/gif, image/jpeg, *; q=.2, */*; q=.2User-Agent: JAX-WS RI 2.1.6 in JDK 6Host: 61.139.44.236Connection: keep-aliveContent-Length: 811
uconn.setRequestProperty("Accept", "*/*");
uconn.setRequestProperty("Host", java.net.InetAddress.getLocalHost().getHostAddress());
byte[] byteContent = content.getBytes(); //"utf-8"
System.out.println("write bytes len="+ byteContent.length);
uconn.setRequestProperty("Content-Length", String.valueOf(byteContent.length));
uconn.setDoOutput(true);
uconn.connect();
OutputStream out = uconn.getOutputStream();
out.write(byteContent);
out.close();
int res=0;
res = uconn.getResponseCode();
//System.out.println("\t receive response:");
if(res!=200){
return "responseCode="+res+": "+ uconn.getResponseMessage();
}
return null;
}catch(IOException e){
//throw new RuntimeException(e);
e.printStackTrace();
return e.getMessage();
}
}
}
/
如果是单独的java文件,可用oracle客户端的loadjava装载。
想把post包装成oracle function, 需要
CREATE OR REPLACE PACKAGE WORKSUPPORT."ZGDX/TOOL/UTIL" AS
FUNCTION post(Param1 VARCHAR2, Param2 VARCHAR2)
return VARCHAR2
AS LANGUAGE java NAME 'zgdx.tool.Util.post(java.lang.String, java.lang.String) return java.lang.String';
end;
/
如果使用toad,可用“publish java to ps/sql”工具。
测试:
在test.jsp中
oracle 执行:
declare res varchar2(100); begin res := "ZGDX/TOOL/UTIL".post('http://133.44.8.71:8084/payAfterInstall/test.jsp', 'name=XXX' ); if length(res)>0 then dbms_output.put_line(res); end if; end;