测试用的httpclient版本
<dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version>4.1.2</version> <scope>test</scope> </dependency>
1.传键值对
http://www.androidsnippets.com/executing-a-http-post-request-with-httpclient
2.发送https请求
http://javaskeleton.blogspot.it/2010/07/avoiding-peer-not-authenticated-with.html
最终测试代码:
public class LoginTest { @Test public void testHttpPost() throws Exception { HttpClient client = new DefaultHttpClient(); client = WebClientDevWrapper.wrapClient(client); HttpPost post = new HttpPost("https://localhost:8443/login"); // StringEntity entity = new StringEntity("[email protected]&pwd=111&type=x"); // post.setEntity(entity); List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2); nameValuePairs.add(new BasicNameValuePair("user", "[email protected]")); nameValuePairs.add(new BasicNameValuePair("pwd", "111")); nameValuePairs.add(new BasicNameValuePair("type", "x")); post.setEntity(new UrlEncodedFormEntity(nameValuePairs)); HttpResponse res = client.execute(post); System.out.println(res.getStatusLine()); BufferedReader br = new BufferedReader(new InputStreamReader(res.getEntity().getContent())); String line = br.readLine(); while (line != null) { System.out.println(line); line = br.readLine(); } client.getConnectionManager().shutdown(); } }
工具类:
/* This code is public domain: you are free to use, link and/or modify it in any way you want, for all purposes including commercial applications. */ public class WebClientDevWrapper { public static HttpClient wrapClient(HttpClient base) throws Exception { SSLContext ctx = SSLContext.getInstance("TLS"); X509TrustManager tm = new X509TrustManager() { @Override public void checkClientTrusted(java.security.cert.X509Certificate[] x509Certificates, String s) throws java.security.cert.CertificateException { } @Override public void checkServerTrusted(java.security.cert.X509Certificate[] x509Certificates, String s) throws java.security.cert.CertificateException { } @Override public java.security.cert.X509Certificate[] getAcceptedIssuers() { return new java.security.cert.X509Certificate[0]; } }; ctx.init(null, new TrustManager[]{tm}, null); SSLSocketFactory ssf = new SSLSocketFactory(ctx); ssf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); ClientConnectionManager ccm = base.getConnectionManager(); SchemeRegistry sr = ccm.getSchemeRegistry(); sr.register(new Scheme("https", ssf, 443)); return new DefaultHttpClient(ccm, base.getParams()); } }
使用命令行测试:
curl -k -X POST https://localhost:8443/login --data "[email protected]&pwd=111&type=x"
待研究http://my.oschina.net/wenziqiu/blog/339630,看起来更简单的样子。
时间: 2024-09-29 12:52:53