我正在为Java开发一个小型REST客户端,并且我在测试时使用GitHub的API。 我似乎无法弄清楚我做错了什么,这是发出https请求的代码。
链接到回购:https://github.com/sigurdsvela/JREST
HttpURLConnection connection = (HttpURLConnection)ourl.openConnection();
if (protocol == Protocol.HTTPS) { //protocol is Protocol.HTTPS
SSLSocketFactory sslsocketfactory = (SSLSocketFactory) SSLSocketFactory.getDefault();
((HttpsURLConnection) connection).setSSLSocketFactory(sslsocketfactory);
}
System.out.println("Sending " + method + " request to " + ourl + "?" + urlParameters);
connection.setRequestMethod(method.getName());
connection.setRequestProperty("Content-Type", "application/json");
connection.setRequestProperty("Content-Length", "" + Integer.toString(urlParameters.toString().getBytes().length));
connection.setRequestProperty("Content-Language", "en-US");
connection.setUseCaches (false);
connection.setDoInput(true);
connection.setDoOutput(true);
//Send request
DataOutputStream wr = new DataOutputStream( connection.getOutputStream() );
wr.writeBytes(urlParameters.toString());
wr.flush();
wr.close();
System.out.println("Server responded with " + connection.getResponseCode() + " " + connection.getResponseMessage());
//Get Response
InputStream is = connection.getInputStream();
当我运行此代码时,我从最后一行获得一个FileNotFound,并且System.out.println(“服务器响应了......打印服务器响应404未找到。
System.out.println(“正在发送”+方法....打印出它请求的网址。我将其复制粘贴到我的浏览器中,然后它运行正常。我做了一些错误的假设吗?是有一些我忘记了。
我发送了一个。
我还尝试删除if(protocol == Protocol.HTTPS)条件并使其始终为HttpsURLConnection,而不是强制转换它。这也不起作用,我仍然得到一个404同样的消息。
我正在测试的网址,如果相关的话: api.github.com/repos/sigurdsvela/loveletters