关于WebService和Http混合用

           疑惑原因来自今天看老大写的开发文档,用WebService创建接口,这样客户端要访问肯定是要考虑访问那个接口吧?起初最明智的办法就是访问到WebService服务的wsdl之后,找自己所需要的接口了。那么问题来了,如果你用http+post方式去访问它哩?

代码部分:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.InetSocketAddress;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.Map;
import net.sf.json.JSONObject;
import com.sun.net.httpserver.Headers;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;
import com.sun.net.httpserver.spi.HttpServerProvider;
import com.sun.org.apache.xerces.internal.impl.dv.util.Base64;
import com.yinxin.tools.DBUtil;
import com.yinxin.tools.FileTools;
import com.yinxin.tools.Log4jBean;
import com.yinxin.tools.ReadConfig;
/**
 * @content webService模块和Http+post方式混合用
 * @author syp
 * @time 2019-5-22 17:14:49
 */

public class WebServiceModules implements HttpHandler {
	public void handle(HttpExchange httpExchange) throws IOException {
		//2.1收到并解析报文,
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS");  //这个是对时间实例格式的
		Log4jBean.logger.info("监听到客户端接入,开始接收请求...");
		String reqStr = "";  //接收文件内容
		try {
			String requestMethod = httpExchange.getRequestMethod();
			Log4jBean.logger.info("开始校验Http的请求协议方式...");
			if (!requestMethod.equalsIgnoreCase("POST")) {
				// 客户端的请求不是POST方法
				Log4jBean.logger.error("客户端请求不是post方式");
				return;
			}
            //httpExchange.getRequestBody()获得输入流,相当于一个InputStream 
			BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(httpExchange.getRequestBody()));
			// 定义临时变量,接收一行数据
			String str = "";
			//请求报文所有内容
			while ((str = bufferedReader.readLine()) != null) {
				reqStr += str + "\n";  //保存文件内容
			}
			Log4jBean.logger.info("请求内容为:[" + reqStr + "]");
		} catch (Exception e) {
			Log4jBean.logger.error("接收客户端请求异常,异常信息为:[" + e.getMessage() + "]");
			return;
		}
		
        //开始校验报文并响应
		Map<String,String> map = CheckMsg(reqStr);
		String response=map.toString();
		OutputStream responseBody = null;  //响应的输出流
		try {
			// 设置服务端响应的编码格式,否则在客户端收到的可能是乱码
			Headers responseHeaders = httpExchange.getResponseHeaders();
			responseHeaders.set("Content-Type", "text/html;charset=utf-8");
			httpExchange.sendResponseHeaders(HttpURLConnection.HTTP_OK, response.getBytes("UTF-8").length);
			responseBody = httpExchange.getResponseBody();
			OutputStreamWriter writer = new OutputStreamWriter(responseBody, "UTF-8");
			writer.write(response);
			writer.close();
		} catch (Exception e) {
			Log4jBean.logger.error("向客户端发送响应失败,异常信息为:[" + e.getMessage() + "]");
			return;
		} finally {
			responseBody.close();
		}
	}
	
	public static void	main(String[] args) {
		//1读取配置参数,有本地文件路径参数等。
		ReadConfig.PullConfigXml();
		//2创建WebService,启动监听端口,等待公积金发来的消息。
		HttpServerProvider provider = HttpServerProvider.provider();
		HttpServer httpserver=null;
		try {
			httpserver = provider.createHttpServer(new InetSocketAddress(9087), 100);  // 监听端口9087,能同时接受100个请求
		} catch (IOException e) {
			// TODO Auto-generated catch block
			Log4jBean.logger.error("创建Http服务连接出现异常,异常信息为["+e.getMessage()+"]");
		}// 监听端口19087,能同时接受100个请求
		httpserver.createContext("/apsvr", new WebServiceModules());   //给项目服务端起个别名apsvr
		httpserver.setExecutor(null);
		httpserver.start();
		Log4jBean.logger.info("Http服务端创建成功,开始监听…………");
	}

}

用WebService的soap协议怎么去解决Http的post协议?

附上代码:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.StringWriter;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.apache.http.Header;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.HttpVersion;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.params.CookiePolicy;
import org.apache.http.client.params.HttpClientParams;
import org.apache.http.conn.params.ConnRoutePNames;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.protocol.HTTP;
 
//import bsh.ParseException;
import com.google.gson.Gson;
 
/**
 * TODO
 * @Version 1.0
 */
public class HttpClients {
    /** UTF-8 */
    private static final String UTF_8 = "UTF-8";
    /** 日志记录tag */
    private static final String TAG = "HttpClients";
 
    /** 用户host */
    private static String proxyHost = "";
    /** 用户端口 */
    private static int proxyPort = 80;
    /** 是否使用用户端口 */
    private static boolean useProxy = false;
 
    /** 连接超时 */
    private static final int TIMEOUT_CONNECTION = 60000;
    /** 读取超时 */
    private static final int TIMEOUT_SOCKET = 60000;
    /** 重试3次 */
    private static final int RETRY_TIME = 3;
 
    /**
     * @param url
     * @param requestData
     * @return
     */
    public String doHtmlPost(HttpClient httpClient,HttpPost httpPost )
    {
        String responseBody = null;
 
        int statusCode = -1;
 
        try {
             
            HttpResponse httpResponse = httpClient.execute(httpPost);
            Header lastHeader = httpResponse.getLastHeader("Set-Cookie");
            if(null != lastHeader)
            {
                httpPost.setHeader("cookie", lastHeader.getValue());
            }
            statusCode = httpResponse.getStatusLine().getStatusCode();
            if (statusCode != HttpStatus.SC_OK) {
                System.out.println("HTTP" + "  " + "HttpMethod failed: " + httpResponse.getStatusLine());
            }
            InputStream is = httpResponse.getEntity().getContent();
            responseBody = getStreamAsString(is, HTTP.UTF_8);
 
        } catch (Exception e) {
            // 发生网络异常
            e.printStackTrace();
        } finally {
//          httpClient.getConnectionManager().shutdown();
//          httpClient = null;
        }
 
        return responseBody;
    }
     
     
    /**
     * 
     * 发起网络请求
     * 
     * @param url
     *            URL
     * @param requestData
     *            requestData
     * @return INPUTSTREAM
     * @throws AppException
     */
    public static String doPost(String url, String requestData) throws Exception {
        String responseBody = null;
        HttpPost httpPost = null;
        HttpClient httpClient = null;
        int statusCode = -1;
        int time = 0;
        do {
            try {
                httpPost = new HttpPost(url);
                httpClient = getHttpClient();
                // 设置HTTP POST请求参数必须用NameValuePair对象
                List<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
                params.add(new BasicNameValuePair("param", requestData));
                UrlEncodedFormEntity entity = new UrlEncodedFormEntity(params, HTTP.UTF_8);
                // 设置HTTP POST请求参数
                httpPost.setEntity(entity);
                HttpResponse httpResponse = httpClient.execute(httpPost);
                statusCode = httpResponse.getStatusLine().getStatusCode();
                if (statusCode != HttpStatus.SC_OK) {
                    System.out.println("HTTP" + "  " + "HttpMethod failed: " + httpResponse.getStatusLine());
                }
                InputStream is = httpResponse.getEntity().getContent();
                responseBody = getStreamAsString(is, HTTP.UTF_8);
                break;
            } catch (UnsupportedEncodingException e) {
                time++;
                if (time < RETRY_TIME) {
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e1) {
                    }
                    continue;
                }
                // 发生致命的异常,可能是协议不对或者返回的内容有问题
                e.printStackTrace();
 
            } catch (ClientProtocolException e) {
                time++;
                if (time < RETRY_TIME) {
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e1) {
                    }
                    continue;
                }
                // 发生致命的异常,可能是协议不对或者返回的内容有问题
                e.printStackTrace();
            } catch (IOException e) {
                time++;
                if (time < RETRY_TIME) {
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e1) {
                    }
                    continue;
                }
                // 发生网络异常
                e.printStackTrace();
            } catch (Exception e) {
                time++;
                if (time < RETRY_TIME) {
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e1) {
                    }
                    continue;
                }
                // 发生网络异常
                e.printStackTrace();
            } finally {
                httpClient.getConnectionManager().shutdown();
                httpClient = null;
            }
        } while (time < RETRY_TIME);
        return responseBody;
    }
 
    /**
     * 
     * 将InputStream 转化为String
     * 
     * @param stream
     *            inputstream
     * @param charset
     *            字符集
     * @return
     * @throws IOException
     */
    private static String getStreamAsString(InputStream stream, String charset) throws IOException {
        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(stream, charset), 8192);
            StringWriter writer = new StringWriter();
 
            char[] chars = new char[8192];
            int count = 0;
            while ((count = reader.read(chars)) > 0) {
                writer.write(chars, 0, count);
            }
 
            return writer.toString();
        } finally {
            if (stream != null) {
                stream.close();
            }
        }
    }
     
    /**
     * 得到httpClient
     * 
     * @return
     */
    public HttpClient getHttpClient1() {
        final HttpParams httpParams = new BasicHttpParams();
 
        if (useProxy) {
            HttpHost proxy = new HttpHost(proxyHost, proxyPort, "http");
            httpParams.setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
        }
 
        HttpConnectionParams.setConnectionTimeout(httpParams, TIMEOUT_CONNECTION);
        HttpConnectionParams.setSoTimeout(httpParams, TIMEOUT_SOCKET);
        HttpClientParams.setRedirecting(httpParams, true);
        final String userAgent = "Mozilla/5.0 (Windows; U; Windows NT 6.1; zh-CN; rv:1.9.2.14) Gecko/20110218 Firefox/3.6.14";
 
        HttpProtocolParams.setUserAgent(httpParams, userAgent);
        HttpProtocolParams.setVersion(httpParams, HttpVersion.HTTP_1_1);
        HttpClientParams.setCookiePolicy(httpParams, CookiePolicy.RFC_2109);
         
        HttpProtocolParams.setUseExpectContinue(httpParams, false);
        HttpClient client = new DefaultHttpClient(httpParams);
 
        return client;
    }
 
    /**
     * 
     * 得到httpClient
     * 
     * @return
     */
    private static HttpClient getHttpClient() {
        final HttpParams httpParams = new BasicHttpParams();
 
        if (useProxy) {
            HttpHost proxy = new HttpHost(proxyHost, proxyPort, "http");
            httpParams.setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
        }
 
        HttpConnectionParams.setConnectionTimeout(httpParams, TIMEOUT_CONNECTION);
        HttpConnectionParams.setSoTimeout(httpParams, TIMEOUT_SOCKET);
        HttpClientParams.setRedirecting(httpParams, true);
        final String userAgent = "Mozilla/5.0 (Windows; U; Windows NT 6.1; zh-CN; rv:1.9.2.14) Gecko/20110218 Firefox/3.6.14";
 
        HttpProtocolParams.setUserAgent(httpParams, userAgent);
        HttpProtocolParams.setVersion(httpParams, HttpVersion.HTTP_1_1);
        HttpClientParams.setCookiePolicy(httpParams, CookiePolicy.BROWSER_COMPATIBILITY);
        HttpProtocolParams.setUseExpectContinue(httpParams, false);
        HttpClient client = new DefaultHttpClient(httpParams);
 
        return client;
    }
 
    /**
     * 打印返回内容
     * @param response
     * @throws ParseException
     * @throws IOException
     */
    public static void showResponse(String str) throws Exception {
        Gson gson = new Gson();    
        Map<String, Object> map = (Map<String, Object>) gson.fromJson(str, Object.class);
        String value = (String) map.get("data");       
        //String decodeValue =  Des3Request.decode(value);
        //System.out.println(decodeValue);
        //logger.debug(decodeValue);
    }
     
    /**
     * 
     * 发起网络请求
     * 
     * @param url
     *            URL
     * @param requestData
     *            requestData
     * @return INPUTSTREAM
     * @throws AppException
     */
    public static String doGet(String url) throws Exception {
        String responseBody = null;
        HttpGet httpGet = null;
        HttpClient httpClient = null;
        int statusCode = -1;
        int time = 0;
        do {
            try {
                httpGet = new HttpGet(url);
                httpClient = getHttpClient();
                HttpResponse httpResponse = httpClient.execute(httpGet);
                statusCode = httpResponse.getStatusLine().getStatusCode();
                if (statusCode != HttpStatus.SC_OK) {
                    System.out.println("HTTP" + "  " + "HttpMethod failed: " + httpResponse.getStatusLine());
                }
                InputStream is = httpResponse.getEntity().getContent();
                responseBody = getStreamAsString(is, HTTP.UTF_8);
                break;
            } catch (UnsupportedEncodingException e) {
                time++;
                if (time < RETRY_TIME) {
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e1) {
                    }
                    continue;
                }
                // 发生致命的异常,可能是协议不对或者返回的内容有问题
                e.printStackTrace();
 
            } catch (ClientProtocolException e) {
                time++;
                if (time < RETRY_TIME) {
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e1) {
                    }
                    continue;
                }
                // 发生致命的异常,可能是协议不对或者返回的内容有问题
                e.printStackTrace();
            } catch (IOException e) {
                time++;
                if (time < RETRY_TIME) {
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e1) {
                    }
                    continue;
                }
                // 发生网络异常
                e.printStackTrace();
            } catch (Exception e) {
                time++;
                if (time < RETRY_TIME) {
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e1) {
                    }
                    continue;
                }
                // 发生网络异常
                e.printStackTrace();
            } finally {
                httpClient.getConnectionManager().shutdown();
                httpClient = null;
            }
        } while (time < RETRY_TIME);
        return responseBody;
    }
}

提出思路:

就是总共发布一个服务接口及端口地址,用http+post方式是不是就不用找WebService中哪一个接口了哩?

 

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

醉梦洛

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值