我正在使用FALCON语义搜索引擎RESTful API&写了这个程序 但是没有得到应该从搜索引擎响应的结果。请看代码&帮我。
package httpProject;
import java.io.*;
import java.net.*;
import java.lang.*;
public class HTTPRequestPoster {
public String sendGetRequest(String endpoint, String requestParameters) {
String result = null;
if (endpoint.startsWith("http://")) {
try {
String urlStr = endpoint;
if (requestParameters != null && requestParameters.length () > 0) {
urlStr += "?" + requestParameters;
}
URL url = new URL(urlStr);
URLConnection conn = url.openConnection ();
// Get the response
BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
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;
}
/**
* @param args
* @throws UnsupportedEncodingException
*/
public static void main(String[] args) throws UnsupportedEncodingException {
// TODO Auto-generated method stub
//HTTPRequestPoster a = new HTTPRequestPoster();//
HTTPRequestPoster astring = new HTTPRequestPoster ();
String param = "query=Person";
String stringtoreverse = URLEncoder.encode(param, "UTF-8");
astring.sendGetRequest("http://ws.nju.edu.cn/falcons/api/classsearch.jsp", stringtoreverse);
astring.toString();
System.out.println(astring);
//PrintStream.class.toString();
}
}
答案 0 :(得分:1)
除了两个小问题之外,你已经完成了所有繁重的工作:
URLEncoder.encode(...)
不应该在这里使用。 Javadoc表示将字符串转换为application/x-www-form-urlencoded
格式,即在执行POST
时。
astring.sendGetRequest(...)
而不是astring
本身应该被用作结果。
以下作品:
public static void main(String[] args) throws UnsupportedEncodingException {
// TODO Auto-generated method stub
//HTTPRequestPoster a = new HTTPRequestPoster();//
HTTPRequestPoster astring = new HTTPRequestPoster ();
String param = "query=Person";
String result = astring.sendGetRequest("http://ws.nju.edu.cn/falcons/api/classsearch.jsp", param);
System.out.println(result);
}