详解java中通过post方式访问后台服务器
最近在学习java中通过post方式访问后台服务器,那么今天也算个学习笔记吧!
首先,上代码:
RunnablepayRunnable=newRunnable()
{
@Override
publicvoidrun()
{
try
{
HashMappayParamMap=newHashMap();
payParamMap.put("canshu","woshicanshu");
StringpayParamStr=XmlUtils.toXml(payParamMap);//转换成xml格式
StringresultStr=Utils.httpPost(UrlString,payParamStr);//调用访问函数
//resultStr就是访问所得到的返回值
}
catch(Exceptione)
{
e.printStackTrace();
}
}
};
//必须异步调用
ThreadpayThread=newThread(payRunnable);
payThread.start();
其次,上代码:
publicclassUtils{
privatestaticfinalStringTAG="woshiTag";
publicstaticStringhttpPost(Stringurl,Stringentity){
if(url==null||url.length()==0){
Log.e(TAG,"httpPost,urlisnull");
returnnull;
}
HttpClienthttpClient=getNewHttpClient();
HttpPosthttpPost=newHttpPost(url);
try{
httpPost.setEntity(newStringEntity(entity,HTTP.UTF_8));
httpPost.setHeader("Accept","application/json");
httpPost.setHeader("Content-type","application/json");
HttpResponseresp=httpClient.execute(httpPost);
if(resp.getStatusLine().getStatusCode()!=HttpStatus.SC_OK){
Log.e(TAG,"httpGetfail,statuscode="+resp.getStatusLine().getStatusCode());
returnnull;
}
returnnewString(EntityUtils.toByteArray(resp.getEntity()));
}catch(Exceptione){
Log.e(TAG,"httpPostexception,e="+e.getMessage());
e.printStackTrace();
returnnull;
}
}
privatestaticHttpClientgetNewHttpClient(){
try{
KeyStoretrustStore=KeyStore.getInstance(KeyStore.getDefaultType());
trustStore.load(null,null);
SSLSocketFactorysf=newSSLSocketFactoryEx(trustStore);
sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
HttpParamsparams=newBasicHttpParams();
HttpProtocolParams.setVersion(params,HttpVersion.HTTP_1_1);
HttpProtocolParams.setContentCharset(params,HTTP.UTF_8);
SchemeRegistryregistry=newSchemeRegistry();
registry.register(newScheme("http",PlainSocketFactory.getSocketFactory(),80));
registry.register(newScheme("https",sf,443));
ClientConnectionManagerccm=newThreadSafeClientConnManager(params,registry);
returnnewDefaultHttpClient(ccm,params);
}catch(Exceptione){
returnnewDefaultHttpClient();
}
}
}
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。