java模拟from表单提交https请求(含有文件)

package com.xwtech.util;


import java.io.File;
import java.nio.ByteBuffer;
import java.nio.charset.Charset;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.util.EntityUtils;

/**
 * 模拟表单提交(https)
 * 
 * @author jing
 * 
 */
public class Restful {


/**

* @param url  https请求路径
* @param type  参数
* @param filePath  文件路径
* @return
* @throws NoSuchAlgorithmException
*/
public static String restful(String url, int type, String filePath)
throws NoSuchAlgorithmException {
// client客户端
DefaultHttpClient httpClient = new DefaultHttpClient();
// 设置编码
Charset charset = Charset.forName("UTF-8");
// 格式化打通SSL
httpClient = wrapClient(httpClient);
// post客户端
HttpPost httpPost = new HttpPost(url);
String result = null;
// httpPost.setHeader("Content-Type","application/x-www-form-urlencoded"); 在使用文件上传时候不需要这个header
try {
FileBody bin = new FileBody(new File(filePath));
// 第一种获取reqEntity方法:
// HttpEntity reqEntity
// =MultipartEntityBuilder.create().addPart("config_xml",bin).addPart("type",new StringBody("1")).build();
// 第二种获取reqEntity方法:
MultipartEntity reqEntity = new MultipartEntity();
// xml为请求后台的文件属性名
reqEntity.addPart("config_xml", bin);
// 请求后台的普通参数属性名
reqEntity.addPart("type", new StringBody("1", charset));
// 参数传入
httpPost.setEntity(reqEntity);
HttpResponse response = httpClient.execute(httpPost);
result = EntityUtils.toString(response.getEntity(), "UTF-8");
} catch (Exception e) {
e.printStackTrace();
} finally {
// 释放post连接
httpPost.releaseConnection();
}
return result;
}

/**
* DefaultHttpClient格式化,使之不需要SSL证书也可以打通SSL 如果不格式化会报错:
* javax.net.ssl.SSLPeerUnverifiedException: peer not authenticate
* @param base
* @return
*/
public static DefaultHttpClient wrapClient(DefaultHttpClient base) {
SSLContext sslContext;
try {
sslContext = SSLContext.getInstance("SSL");
sslContext.init(null, new TrustManager[] { new X509TrustManager() {
public X509Certificate[] getAcceptedIssuers() {
return null;
}


public void checkClientTrusted(X509Certificate[] certs,
String authType) {
}


public void checkServerTrusted(X509Certificate[] certs,
String authType) {
}
} }, new SecureRandom());
SSLSocketFactory ssf = new SSLSocketFactory(sslContext,
SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
SchemeRegistry registry = new SchemeRegistry();
registry.register(new Scheme("https", 443, ssf));
ThreadSafeClientConnManager mgr = new ThreadSafeClientConnManager(
registry);
return new DefaultHttpClient(mgr, base.getParams());
} catch (Exception ex) {
ex.printStackTrace();
return null;
}
}

/**
* 当多个文件需要上传时,对文件进行组装
*/
public static void addFileBodyPart(String paramName,
ArrayList<FileBody> fileBodys, MultipartEntity reqEntity) {
if (fileBodys == null || fileBodys.size() < 1 || reqEntity == null
|| paramName == null) {
return;
}
for (FileBody iteam : fileBodys) {
reqEntity.addPart(paramName, iteam);
}
}

/**
* 把unicode编码转化成中文
* @param str
* @return
*/
public static String unicodeToChina(String str) {
Charset set = Charset.forName("UTF-8");
Pattern p = Pattern.compile("\\\\u([0-9a-fA-F]{4})");
Matcher m = p.matcher(str);
int start = 0;
int start2 = 0;
StringBuffer sb = new StringBuffer();
while (m.find(start)) {
start2 = m.start();
if (start2 > start) {
String seg = str.substring(start, start2);
sb.append(seg);
}
String code = m.group(1);
int i = Integer.valueOf(code, 16);
byte[] bb = new byte[4];
bb[0] = (byte) ((i >> 8) & 0xFF);
bb[1] = (byte) (i & 0xFF);
ByteBuffer b = ByteBuffer.wrap(bb);
sb.append(String.valueOf(set.decode(b)).trim());
start = m.end();
}
start2 = str.length();
if (start2 > start) {
String seg = str.substring(start, start2);
sb.append(seg);
}
return sb.toString();
}


/**
* int转化成byte[] 高位在前,低位在后
* @param num
* @return
*/
public static byte[] int2bytes(int num) {
byte[] result = new byte[4];
result[0] = (byte) ((num >>> 24) & 0xff);// 说明一
result[1] = (byte) ((num >>> 16) & 0xff);
result[2] = (byte) ((num >>> 8) & 0xff);
result[3] = (byte) ((num >>> 0) & 0xff);
return result;
}


/**
* byte[] 转化成int 高位在前,低位在后
* @param bytes
* @return
*/
public static int bytes2int(byte[] bytes) {
int result = 0;
if (bytes.length == 4) {
int a = (bytes[0] & 0xff) << 24;// 说明二
int b = (bytes[1] & 0xff) << 16;
int c = (bytes[2] & 0xff) << 8;
int d = (bytes[3] & 0xff);
result = a | b | c | d;
}
return result;
}


}


猜你喜欢

转载自blog.csdn.net/jingyang07/article/details/79976554