【问题标题】:How to get URIs by using Falcon RESTful API如何使用 Falcon RESTful API 获取 URI
【发布时间】:2012-01-27 07:34:34
【问题描述】:

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

【问题讨论】:

  • 这不是你的问题,但你永远不需要做import java.lang.*;,因为Java会自动为你做这件事。一直都有。
  • 是的,但删除 import java.lang.* 后将无法使用;
  • 删除后不起作用?!要么你有与 HTTPRequestPoster 相同的包中的类,但名称选择非常糟糕,或者这个世界确实很奇怪。

标签: java httpwebrequest asp.net-web-api


【解决方案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);
}

【讨论】:

  • 感谢您的建议,但我需要将字符串编码为 UTF-8 格式
  • 它是 Java,所以你不需要明确地这样做。
猜你喜欢
  • 1970-01-01
  • 2023-03-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-10-20
  • 2013-12-01
  • 2020-05-31
相关资源
最近更新 更多