【问题标题】:Receiving response from CURL in JAVA在 JAVA 中接收来自 CURL 的响应
【发布时间】:2013-03-20 05:56:03
【问题描述】:

我正在使用 Sentiment-140 提供的公共 API 来查找小文本是正面的、负面的还是中性的。虽然我可以成功使用他们简单的 HTTP-JSON 服务,但我在使用 CURL 时失败了。这是我的代码:

public static void makeCURL(String jsonData) throws MalformedURLException, ProtocolException, IOException {
    byte[] queryData = jsonData.getBytes("UTF-8");

    Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("10.1.1.1", 8080));
    HttpURLConnection con = (HttpURLConnection) new URL("http://www.sentiment140.com/api/bulkClassifyJson").openConnection(proxy);
    con.setRequestMethod("POST");
    con.setDoOutput(true);

    OutputStream os = con.getOutputStream();
    InputStream instr = con.getInputStream();
    BufferedReader br = new BufferedReader(new InputStreamReader(instr));

    os.write(queryData);
    os.close();
    String lin;
    while((lin = br.readLine())!=null){
        System.out.println("[Debug]"+lin); // I expect some response here But it's not showing anything            
    }
}

我做错了什么?

【问题讨论】:

  • 您的代理需要身份验证吗?有什么例外吗?堆栈跟踪?
  • 无身份验证。我可以成功地使用类似的技术来获得常规的 HTTP 响应...
  • 尝试移动这些行: InputStream instr = con.getInputStream(); BufferedReader br = new BufferedReader(new InputStreamReader(instr));在 os.write() 和 os.close() 之后。
  • 移动了行。还是不行……

标签: java json http curl sentiment-analysis


【解决方案1】:

您应该在获取连接输入流之前发送所有请求数据。

byte[] queryData = jsonData.getBytes("UTF-8");
Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("10.1.1.1", 8080));
HttpURLConnection con = (HttpURLConnection) new URL("http://www.sentiment140.com/api/bulkClassifyJson").openConnection(proxy);
con.setRequestMethod("POST");
con.setDoOutput(true);
OutputStream os = con.getOutputStream();
os.write(queryData);
os.close();

InputStream instr = con.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(instr));
String lin;
while((lin = br.readLine())!=null){
    System.out.println("[Debug]"+lin);
}

【讨论】:

    猜你喜欢
    • 2021-06-05
    • 1970-01-01
    • 2020-09-19
    • 2020-05-13
    • 1970-01-01
    • 2017-01-02
    • 2022-12-18
    • 2013-05-13
    • 1970-01-01
    相关资源
    最近更新 更多