java中通过post方式访问后台服务器

本文提供了一个Java实现的异步支付请求示例代码,包括构造支付参数、转换为XML格式、通过HTTPS POST方式发送请求的具体实现。此外,还展示了如何创建线程并启动异步任务。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

首先,上代码:

Runnable payRunnable = new Runnable() 
    		{
    			@Override
    			public void run() 
    			{
    				try
    	    		{	
    					HashMap<String, String> payParamMap = new HashMap<String, String>();
				    	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(); 
		   } 
		}
}

最后,没有了。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值