我正在尝试将桌面应用程序的评论发布到Trac。
我在这个项目中使用apache http客户端库这里是link
这是我的代码,对不起,如果难以阅读
public class TestComment {
private static String cookie;
public static void main(String[] args) throws Exception {
CookieHandler.setDefault(new CookieManager());
DefaultHttpClient defaultHttpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet("http://localhost:8080/mytrac/login");
BasicHeader authHeader = new BasicHeader("Authorization", "Basic " + encodedPassword("admin", "123123"));
httpGet.addHeader(authHeader);
HttpResponse response = defaultHttpClient.execute(httpGet);
List<Cookie> cookies = defaultHttpClient.getCookieStore().getCookies();
String token = null;
if(!cookies.isEmpty()){
for (int i = 0; i < cookies.size(); i++) {
System.out.println("- " + cookies.get(i).toString());
token = cookies.get(i).toString().substring(43, 67);
System.out.println(token);
}
}
setCookie(token);
responseLog(response);
HttpPost httpPost = new HttpPost("http://localhost:8080/mytrac/ticket/2#comment:5");
httpPost.setHeader(authHeader);
httpPost.setHeader("Host", "localhost:8080");
httpPost.setHeader("User-Agent", "Mozilla/5.0");
httpPost.setHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
httpPost.setHeader("Accept-Language", "en-US,en;q=0.8");
httpPost.setHeader("Connection", "keep-alive");
httpPost.setHeader("Referer", "http://localhost:8080/mytrac/ticket/2");
httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
List<NameValuePair> formparams = new ArrayList<NameValuePair>();
formparams.add(new BasicNameValuePair("__FORM_TOKEN", token));
formparams.add(new BasicNameValuePair("comment", "Test comment"));
formparams.add(new BasicNameValuePair("field_reporter", "admin"));
httpPost.setEntity(new UrlEncodedFormEntity(formparams));
response = defaultHttpClient.execute(httpPost);
responseLog(response);
System.out.println(response.getStatusLine());
}
private static String encodedPassword(String username, String password) {
byte[] encodedPassword = (username + ":" + password).getBytes();
BASE64Encoder base64Encoder = new BASE64Encoder();
return base64Encoder.encode(encodedPassword);
}
private static void responseLog(org.apache.http.HttpResponse httpResponse) throws IOException {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(httpResponse. getEntity().getContent()));
StringBuffer stringBuffer = new StringBuffer();
String line1;
while ((line1 = bufferedReader.readLine()) != null) {
stringBuffer.append(line1 + "\n");
}
System.out.println(stringBuffer) ;
}
public static String getCookie() {
cookie = cookie.substring(cookie.indexOf(":") + 1);
return cookie;
}
public static void setCookie(String cookie) {
TestComment.cookie = cookie;
}
}
当我运行此代码时,我得到了200个代码,它告诉了我,我甚至在Text-Aria表单中得到了我的评论,但是不发布它。当我在浏览器中发表评论时,代码是303.我错在哪里,可能是我完全错误的方式?
答案 0 :(得分:0)
我们解决了问题
我不知道,但我只需要再发送一个表单,我们需要从trac获取查看时间并将其作为表单发送:
formparams.add(new BasicNameValuePair("view_time", view_time));
现在可行了