更新:这是重复的,
我正在使用grails taglib构建一个Proxy-custom-tag,默认情况下它会生成一个get-request,现在我遇到了问题,它应该能够处理Post-request,# 并且我能够检查请求方法并有条件地将openConnection方法设置为必要时发布,但我不知道如何将post-params附加到请求。 这是我目前的代码
def wordpressContent = { attrs, body ->
def url
def requestMethod = request.getMethod()
def queryString = request.getQueryString()?'&'+request.getQueryString():''
def content
println "method :"+requestMethod
println "params == "+params // <- inside here are the post-parameters
url = grailsApplication.config.wordpress.server.url+attrs.pageName+'?include=true'+queryString
try {
content = url.toURL().openConnection().with { conn ->
if(requestMethod == 'POST'){
println "Its a POST"
conn.setRequestMethod("POST")
conn.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
// HOW to append the params here ?
}
readTimeout = 6000
if( responseCode != 200 ) {
throw new Exception( 'Not Ok' )
}
conn.content.withReader { r ->
r.text
}
}
}
catch( e ) {
println "exception : "+e
content="<div class='float' style='margin-top:10px;width:850px;background-color:white;border-radius:5px;padding:50px;'>Hier wird gerade gebaut</div>"
}
out << content
}
我现在非常困在这里,我找到了使用这种语法的答案
Writer wr = new OutputStreamWriter(conn.outputStream)
wr.write(postParams)
wr.flush()
wr.close()
但我不知道如何将其包含在我现有的代码中, 任何提示都要提前感谢
更新:我的解决方案是通过在这个模式“xyz = zyx&amp; abc = cba”中迭代params对象来构建post-parameter-querystring并将其写入如上所述的outputStream
答案 0 :(得分:2)
// HTTP POST request
private void sendPost() throws Exception {
String url = "https://selfsolve.apple.com/wcResults.do";
URL obj = new URL(url);
HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();
//add request header
con.setRequestMethod("POST");
con.setRequestProperty("User-Agent", USER_AGENT);
con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
String urlParameters = "sn=C02G8416DRJM&cn=&locale=&caller=&num=12345";
// Send post request
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(urlParameters);
wr.flush();
wr.close();
int responseCode = con.getResponseCode();
System.out.println("\nSending 'POST' request to URL : " + url);
System.out.println("Post parameters : " + urlParameters);
System.out.println("Response Code : " + responseCode);
BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
//print result
System.out.println(response.toString());
}
您正在使用grails,因此您也可以使用如下所示的groovy HTTPBuilder