0

我对 gae 有意见。我有一个应用程序http://www.similarityface.appspot.com/query。我正在尝试通过 java 中的程序与此应用程序通信以通过 POST 方法执行查询。产生 500 错误的问题。代码如下,有人可以帮我告诉我做错了什么。

public class Vetores_Facebook {
   public static void main(String[] args) throws UnsupportedEncodingException, IOException {
        final String server = "https://www.similarityface.appspot.com/query";
        URL url = null;
        try {
            url = new URL(server);

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

    HttpURLConnection urlConn = null;
    try {
        // URL connection channel.
        urlConn = (HttpURLConnection) url.openConnection();

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


    urlConn.setDoOutput (true);

    // No caching, we want the real thing.
    urlConn.setUseCaches (false);

    try {    

        urlConn.setRequestMethod("POST");
    } catch (ProtocolException ex) {
        Logger.getLogger(Vetores_Facebook.class.getName()).log(Level.SEVERE, null, ex);
    }

    try {

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

    String message = URLEncoder.encode("get_object(\"me\", metadata=1)", "UTF-8");
    try (OutputStreamWriter writer = new OutputStreamWriter(urlConn.getOutputStream())) {
        writer.write(message);
        writer.close();

    }



     if (urlConn.getResponseCode() == HttpURLConnection.HTTP_OK) {
         System.out.println("ok");
        }
     else{
            int x = urlConn.getResponseCode();
            System.out.println("error "+x);

     }
 }
}
4

1 回答 1

0
try {

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

String message = URLEncoder.encode("get_object(\"me\", metadata=1)", "UTF-8");
try (OutputStreamWriter writer = new OutputStreamWriter(urlConn.getOutputStream())) {
    writer.write(message);
    writer.close();

}

问题是您正在调用 urlConn.connect(); 这似乎会刷新您可能拥有的任何输出缓冲区并准备连接以获取输入流。在此之后尝试写入以打开输出流将导致异常。

使用此处给出的示例获取正确的方法:https ://developers.google.com/appengine/docs/java/urlfetch/usingjavanet#Using_HttpURLConnection

于 2013-05-23T15:31:04.073 回答