您的位置:首页 > 理论基础 > 计算机网络

java代码模拟页面上传文件至服务器(支持https上传)

2012-12-06 14:05 796 查看
先下载httpclient.jar,包括code.jar。下载地址:http://download.csdn.net/detail/yanning1314/4853021

https上传需要下载 commons-io-2.2.jar 下载地址:http://download.csdn.net/detail/yanning1314/4856933

import java.io.*;
import java.net.URL;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import org.apache.commons.httpclient.*;
import org.apache.commons.httpclient.methods.*;
import org.apache.commons.io.IOUtils;

public class HttpUp {
/**
* URL为http
* @param URLString
* @return
*/
public int access(String URLString) {
try {

StringBuffer response = new StringBuffer();

HttpClient client = new HttpClient();
PostMethod method = new PostMethod(URLString);

// 设置Http Post数据,这里是上传文件
File f = new File("imei.xml");
FileInputStream fi = new FileInputStream(f);
InputStreamRequestEntity fr = new InputStreamRequestEntity(fi);
method.setRequestEntity((RequestEntity) fr);
try {
client.executeMethod(method); // 这一步就把文件上传了
// 下面是读取网站的返回网页,例如上传成功之类的
if (method.getStatusCode() == HttpStatus.SC_OK) {
// 读取为 InputStream,在网页内容数据量大时候推荐使用
BufferedReader reader = new BufferedReader(
new InputStreamReader(method
.getResponseBodyAsStream(), "UTF-8"));
String line;
while ((line = reader.readLine()) != null) {
response.append(line);
}
reader.close();
}
} catch (IOException e) {
System.out.println("执行HTTP Post请求" + URLString + "时,发生异常!");
e.printStackTrace();
} finally {
method.releaseConnection();
}
// System.out.println("--------------------"+response.toString());
if (response.toString().indexOf("imei add success") != -1) {
return 1;
} else {
return -1;
}
} catch (Exception e) {
e.printStackTrace();
return -1;
}
}

private static class TrustAnyTrustManager implements X509TrustManager

{

public void checkClientTrusted(X509Certificate[] chain, String

authType) throws CertificateException {
}

public void checkServerTrusted(X509Certificate[] chain, String

authType) throws CertificateException {
}

public X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[] {};
}
}

private static class TrustAnyHostnameVerifier implements HostnameVerifier {
public boolean verify(String hostname, SSLSession session) {
return true;
}
}
/**
* URL为https
* @param URLString
* @return
*/
public int upload(String URLString) {
int a = -1;
File localFile = new File("imei.xml");
try {
SSLContext sc = SSLContext.getInstance("SSL");
sc.init(null, new TrustManager[] { new TrustAnyTrustManager() },
new java.security.SecureRandom());
URL console = new URL(URLString);

HttpsURLConnection conn = (HttpsURLConnection) console
.openConnection();
conn.setSSLSocketFactory(sc.getSocketFactory());
conn.setHostnameVerifier(new TrustAnyHostnameVerifier());
//            conn.connect();

conn.setRequestProperty("Charset", "UTF-8");
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setRequestMethod("PUT");
OutputStream urlOutputStream = conn.getOutputStream();
FileInputStream fileInputStream = new FileInputStream(localFile);
IOUtils.copy(fileInputStream, urlOutputStream);

StringBuffer response = new StringBuffer();
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream(),"UTF-8"));
String line;
while ((line = in.readLine()) != null) {
response.append(line);
}

fileInputStream.close();
urlOutputStream.close();
int res = conn.getResponseCode();
if (res == 200) {
if (response.toString().indexOf("imei add success") != -1) {
a = 200;
} else {
a = -1;
}
}

} catch (Exception e) {
e.printStackTrace();
}
return a;
}

public static void main(String args[]) {
HttpUp hu = new HttpUp();
hu.upload("https://10.10.10.82:8080/HPDDimei/upload.jsp");
//        hu.access("http://10.10.10.82:8080/axis/aaa.jsp");
}


服务器端接收上传页面upload.jsp

<%@ page  language="java" contentType="text/html; charset=UTF-8"
import = "java.io.*" %>
<%@page import="com.kmi.xml.JavaReader2DOM"%>
<%@page import="java.util.List"%>
<%@page import="com.kmi.pojo.Imei"%>
<%@page import="com.kmi.dao.imp.DaoImp"%>
<%@page import="com.kmi.dao.Dao"%>

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>---接收上传页面---</title>
<link href="css/BasicStyle.css" rel="stylesheet" type="text/css" />
<link href="css/table.css" rel="stylesheet" type="text/css" />
</head>
<body>

<%
String path = request.getSession().getServletContext().getRealPath("/");

String xmlPath = path+"imei.xml";
System.out.println(path);
try
{
PrintWriter pw = new PrintWriter(
new BufferedWriter(new FileWriter(xmlPath)));

ServletInputStream in = request.getInputStream();
int i = in.read();
while (i != -1)
{
pw.print((char) i);
i = in.read();
}
pw.close();
out.println("imei add successs");
}
catch (Exception e)
{
out.println("error,文件生成失败,请查看后台日志");
e.printStackTrace();
}

%>

</body>
</html>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: