在Java中调用Get Request时收到404错误

时间:2018-12-04 09:09:47

标签: java rest

我试图在特定的API端点上调用GET请求以获取产品信息。我有两个netbeans项目,一个用于我拥有端点的服务器,另一个用于我的GUI。

在我的GUI类中,我具有用于获取产品信息的按钮,并且我试图将返回的JSON放入Swing中的TextArea中。我的GUI项目中有两个类,一个用于客户端get(将字符串作为字符串返回json),另一个用于jFrame。

  

奇怪的是,当我在按钮上调用客户类时,我得到:   !线程“ AWT-EventQueue-0”中的异常java.lang.RuntimeException:失败>:HTTP错误代码:404

当我简单地自己运行客户端类时,确实会在控制台中获得预期的输出,如果有人可以帮助,不确定如何解决此问题?

ClientCall.java

public class ClientCall{

String tempOut = "";

public String getProduct() throws ClientProtocolException, IOException  {

    DefaultHttpClient httpClient = new DefaultHttpClient();
    HttpGet getRequest = new HttpGet(
            "http://localhost:8080/api/product/1");
    getRequest.addHeader("accept", "application/json");

    HttpResponse response = httpClient.execute(getRequest);

    if (response.getStatusLine().getStatusCode() != 200) {
            throw new RuntimeException("Failed : HTTP error code : "
               + response.getStatusLine().getStatusCode());
    }

    BufferedReader br = new BufferedReader(
             new InputStreamReader((response.getEntity().getContent())));

    String output;
    System.out.println("Output from Server .... \n");
    while ((output = br.readLine()) != null) {
            System.out.println(output);
    }
    tempOut = output;
    httpClient.getConnectionManager().shutdown();

    return tempOut;
}

/*public static void main(String args[]) throws IOException{
    ClientCall c = new ClientCall();
    System.out.println(c.getProduct());
}*/

}

GUI.java

private void jButton1MouseClicked(java.awt.event.MouseEvent evt) {                                      
    // TODO add your handling code here:
    System.out.print("!");
    try {
        System.out.println(cc.getProduct());

    } catch (IOException ex) {
        Logger.getLogger(GetDetailsGUI.class.getName()).log(Level.SEVERE, null, ex);
    }
}    

注意,在我上面的代码(GUI)中,我只是输出响应,即使此操作也不起作用。

0 个答案:

没有答案