1

我正在使用 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();
    }
}
4

1 回答 1

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);
}
于 2011-12-24T13:59:38.820 回答