java实现http~~~ get方法

其实核心思路都被java封装好了,
先得到URL类, 然后一切http通讯都委托URL类来完成
[color=darkblue]  发送链接并链接服务器的核心代码   url.openConnection();
  接受服务器端传来的参数核心代码   url.getInputStream();[/color]
  只不过用reader封装会快点而已

/**
 * Sends an HTTP GET request to a url
 * 
 * @param endpoint
 *            - The URL of the server. (Example:
 *            " http://www.yahoo.com/search")
 * @param requestParameters
 *            - all the request parameters (Example:
 *            "param1=val1&param2=val2"). Note: This method will add the
 *            question mark (?) to the request - DO NOT add it yourself
 * @return - The response from the end point
 */

public static String sendGetRequest(String endpoint,
		String requestParameters) {

     String result = null;
     if (endpoint.startsWith("http://")) {
     // Send a GET request to the servlet
     try {
	// Construct data
	StringBuffer data = new StringBuffer();
	// Send data
	String urlStr = endpoint;
      if (requestParameters != null&&requestParameters.length() > 0) {
	urlStr += "?" + requestParameters;
      }
        URL url = new URL(urlStr);
        URLConnection conn = url.openConnection();

        // Get the response
        InputStreamReader r = 
                     new InputStreamReader(conn.getInputStream());
        BufferedReader rd = 
            new BufferedReader(new InputStreamReader(r));		
        StringBuffer sb = new StringBuffer();
        String line;
        while ((line = rd.readLine()) != null) {
		sb.append(line);
        }
	rd.close();
	result = sb.toString();
      } catch (Exception e) {
	e.printStackTrace();
      }
   }
   return result;
}

你可能感兴趣的:(java,servlet,Yahoo)