http
package cn.com.xmh.channels.icbc; import java.util.ArrayList; import java.util.List; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.HttpStatus; import org.apache.http.NameValuePair; import org.apache.http.client.config.RequestConfig; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.message.BasicNameValuePair; import org.apache.http.util.EntityUtils; /* * org.apache.http.client.HttpClient 与 org.apache.commons.httpclient.HttpClient 区别 * commons.httpclient-3.1.jar这个jar包是依赖了httpcore,commons-logging,commons-codec这三个jar包。而在commons-httpclient.jar包在使用过程中,需要依赖commons-logging.jar和commons-codec.jar, * 这个httpclient4.2.1.jar就相当于集合了以前的commons-httpclient,commons-logging,commons-codec,这三个jar包,减少了繁琐的导入jar包的过程,现在只需导入一个httpclient.jar就可以使用了。 * * */ public class HttpClient4 { public static void main(String[] args) { try { httpclient4(); } catch (Exception e) { e.printStackTrace(); } } public static void httpclient4() throws Exception { String url = "http://127.0.0.1:8080/cashier-web/cashier/default.dhtml"; // HttpRequestBase method = null; // switch (methodType) { // case 0: // method = new HttpGet(url); // break; // case 1: // method = new HttpPost(url); // break; // case 2: // method = new HttpPut(url); // break; // case 3: // method = new HttpDelete(url); // break; // default: // method = new HttpGet(url); // break; // } HttpPost method = new HttpPost(url); // HttpClient client = new DefaultHttpClient(); 4.1版本 RequestConfig defaultRequestConfig = RequestConfig.custom() .setSocketTimeout(5000) .setConnectTimeout(5000) .setConnectionRequestTimeout(5000) .build(); // CloseableHttpClient client = HttpClients.createDefault(); CloseableHttpClient client = HttpClients.custom() .setDefaultRequestConfig(defaultRequestConfig) .build(); // HttpParams params = client.getParams(); // params.setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 3000); // params.setParameter(CoreConnectionPNames.SO_TIMEOUT, 3000); // method.setParams(params); method.setHeader("Charset", "UTF-8"); method.setHeader("Content-Type", "application/x-www-form-urlencoded");//text/xml; charset=utf-8 List<NameValuePair> vnps = new ArrayList<NameValuePair>(); vnps.add(new BasicNameValuePair("ids","11111"));//BasicNameValuePair impl NameValuePair HttpEntity entity = new UrlEncodedFormEntity(vnps); method.setEntity(entity); HttpResponse response = client.execute(method); String ret = ""; int statusCode = response.getStatusLine().getStatusCode(); entity = response.getEntity(); ret = EntityUtils.toString(entity, "utf-8"); if (statusCode != HttpStatus.SC_OK) { System.out.println("=========" + ret); throw new Exception("something wrong happened when you request http ,statusCode:" + statusCode); } System.out.println(statusCode+" : "+ret); // client.getConnectionManager().shutdown(); client.close(); } }
package cn.com.xmh.channels.icbc; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLDecoder; import java.util.Arrays; import org.apache.commons.httpclient.HttpClient; import org.apache.commons.httpclient.HttpStatus; import org.apache.commons.httpclient.NameValuePair; import org.apache.commons.httpclient.methods.PostMethod; import org.apache.commons.httpclient.params.HttpClientParams; import org.apache.commons.httpclient.params.HttpConnectionManagerParams; import org.apache.commons.httpclient.protocol.Protocol; import org.apache.http.params.CoreConnectionPNames; import cn.com.xmh.channels.icbc.common.AuthSSLProtocolSocketFactory; public class HttpTest { public static void main(String[] args) { try { httpURLConnectionPost(); } catch (Exception e) { e.printStackTrace(); } } /** * java原生api java.net.HttpURLConnection */ public static void httpURLConnectionPost(){ HttpURLConnection conn = null; String[] result = new String[2]; try { byte[] data = "id=123".getBytes(); // 送报文兼容GB2312和GB18030编码格式,返回报文为GB18030编码格式 String parameters = "id=1&name=123"; URL url = new URL("http://127.0.0.1:8080/cashier-web/cashier/default.dhtml"); // 使用HttpURLConnection发送http请求 conn = (HttpURLConnection) url.openConnection(); conn.setConnectTimeout(3000); conn.setReadTimeout(3000); conn.setDoOutput(true);// 允许输出 conn.setDoInput(true); conn.setAllowUserInteraction(false); conn.setUseCaches(false);// 不使用Cache conn.setRequestMethod("POST"); // conn.setRequestProperty("Connection", "Keep-Alive");// 维持长连接 // conn.setRequestProperty("Charset", "UTF-8"); conn.setRequestProperty("Content-Length", String.valueOf(data.length)); conn.setRequestProperty("Content-Type", "text/xml; charset=utf-8");//以流的方式传送 字符串 接收者以流的方式读取 // conn.setRequestProperty("Accept-Charset", "utf-8"); // conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");//x-www-form-urlencoded orm表单数据被编码为key/value格式发送到服务器(表单默认的提交数据的格式) // conn.setRequestProperty("Content-Length", String.valueOf(parameters.length())); // DataOutputStream outStream = new DataOutputStream(conn.getOutputStream()); // outStream.write(data);// 发送数据 OutputStreamWriter outputStreamWriter = new OutputStreamWriter(conn.getOutputStream()); outputStreamWriter.write(parameters); outputStreamWriter.flush(); outputStreamWriter.close(); // 解析返回来的xml消息体 BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream())); StringBuffer buf = new StringBuffer(); String line = null; while ((line = in.readLine()) != null) { buf.append(line); } result[0] = String.valueOf(conn.getResponseCode()); // 响应状态 result[1] = buf.toString(); // 响应数据 } catch (Exception e) { e.printStackTrace(); } finally { conn.disconnect(); } System.out.println(Arrays.toString(result)); } public static void httpClientPostAuth() throws Exception, IOException{ HttpClient client = new HttpClient(); HttpConnectionManagerParams managerParams = client.getHttpConnectionManager().getParams(); // 设置连接超时时间(单位毫秒) managerParams.setConnectionTimeout(30000); // 设置读数据超时时间(单位毫秒) managerParams.setSoTimeout(120000); String keyPath = "file:D:\\icbc.jks"; URL url = new URL(keyPath); Protocol authhttps = new Protocol("https",new AuthSSLProtocolSocketFactory(url, "12345678", url, "12345678"), 443); client.getHostConfiguration().setHost("corporbank.icbc.com.cn",443,authhttps); PostMethod httpget = new PostMethod("/servlet/ICBCINBSEBusinessServlet"); httpget.setParameter("APIName", "EAPI"); httpget.setParameter("APIVersion", "001.001.002.001"); httpget.setParameter("MerReqData", ""); client.executeMethod(httpget); String resStr = URLDecoder.decode(httpget.getResponseBodyAsString(),"GBK").replaceAll("\\s+", " "); System.out.println(resStr); } //http://hc.apache.org/httpclient-3.x/userguide.html /** *引用apache的commons包实现 org.apache.commons.httpclient.HttpClient */ public static void httpClient2(){ // System.setProperty("http.proxySet", "true"); // System.setProperty("http.proxyHost", "127.0.0.1"); // System.setProperty("http.proxyPort", "8888"); // HttpClient hc = new HttpClient(); HttpClientParams params = new HttpClientParams(); params.setContentCharset("UTF-8"); // params.setSoTimeout(3000); hc.getParams().setParameter("http.connection.timeout", 3000); hc.getParams().setParameter("http.socket.timeout", 3000); //请求超时 hc.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 3000); //读取超时 hc.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 3000); // HttpConnectionManagerParams managerParams = hc.getHttpConnectionManager().getParams(); // // 设置连接超时时间(单位毫秒) // managerParams.setConnectionTimeout(3000); // // 设置读数据超时时间(单位毫秒) // managerParams.setSoTimeout(3000); hc.setParams(params); PostMethod pm = new PostMethod("http://127.0.0.1:8080/cashier-web/cashier/default.dhtml"); pm.addRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=utf-8"); // GetMethod method = new GetMethod("https://gw.tenpay.com/gateway/normalorderquery.xml"); // method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,new DefaultHttpMethodRetryHandler(3, false)); //请求参数设置 pm.setParameter("idsss", "111"); NameValuePair[] s = new NameValuePair[1]; NameValuePair mp = new NameValuePair(); mp.setName("names"); mp.setValue("xmh"); s[0] = mp; pm.addParameters(s); try { hc.executeMethod(pm); if (pm.getStatusCode() == HttpStatus.SC_OK) { System.out.println(pm.getResponseBodyAsString()); } else { System.out.println("Unexpected failure: " + pm.getStatusLine().toString()); } String repMsg = pm.getResponseBodyAsString(); System.out.println(repMsg); repMsg = new String(pm.getResponseBody(), "utf-8"); System.out.println(repMsg); } catch (Exception ex) { throw new RuntimeException(ex); } finally { pm.releaseConnection(); } }
// HttpClient 4:
//
// 连接超时:
// httpclient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT,60000);
// // 或者
// HttpConnectionParams.setConnectionTimeout(params, 6000);
//
// 读取超时:
// httpclient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT,60000);
// // 或者
// HttpConnectionParams.setSoTimeout(params, 60000);
// HttpClient 3:
//
// 连接超时:
// httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(60000);
//
// 读取超时:
// httpClient.getHttpConnectionManager().getParams().setSoTimeout(60000);
}