2011-01-23 104 views
0

如何將此代碼轉換爲JSPfsockopen在JSP中相當於

任何幫助表示讚賞..!

$fp = fsockopen("www.example.com", 80, $errno, $errstr, 30); 
if (!$fp) { 
    echo "$errstr ($errno)<br />\n"; 
} else { 
    $out = "GET/HTTP/1.1\r\n"; 
    $out .= "Host: www.example.com\r\n"; 
    $out .= "Connection: Close\r\n\r\n"; 
    fwrite($fp, $out); 
    while (!feof($fp)) { 
     echo fgets($fp, 128); 
    } 
    fclose($fp); 
} 
+0

編寫的代碼是沒有好主意,你爲什麼不創建一個bean,並使用它呢?代碼將是相同的,可用性和可測試性要好得多。 – maaartinus 2011-01-23 14:25:58

回答

0

您可以使用Apache HTTP Components庫執行此操作。類似下面的內容應該可以與HTTP組件庫一起使用:

<%@ page import="org.apache.http.*, org.apache.http.impl.*, org.apache.http.params.*, org.apache.http.protocol.*, org.apache.http.message.BasicHttpRequest, org.apache.http.util.EntityUtils, java.net.Socket" %> 

<% 
HttpParams params = new SyncBasicHttpParams(); 
HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); 
HttpProtocolParams.setContentCharset(params, "UTF-8"); 
HttpProtocolParams.setUserAgent(params, "HttpComponents/1.1"); 
HttpProtocolParams.setUseExpectContinue(params, true); 

HttpProcessor httpproc = new ImmutableHttpProcessor(new HttpRequestInterceptor[] { 
     new RequestContent(), 
     new RequestTargetHost(), 
     new RequestConnControl(), 
     new RequestUserAgent(), 
     new RequestExpectContinue()}); 

HttpRequestExecutor httpexecutor = new HttpRequestExecutor(); 

HttpContext context = new BasicHttpContext(null); 
HttpHost host = new HttpHost("www.example.com", 80); 

DefaultHttpClientConnection conn = new DefaultHttpClientConnection(); 
ConnectionReuseStrategy connStrategy = new DefaultConnectionReuseStrategy(); 

context.setAttribute(ExecutionContext.HTTP_CONNECTION, conn); 
context.setAttribute(ExecutionContext.HTTP_TARGET_HOST, host); 

try 
{   
    Socket socket = new Socket(host.getHostName(), host.getPort()); 
    conn.bind(socket, params); 

    BasicHttpRequest request = new BasicHttpRequest("GET", "/"); 


    request.setParams(params); 
    httpexecutor.preProcess(request, httpproc, context); 
    HttpResponse response = httpexecutor.execute(request, conn, context); 
    response.setParams(params); 
    httpexecutor.postProcess(response, httpproc, context); 

%> 
<%=EntityUtils.toString(response.getEntity())%> 
<% 
} 
finally 
{ 
    conn.close(); 
} 
%> 
2

您可以使用JSTL taglib。首先使用

<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> 

聲明在JSP的頂部的名稱空間,然後使用C:進口標籤,包括從指定的URL內容:

<c:import url="htp://www.example.com/" /> 
1

看看這個工程.... ...

<%@頁面的contentType = 「text/html的」 進口= 「java.io。,java.net。」 %>

< % try {socket} s = new Socket(「www.java2s.com」,80);在JSP

 BufferedReader in = new BufferedReader(new 
      InputStreamReader(s.getInputStream())); 
     PrintWriter socketOut = new PrintWriter(s.getOutputStream()); 

     socketOut.print("GET /index.html\n\n"); 
     socketOut.flush(); 

     String line; 

     while ((line = in.readLine()) != null){ 
      out.println(line); 
     } 

    } catch (Exception e){} 

%>