HTTP送信java代码,用HttpUrl来完成HTTP发送报文接受报文!
import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import org.apache.struts.util.MessageResources;
/**
* 向指定URL里送出HTTP/HTTPS报文
* TODO To change the template for this generated type comment go to Window -
* Preferences - Java - Code Style - Code Templates
*/
public class SendHttpReq {
static final String AUTH = "auth=";
// SSO timer值
private static final String ssoTimer = "ssoTimer";
public static String sendHttps(String sendUrl, String query)
throws MalformedURLException, IOException{
try {
//指定代理服务器地址以及端口
//System.setProperty("https.proxyHost", "web.nrinetcom.co.jp");
//System.setProperty("https.proxyPort", "8080");
URL url = new URL(sendUrl);
HttpURLConnection hCon = (HttpURLConnection) url.openConnection();
/**
* 从配置文件里读取默认连接时间微秒数
*/
MessageResources def = MessageResources
.getMessageResources("ko_def");
int sso_timer = Integer.parseInt(def.getMessage(ssoTimer));
//hCon.setConnectTimeout(sso_timer);
System.setProperty("sun.net.client.defaultConnectTimeout", def.getMessage(ssoTimer));
//设定方法的提交方式
hCon.setRequestMethod("POST");
//指定HTTP头
//hCon.setRequestProperty("","");
hCon.setDoOutput(true);//POST可能
OutputStream os = hCon.getOutputStream();//取得POST用的OutputStream
PrintStream ps = new PrintStream(os);
ps.print(query);//把数据POST出去
//用Stream取得返回的HTML文件
BufferedInputStream in = new BufferedInputStream(hCon
.getInputStream());
ByteArrayOutputStream byteout = new ByteArrayOutputStream();
//用OutputStream来接收
byte bb[] = new byte[1024];
int length = 0;
while ((length = in.read(bb, 0, bb.length)) != -1) {
byteout.write(bb, 0, length);
}
//用文本方式来接收
String ret = byteout.toString();
in.close();
byteout.close();
return ret;
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
throw e;
} catch (IOException e) {
// TODO Auto-generated catch block
throw e;
}
}
/**
* 结果判断出来
*
* @param res
* @return 0:成功 1:失敗 9:System error等 99:对方服务器停止
*/
public static int isTradePass(String res) {
try {
if (res != null && res.length() > 0) {
if (res.lastIndexOf(AUTH) > -1) {
String ret = res.substring(res.indexOf(AUTH)
+ AUTH.length(), res.lastIndexOf(AUTH)
+ AUTH.length() + 1);
System.out.println(ret);
return Integer.parseInt(ret);
}
}
} catch (Exception e) {//Exception发生时"99"返回
//log不打印
}
return 99;
}
}
import java.io.IOException;
import java.net.MalformedURLException;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import javax.crypto.NoSuchPaddingException;
import jp.co.nri.x1.common.ApplicationException;
import jp.co.nri.x1.common.FrontConnectFailureException;
import jp.co.nri.x1.common.util.SendHttpReq;
import org.apache.struts.util.MessageResources;
/**
*
* 对指定的参数进行暗号话,向对方服务器发送request
* @version 1.0 2007/03/27
*
*/
public class SendReqestToFront {
//key对象
private static KeyContainer container = null;
//key文件的
private static final String key = "SSO.key.file";
// //SSO用的时间值
// private static final String ssoTimer = "ssoTimer";
/**
*
* 对方服务器的Servlet调用处理
* @param 送信类型
* @param Request参数
* @throws ApplicationException
* 送信/暗号化失敗的场合
*
* @return Response数据
*/
public static String sendReq(String url, String query, Map inParams) throws ApplicationException {
try {
/**
* 从配置文件里取得key文件名
*/
MessageResources settings = MessageResources
.getMessageResources("AplicationEnvironment");
String fileName = settings.getMessage(key);
// /**
// * 从属性配置文件里读取SSO timer值
// */
// MessageResources def = MessageResources
// .getMessageResources("ko_def");
// int sso_timer = Integer.parseInt(def.getMessage(ssoTimer));
// 暗号化对象参数用的intance生成
Map params = CipherUtil.createParametersMap();
Set set = inParams.keySet();
Iterator it = set.iterator();
while(it.hasNext()){
String name = (String)it.next();
params.put(name,inParams.get(name));
}
//从key文件生成key内容
if (container == null) {
container = CipherUtil.getKeyContainer(fileName);
}
// 防止改窜用的hash生成
final String hash = CipherUtil.createHash(container.getHASH_KEY(),
params);
// 暗号化
final String encrypt = CipherUtil.encrypt(container.getAES_KEY(),
container.getIv(), params);
query = query + "&hs=" + hash + "&value=" + encrypt;
//query = query + "&hash=" + hash + "&value=" + encrypt;
System.out.println("##########url" + url);
System.out.println("##########query" + query);
return SendHttpReq.sendHttps(url, query);
//Exception
//FrontConnectFailureException発生時のハンドリングをstruts-configに追記も必要です。
}catch(Exception e){
throw e;
}
}
/**
* 从key文件读取生成key对象
*/
public void loadKeyFile() {
/**
* 从属性文件里取得key文件名
*/
MessageResources settings = MessageResources
.getMessageResources("AplicationEnvironment");
String fileName = settings.getMessage(key);
try {
//取得暗号化code
container = CipherUtil.getKeyContainer(fileName);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
下面的也可以:
URL url = null;
HttpURLConnection httpurlconnection = null;
try {
url = new URL("http://211.147.222.30/se/sseS");
// 以post方式请求
httpurlconnection = (HttpURLConnection) url.openConnection();
httpurlconnection.setConnectTimeout(6000);
httpurlconnection.setReadTimeout(6000);
httpurlconnection.setDoOutput(true);
httpurlconnection.setRequestMethod("POST");
msg=java.net.URLEncoder.encode(msg,"utf-8");
String username = "UserName=user&Password=pwd&SrcNumber=1065&DestTermID="
+ dest+ "&MsgContent=" + msg;
httpurlconnection.getOutputStream().write(
username.getBytes("utf-8"));
httpurlconnection.getOutputStream().flush();
httpurlconnection.getOutputStream().close();
// 获取响应代码
code = httpurlconnection.getResponseCode();
// 获取页面内容
java.io.InputStream in = httpurlconnection.getInputStream();
java.io.BufferedReader breader = new BufferedReader(
new InputStreamReader(in, "gb2312"));
String str = breader.readLine();
while (str != null) {
resp+=str;
str= breader.readLine();
}
} catch (Exception e) {
resp="err";
} finally {
if (httpurlconnection != null)
httpurlconnection.disconnect();
}
System.setProperty("sun.net.client.defaultReadTimeout", "5000");//jdk1.5以前的版本,用此方法。默认是毫秒
// 如果请求的服务器处理的时间超过5000毫秒的话,则会抛出
//e.toString()的内容是:java.net.SocketTimeoutException:Read timed out
//e.getLocalizedMessage()的内容是:Read timed out
对此的测试方法,可以在请求的URL得出的页面HTML(一般可能是Jsp)里面,写一段花费时间的处理,造成response响应回来需要较长时间,然后通过
这里的System.setProperty设置来测试。