本篇文章主要介绍了详解java中通过post方式访问后台服务器,具有一定的参考价值,感兴趣的小伙伴们可以参考一下。
最近在学习java中通过post方式访问后台服务器,那么今天也算个学习笔记吧!
首先,上代码:
ECTouch是上海商创网络科技有限公司推出的一套基于 PHP 和 MySQL 数据库构建的开源且易于使用的移动商城网店系统!应用于各种服务器平台的高效、快速和易于管理的网店解决方案,采用稳定的MVC框架开发,完美对接ecshop系统与模板堂众多模板,为中小企业提供最佳的移动电商解决方案。ECTouch程序源代码完全无加密。安装时只需将已集成的文件夹放进指定位置,通过浏览器访问一键安装,无需对已有
Runnable payRunnable = new Runnable()
{
@Override
public void run()
{
try
{
HashMap payParamMap = new HashMap();
payParamMap.put("canshu" ,"woshicanshu" );
String payParamStr = XmlUtils.toXml(payParamMap);//转换成xml格式
String resultStr = Utils.httpPost(UrlString, payParamStr);//调用访问函数
//resultStr 就是访问所得到的返回值
}
catch(Exception e)
{
e.printStackTrace();
}
}
};
// 必须异步调用
Thread payThread = new Thread(payRunnable);
payThread.start(); 其次,上代码:
public class Utils {
private static final String TAG = "woshiTag";
public static String httpPost(String url, String entity) {
if (url == null || url.length() == 0) {
Log.e(TAG, "httpPost, url is null");
return null;
}
HttpClient httpClient = getNewHttpClient();
HttpPost httpPost = new HttpPost(url);
try {
httpPost.setEntity(new StringEntity(entity, HTTP.UTF_8));
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Content-type", "application/json");
HttpResponse resp = httpClient.execute(httpPost);
if (resp.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
Log.e(TAG, "httpGet fail, status code = " + resp.getStatusLine().getStatusCode());
return null;
}
return new String(EntityUtils.toByteArray(resp.getEntity()));
} catch (Exception e) {
Log.e(TAG, "httpPost exception, e = " + e.getMessage());
e.printStackTrace();
return null;
}
}
private static HttpClient getNewHttpClient() {
try {
KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
trustStore.load(null, null);
SSLSocketFactory sf = new SSLSocketFactoryEx(trustStore);
sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
HttpParams params = new BasicHttpParams();
HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);
SchemeRegistry registry = new SchemeRegistry();
registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
registry.register(new Scheme("https", sf, 443));
ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry);
return new DefaultHttpClient(ccm, params);
} catch (Exception e) {
return new DefaultHttpClient();
}
}
}










