当前位置: 代码迷 >> Web前端 >> Sample-simulate the http request
  详细解决方案

Sample-simulate the http request

热度:834   发布时间:2012-09-09 09:27:54.0
Sample---simulate the http request
package com.wlq;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;


public class RDRHttpCallSample {

	private static final int TIMEOUT = 50000;
	
    public final static String BAIDU_URL = "http://www.baidu.com" ;
	
    public final static String MSG_NULL = "content is null";

	
	public static boolean validate(String source) {
		boolean rs = true;
		if (source.equals(MSG_NULL))
			rs = false;
		if (source.indexOf("ERROR#") != -1 || source.indexOf("ErrorMsg") != -1 || source.indexOf("ERROR_TYPE") != -1)
			rs = false;
		return rs;
	}

	public static String getHttpUsefulInfo(StringBuffer buffer) {

		String rs = "";
		if (buffer.indexOf("<body>") != -1) {
			int index = buffer.indexOf("<body>");
			buffer.replace(0, index + 6, "");
			index = buffer.indexOf("</body>");
			buffer.replace(index, buffer.length(), "");
		}
		rs = buffer.toString();
		return rs.equals("") ? rs = MSG_NULL : rs;
	}
	
	public static StringBuffer doCall(String url, String queryStr){
		
		StringBuffer rs = new StringBuffer();
		HttpURLConnection conn = null;
		String sTotalString = "";
		int respCode = 0;
		try{
			URL console = new URL(url);
			conn = (HttpURLConnection) console.openConnection();
			conn.setConnectTimeout(TIMEOUT);
			conn.setDoOutput(true);
			conn.setRequestMethod("POST");
			
			conn.getOutputStream().write(queryStr.getBytes());
			conn.getOutputStream().flush();
			conn.getOutputStream().close();
			conn.connect();
			
			respCode = conn.getResponseCode();
			if(respCode == 200){
				String sCurrentLine = "";
				InputStream is = conn.getInputStream();
				BufferedReader reader = new BufferedReader(new InputStreamReader(is));
				while ((sCurrentLine = reader.readLine()) != null)
					if (sCurrentLine.length() > 0)
						sTotalString = sTotalString + sCurrentLine.trim();
			}else{
				sTotalString = "Call the rdr server error, error code is " + respCode;
			}
		}catch (Exception e) {
			e.printStackTrace();
		}finally{
			if(conn !=null)
				conn.disconnect();
			if(validate(sTotalString))
				rs.append(getHttpUsefulInfo(new StringBuffer(sTotalString)));
		}
		return rs;
	}
	
	public enum QueryStrGenerator{
		
				BAIDU_CASE{
			@Override
			public String getQueryStr(){
				String str ="s?wd=what+if+you+go&rsv_spt=1&issp=1&rsv_bp=0&ie=utf-8&tn=baiduhome_pg&inputT=2094";
				return str;
			}
		};
		abstract public String getQueryStr();
	}
	
	public static void main(String...args){
		
		String url = BAIDU_URL,
			   queryStr = QueryStrGenerator.BAIDU_CASE.getQueryStr();
		StringBuffer rs = doCall(url, queryStr);
		System.out.println(rs.toString());
	}
}
  相关解决方案