Java GitHub HTTPS/SSL request gives 404 response - java

I’m developing a small REST client for Java, and my using GitHub’s API while testing.
I can’t seem to figure out what i’v done wrong, here is the code that makes the https request.
Link to the repo: 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();
When I run this code i get a FileNotFound from the last line, and the System.out.println("Server responded whi.... print that the server responded with 404 Not Found.
The System.out.println("Sending " + method.... print out the url its requesting. I’ve copy pasted it into my browser, and then it works fine. Am i making some false assumption? Is there something i have forgotten.
I'm sending a get.
I've also tried to remove the if (protocol == Protocol.HTTPS) condition and have it always be a HttpsURLConnection, instead of casting it. That didn't work either, and I was still getting a 404 with the same message.
The URL I’m testing against, if relevant is:
api.github.com/repos/sigurdsvela/loveletters

Related

Why does discord return 403 on any request?

I am trying to send https request to discord api form java, but discord is responding with 403. My code is:
String query = "client_id=id" +
"&client_secret=secret" +
"&grant_type=authorization_code" +
"&code=" + code +
"&redirect_uri=" + URLEncoder.encode("https://discordapi.tridentgames.eu/oauth2", StandardCharsets.UTF_8.toString());
HttpsURLConnection connection = (HttpsURLConnection) new URL("https://discord.com/api/oauth2/token").openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-length", String.valueOf(query.length()));
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.setDoOutput(true);
connection.setDoInput(true);
DataOutputStream output = new DataOutputStream(connection.getOutputStream());
output.writeBytes(query);
output.close();
DataInputStream input = new DataInputStream(connection.getInputStream());
for (int c = input.read(); c != -1; c = input.read())
System.out.print((char) c);
input.close();
It is running in pterodactyl's docker container. I tried to execute the same request from postman and it is ok, even I was unsuccesfull when I tried to recreate the 403 error from postman. I also tried to change the URL, but result is same even with only https://discord.com. I also tried to curl discord api from the docker container and it was ok. Also, the code is based on my older node.js code, that worked without any problems. Does anyone know what's wrong with my request?

What is format to send a response to an HttpURLConnection.getInputStream() and avoid "Invalid Http Response"?

My server sends a response to an HTTPUrlConnection in this manner:
ServerSocket servSok = new ServerSocket(portNmb);
Socket sok = servSok.accept();
processTheIncomingData(sok.getInputStream());
Writer wrtr = new OutputStreamWriter(sok.getOutputStream());
wrtr.write("<html><body>123 Hello World</body></html>"); // <------- format?
wrtr.flush();
the client
HttpURLConnection conn = (HttpUTLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setDoOutput(true);
conn.setDoInput(true);
sendSomeData(conn.getOutputStream());
String mssg = conn.getResponseMessage(); // <----- Invalid Http Response
conn.getResponseCode() also gives the same "Invalid http response."
I agree with #JBNizet. HTTP is a very complex protocol. You should use a server.
But if you are writing this for a toy project, here is some code to get you started.
Do not use any of this in production :)
String content = "<html><body>123 Hello World</body></html>";
Writer wrtr = new OutputStreamWriter(sok.getOutputStream());
wrtr.write("HTTP/1.1 200 OK\n");
wrtr.write("Content-Type: text/html; charset=UTF-8\n");
//assuming content is pure ascii
wrtr.write("Content-Length: " + content.length() + "\n");
wrtr.write("Connection: close\n\n");
wrtr.write(content);
wrtr.flush();
//then close the connection, do not reuse the connection
//as you might not have consumed the full request content

Difference between Java Post Request and browser post request

I am trying to use api of one popular russian social networks. I am using OAuth via Java HttpUrlConnection. The problem is, when I send post data via Java, I get 401 response code. When I copy request and paste it browser, I get redirect to URL containing access token I need. That means that my post request is correct, but why when I send it with Java I get 401 error? When I send request with incorrect password, I get 200. It means that request is correct too.
private void getHomeAuth() throws Exception {
String url = "https://oauth.vk.com/authorize?client_id=APP_ID&scope=friends&redirect_uri=https://oauth.vk.com/blank.html&display=page&v=5.34&response_type=token";
URL oauth = new URL(url);
HttpURLConnection connection = (HttpURLConnection) oauth.openConnection();
connection.setRequestMethod("GET");
connection.setRequestProperty("User-Agent", USER_AGENT);
int responseCode = connection.getResponseCode();
System.out.println("Response code: " + responseCode);
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String inputLine;
StringBuilder response = new StringBuilder();
while((inputLine = reader.readLine()) != null)
response.append(inputLine + "\n");
reader.close();
PrintWriter writer = new PrintWriter("auth.html");
writer.print(response);
writer.close();
parse();
cookies = connection.getHeaderField("Set-Cookie");
referer = connection.getURL().toString();
}
private void postAuth() throws Exception {
email = URLEncoder.encode("example#gmail.com", "UTF-8");
password = "password";
_origin = URLEncoder.encode(_origin, "UTF-8");
String url = "https://login.vk.com/?act=login&soft=1";
URL post = new URL(url);
String urlParameters = "ip_h=" + ip_h + "&_origin=" + _origin + "&to=" + to + "&expire=" + expire + "&email=" + email + "&pass=" + password;
HttpsURLConnection con = (HttpsURLConnection) post.openConnection();
con.setRequestMethod("POST");
con.setRequestProperty("User-Agent", USER_AGENT);
con.setRequestProperty("Cookie", cookies);
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(urlParameters);
wr.flush();
wr.close();
int responseCode = con.getResponseCode();
System.out.println("Sent post. Response code: " + responseCode + "\nRequest: " + post.toString() + urlParameters + "\nRequestMethod: " + con.getRequestMethod());
}
I also tryied to send this request via addon in browser, and the result was correct. I obtained access token from redirect link.
Maybe the problem is that something inside request is incorrect. I have tried to monitor requests from java app, but I failed.
My experience with this kind of problem is that the http request that first authenticates the user also puts cookies (scope varies from case to case) into the response and subsequent http requests are expected to contain those cookies. Look very closely at the complete returned response headers to see what cookies might have been returned.

Soap Http post request gives IOException

I'm trying to send a Soap request to a server.
This is my java code:
try {
String xmldata = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
"<SOAP-ENV:Envelope xmlns:SOAP-ENV=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:ns1=\"http://www.telenet.be/TelemeterService/\">\n" +
" <SOAP-ENV:Body>\n" +
" <ns1:RetrieveUsageRequest>\n" +
" <UserId>test</UserId>\n" +
" <Password>test</Password>\n" +
" </ns1:RetrieveUsageRequest>\n" +
" </SOAP-ENV:Body>\n" +
"</SOAP-ENV:Envelope>";
URL myurl = new URL("https://t4t.services.telenet.be/TelemeterService?wsdl");
HttpsURLConnection con = (HttpsURLConnection) myurl.openConnection();
con.setRequestMethod("POST");
con.setRequestProperty("Content-length", String.valueOf(xmldata.length()));
con.setRequestProperty("Content-Type", "text/xml; charset=\\\"utf-8\\\"\\r\\n");
con.setRequestProperty("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/34.0.1847.116 Safari/537.36");
con.setDoOutput(true);
con.setDoInput(true);
DataOutputStream output = new DataOutputStream(con.getOutputStream());
output.writeBytes(xmldata);
output.close();
DataInputStream input = new DataInputStream(con.getInputStream());
for (int c = input.read(); c != -1; c = input.read())
System.out.print((char) c);
input.close();
System.out.println("Resp Code:" + con.getResponseCode());
System.out.println("Resp Message:" + con.getResponseMessage());
}
catch (IOException se)
{
se.printStackTrace();
}
I get the exception:
java.io.IOException: Server returned HTTP response code: 500 for URL: https://t4t.services.telenet.be/TelemeterService?wsdl
I used this tool to be sure of my request: http://wsdlbrowser.com/soapclient?wsdl_url=https%3A%2F%2Ft4t.services.telenet.be%2FTelemeterService%3Fwsdl&function_name=retrieveUsage
I don't see whats wrong with my request.
When I get an internal server error, the first thing I do (and maybe you did) is to check the application server log. For some unexpected reason(s) the server cannot be reached.
I don't see any problem to get the wsdl first to check if you can use the web service. It is an approach I do all the time.
The ?wsdl at the end of the url are for getting the wsdl, for example in a browser. Try removing it , making the endpoint URL https://t4t.services.telenet.be/TelemeterService.

Blackberry Push Notification - Not receiving on Device

I am struggling for getting message on devices since last some days. At last I think to take a help from experts.
Below are the steps I have followed.
I have created Push initiator in core java.
note: I am getting response code : 200 OK - I assume that this message reaches to PPG for further processing - But not confirmed.
I have used sample Push Enabled Application for Blackberry Device -
I could able to register and waiting for messages on perticular port. but I am not receiving any messages :(
Now I am helpless, My question is
1. Does I am in right track
2. Is there any way to find out how to debug and where my messages are hanging.
I am waiting for some positive solution. Thanks in advance..
Here is my actual code for Push initiator for J2SE
StringBuffer dataToSend = new StringBuffer();
dataToSend.append("--" + BOUNDARY);
dataToSend.append(" ");
dataToSend.append("Content-Type: application/xml; charset=UTF-8");
dataToSend.append(" ");
dataToSend.append("<?xml version=\"1.0\"?>");
dataToSend
.append("<!DOCTYPE pap PUBLIC \"-//WAPFORUM//DTD PAP 2.1//EN\" \"http://www.openmobilealliance.org/tech/DTD/pap_2.1.dtd\" [<?wap-pap-ver supported-versions=\"2.0\"?>]>");
dataToSend.append("<pap>");
String myPushId = ""+ new Random().nextInt();
dataToSend.append("<push-message push-id=\"" + myPushId
+ "\" source-reference=\"" + applicationID + "\">");
dataToSend.append("<address address-value=\"" + pin + "\"/>");
dataToSend
.append("<quality-of-service delivery-method=\"confirmed\"/>");
dataToSend.append("</push-message>");
dataToSend.append("</pap> ");
dataToSend.append("--" + BOUNDARY);
dataToSend.append(" Content-Encoding: binary ");
dataToSend.append(" Content-Type: text/plain ");
dataToSend.append(" ");
dataToSend.append("X-Wap-Application-Id: " + applicationID);
dataToSend.append(" X-Rim-Push-Type: browser-channel X-Rim-Push-Title: Test X-Rim-Push-Unread-Icon: http://rim.com/icon_new.png ");
dataToSend.append("X-Rim-Push-Read-Icon: http://rim.com/icon_viewed.png ");
dataToSend.append("X-Rim-Delete-URL: http://rim.com/ReceiveDelete ");
dataToSend.append("X-Rim-Transcode-Content: */* ");
dataToSend.append("Cache-Control: max-age=3600 ");
dataToSend.append(msg);
dataToSend.append("--" + BOUNDARY + "--");
dataToSend.append(" ");
printer(dataToSend.toString());
// printer("-------------------------------------------------------------------");
String authInfo = applicationID + ":" + userPW;
String encoding = new sun.misc.BASE64Encoder().encode(authInfo
.getBytes());
// authInfo = Base64.encode(authInfo.getBytes());
authInfo = "Basic " + encoding;
printer(authInfo);
URL url;
HttpURLConnection connection = null;
try {
// Create connection
url = new URL(targetURL);
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type",
"multipart/related; boundary=" + BOUNDARY
+ "; type=application/xml");
connection.setRequestProperty("User-Agent",
"BlackBerry Push Service SDK/1.0");
// / connection.setRequestProperty("Authorization",
// authInfo.getBytes().toString());
connection.setRequestProperty("Authorization", authInfo);
connection.setRequestProperty("Accept",
"text/html, image/gif, image/jpeg, *; q=.2, */*; q=.2");
connection.setRequestProperty("Connection", "keep-alive");
connection.setRequestProperty("Content-Length",
"" + dataToSend.length());
connection.setDoInput(true);
connection.setDoOutput(true);
// Send request
DataOutputStream wr = new DataOutputStream(
connection.getOutputStream());
wr.writeBytes(dataToSend.toString());
wr.flush();
wr.close();
printer("" + connection.getResponseCode());
String response = connection.getResponseMessage();
printer(response);
// return response;

Categories