第一种方法
需要导入的架包有
import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;
public static PostMethod httpSendPost(String url, Map<String, Object> propsMap) throws Exception {
String responseMsg = "";
HttpClient httpClient = new HttpClient();
PostMethod postMethod = new PostMethod(url);// POST请求
postMethod.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET,"UTF-8");
// 参数设置
Set<String> keySet = propsMap.keySet();
NameValuePair[] postData = new NameValuePair[keySet.size()];
int index = 0;
for (String key : keySet) {
postData[index++] = new NameValuePair(key, propsMap.get(key)
.toString());
System.err.println( key + " : " +propsMap.get(key)
.toString());
}
postMethod.addParameters(postData);
httpClient.executeMethod(postMethod);// 发送请求
return postMethod;
}
第二种方法
需要导入的架包有
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLSession;
public static void test2(){
try {
HttpConnectionUtil http = new HttpConnectionUtil("http://dmztest.allinpaysc.com:12809/getData/getDataServlet");
http.init();
QueryDao queryDao = new QueryDao();
List<Tempoyary> list = queryDao.selectAll(153171501);
TreeMap<String,String> params = new TreeMap<String,String>();
for (Tempoyary tempoyary : list) {
params.put("交易时间", tempoyary.get交易时间());
params.put("商户号", tempoyary.get商户号());
params.put("交易金额", tempoyary.get交易金额());
params.put("交易流水号", tempoyary.get交易流水号());
}
byte[] bys = http.postParams(params,true);
System.out.println("http : " + http.toString());
System.out.println("bys : " + bys.toString());
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public byte[] postParams(Map<String, String> params,boolean readreturn) throws IOException {
StringBuilder outBuf = new StringBuilder();
boolean isNotFirst = false;
for (Map.Entry<String, String> entry: params.entrySet()){
if (isNotFirst)
outBuf.append('&');
isNotFirst = true;
outBuf
.append(entry.getKey())
.append('=')
.append(URLEncoder.encode(entry.getValue(), "UTF-8"));
}
System.out.println("参数:"+outBuf.toString());
return postParams(outBuf.toString(),readreturn);
}
public byte[] postParams(String message,boolean readreturn) throws IOException {
DataOutputStream out = new DataOutputStream(conn.getOutputStream());
out.write(message.getBytes("UTF-8"));
System.out.println("connectUrl : " + connectUrl);
System.out.println("conn : " + conn);
out.close();
if(readreturn){
return readBytesFromStream(conn.getInputStream());
}else{
return null;
}
}