2012-12-18 35 views
2

我正在使用grails应用程序,并且几个小时已经试图从请求中获取html代码。我想要做的是获得普通的html(比如在一个webPage源代码中,包含所有标签和东西),以便我可以处理它。从HTTP请求获取纯HTML HTML代码

我已经设法得到它为我的这个代码GET请求:

url = ("http://google.com").toURL().getText()) 

它工作得很好,但我也需要能够进行POST请求。

我试过httpBuilder,但我得到的响应看起来像格式化文本(与空白和东西),但没有任何html标签,我需要它们。我使用的代码如下所示:

def url = "http://urlToRemoteServer.com/" 
def http = new HTTPBuilder(url); 


http.post(path: 'pathToMyApp', 
     requestContentType: "text/xml") { resp, reader -> 

      println "Tweet response status: ${resp.statusLine}" 
      assert resp.statusLine.statusCode == 200 
      System.out << reader 
     } 

谁能告诉我如何获取该html代码?我正在研究groovy,但Java解决方案将会同样出色。

回答

2

更改后的地图以包括contentType强制纯文本解析(和,我相信更改为Accepts头)如下:

http.post(path: 'pathToMyApp', 
      requestContentType: "text/xml", 
      contentType: "text/xml") { resp, reader -> 

或者,您可以更改解析器通过这一点,将来的请求加入ParserRegistry重映射的构造之后:

http.parser.'text/html' = http.parser.'text/plain' 

您还可以添加一个调用setContentType(),你的构造函数调用后HTTPBuilder

//... 
def http = new HTTPBuilder(url); //existing code 
http.contentType = ContentType.TEXT //new addition 
http.post(path: 'pathToMyApp', //existing code 
//... 
+1

改变解析器的信息并获得成功 - THX非常 – dulcyn

1

另一种方式,你可以做到这一点:

import static groovyx.net.http.ContentType.TEXT 
import static groovyx.net.http.ContentType.URLENC  

def url = "http://urlToRemoteServer.com/" 

def http = new HTTPBuilder(url); 

http.request(Method.POST, TEXT) { resp, reader -> 

    println "Tweet response status: ${resp.statusLine}" 
    assert resp.statusLine.statusCode == 200 
    println reader.text 
} 

松散的基础上包含在http://groovy.codehaus.org/modules/http-builder/doc/contentTypes.html

+0

我想你可能需要在这种情况下改变关闭。至少在0.6版本中,2-arg版本不适用于request()。请注意,请求内容类型也由此改变。 –

0
public static post(String url, String data, def contentType = ContentType.XML) { 
    def client = new HTTPBuilder(url) 
    def xml = null 
    client.request(groovyx.net.http.Method.POST) { 
     contentType = contentType 
     requestContentType = contentType 
     body = data 
     response.success = { resp, raw -> 
      println "Success response: ${resp.statusLine} ->\n${raw.text}" 
      xml = [status: resp.statusLine, response:raw] 
     } 
     response.failure = { resp, raw -> 
      println "Error response: ${resp.statusLine} ->\n${raw.text}" 
      xml = [status: resp.statusLine, response:raw] 
     }  
    } 
    return xml 
}