I am trying to do a simple HTTP Get and POST request in java to my Eclipse Kura gateway but i dont know how to authenticate using username and password. I tried using the url syntax http://user:pw#ipaddress:port/ but i still get HTTP error code 401.
import java.io.*;
import java.net.*;
public class HTTP {
public static String getHTML() throws Exception {
StringBuilder result = new StringBuilder();
String urlToRead = "http://user:pw#ipaddress:port";
URL url = new URL(urlToRead);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
while ((line = rd.readLine()) != null) {
result.append(line);
}
rd.close();
return result.toString();
}
public static void main(String[] args) throws Exception {
System.out.println(getHTML());
}
}
I believe that you are not providing the credentials in the desired way. This very similar question already has an accepted answer, in which James Van Huis suggests using java.net.Authenticator for setting authentication data prior to opening any connections.
Related
I am currently learning to consume an API in Java, I am using the Exchange Rates API, however, it failed to understand what is happening, I send all the requested parameters and I also send my API key as header.
private static void sendHttpGETRequest(String fromCode, String toCode, double amount) throws IOException, JSONException{
String GET_URL = "https://api.apilayer.com/exchangerates_data/convert?to="+toCode+"&from="+fromCode+"&amount="+amount;
URL url = new URL(GET_URL);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setReadTimeout(200 * 1000);
httpURLConnection.setConnectTimeout(200 * 1000);
httpURLConnection.setRequestMethod("GET");
httpURLConnection.setRequestProperty("apikey", "MyApiKeY");
int responseCode = httpURLConnection.getResponseCode();
System.out.println("Response code: " + responseCode);
if(responseCode == httpURLConnection.HTTP_OK){//SUCESS
BufferedReader in = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while((inputLine = in.readLine()) != null){
response.append(inputLine);
}in.close();
JSONObject obj = new JSONObject(response.toString());
Double exchangeRate = obj.getJSONObject("rates").getDouble(fromCode);
System.out.println(obj.getJSONObject("rates"));
System.out.println(exchangeRate); //keep for debugging
System.out.println();
}
else {
System.out.println("GET request failed");
}
}
I have used setConnectTimeout and setReadTimeout to set the network timeout thinking that was the problem but still getting the same error.
I ran into a similar issue while using Spring Web's RestTemplate to try and make the API call.
APILayer is using OKHttpClient (from the okhttp3 library) for their demo samples.
This fixed it for me.
Here is what this could look like for you:
import java.io.*;
import okhttp3.*;
public class main {
public static void main(String []args) throws IOException{
OkHttpClient client = new OkHttpClient().newBuilder().build();
Request request = new Request.Builder()
.url("https://api.apilayer.com/exchangerates_data/convert?to=to&from=from&amount=amount")
.addHeader("apikey", "MyApiKeY")
.method("GET", })
.build();
Response response = client.newCall(request).execute();
System.out.println(response.body().string());
}
}
Hello I'm wondering how could I make a https request for soap API.
In Android app, I had searched a lot but there isn't clear tutorial explaining how to do that.
Any suggestion or help please?
Thanks
import java.io.*;
import java.net.*;
import javax.net.ssl.*;
public class HttpsClient {
public static void main(String[] args) throws Exception {
String httpsURL = "https://postman-echo.com/post";
URL myUrl = new URL(httpsURL);
HttpURLConnection conn = (HttpsURLConnection) myUrl.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("POST");
OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream());
out.append("<xml><body>your SAOP request here</body></xml>");
BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String inputLine;
System.out.println("Response code is : "+conn.getResponseCode());
System.out.print("Response text is :");
while ((inputLine = br.readLine()) != null) {
System.out.println(inputLine);
}
out.flush();
out.close();
br.close();
}
}
SOAP request is also an http POST with an xml in the request body. You need to change the url to the web service endpoint url and replace the sample string with your SOAP request.
I have a command line:
curl -u username:passwd -k "https://myserver/a/b/c"
It works and I will get right information when I call it under Ubuntu or Cygwin.
Now I am willing to accomplish it in Java. So I have Java code like that:
public class Test {
public static String auth = "username:passwd";
public static String url = "https:/myserver/a/b/c";
public static void main(String[] args) {
try {
URL url = new URL(url);
final byte[] authBytes = auth.getBytes(StandardCharsets.UTF_8);
String encoding = java.util.Base64.getEncoder().encodeToString(authBytes);
HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Authorization", encoding);
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
System.out.println(line);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
But It seems not work and always return HTTP response code 411.
Is there something wrong with the java code?
Thanks in advanced.
HTTP response code 411 means that "The server refuses to accept the request without a defined Content- Length."
http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html
HttpsUrlConnection should be able to do that for you. Check out setFixedLengthStreamingMode(). I think you will also need to setDoOutput().
I am learning to how to use http request. The following is the code which return JSON. All I am doing is to get it and print it. But I am facing some error. The error is also given below.
import java.io.*;
import java.net.*;
public class ZipTester {
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
URL stck = new URL("http://www.zipfeeder.us/zip?key=Ect9O9ta&zips=14623");
URLConnection yc = stck.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(yc.getInputStream()));
String inputLine;
String add="";
while ((inputLine = in.readLine()) != null) {
//System.out.println(inputLine);
add=add+inputLine;
}
in.close();
System.out.println(add);
}
}
This is the error. In my old machine this code worked perfectly fine. I just got a new machine this week. The same code is now not working. previously I was using jdk 1.7 and now i am using jdk 1.8
Exception in thread "main" java.io.IOException: Server returned HTTP response code: 403 for URL: http://www.zipfeeder.us/zip?key=Ect9O9ta&zips=14623
at sun.net.www.protocol.http.HttpURLConnection.getInputStream0(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(Unknown Source)
at ZipTester.main(ZipTester.java:11)
You can fix your code with adding user-agent header like this :
yc.addRequestProperty("User-Agent",""); //to avoid 403 error
The website had probably change it access rules and now it request a "user-agent".
The full code :
import java.io.*;
import java.net.*;
public class ZipTester {
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
URL stck = new URL("http://www.zipfeeder.us/zip?key=Ect9O9ta&zips=14623");
URLConnection yc = stck.openConnection();
yc.addRequestProperty("User-Agent",""); //to avoid 403 error
BufferedReader in = new BufferedReader(new InputStreamReader(yc.getInputStream()));
String inputLine;
String add="";
while ((inputLine = in.readLine()) != null) {
add=add+inputLine;
}
in.close();
System.out.println(add);
}
}
I hope it will help you.
Regards.
I fixed this issue by setting the user agent with a following value:
yc.setRequestProperty("User-Agent","Mozilla/5.0");
I've created a Java class that connects to an IIS website requiring NTLM authentication. The Java class uses the JCIFS library and is based on the following example:
Config.registerSmbURLHandler();
Config.setProperty("jcifs.smb.client.domain", domain);
Config.setProperty("jcifs.smb.client.username", user);
Config.setProperty("jcifs.smb.client.password", password);
URL url = new URL(location);
BufferedReader reader = new BufferedReader(
new InputStreamReader(url.openStream()));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
The example works fine when executed from the command prompt, but as soon as I try to use the same code in a servlet container (specifically GlassFish), I get an IOException containing the message "Server returned HTTP response code: 401 for URL: ....".
I've tried moving the jcifs jar to the system classpath (%GLASSFISH%/lib), but that doesn't seem to make any difference.
Suggestions are highly appreciated.
It seems that what I was trying to do is already supported in Java 5/6 and I was therefore able to drop the JCIFS API and do something like this instead:
public static String getResponse(final ConnectionSettings settings,
String request) throws IOException {
String url = settings.getUrl() + "/" + request;
Authenticator.setDefault(new Authenticator() {
#Override
public PasswordAuthentication getPasswordAuthentication() {
System.out.println(getRequestingScheme() + " authentication")
// Remember to include the NT domain in the username
return new PasswordAuthentication(settings.getDomain() + "\\" +
settings.getUsername(), settings.getPassword().toCharArray());
}
});
URL urlRequest = new URL(url);
HttpURLConnection conn = (HttpURLConnection) urlRequest.openConnection();
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setRequestMethod("GET");
StringBuilder response = new StringBuilder();
InputStream stream = conn.getInputStream();
BufferedReader in = new BufferedReader(new InputStreamReader(stream));
String str = "";
while ((str = in.readLine()) != null) {
response.append(str);
}
in.close();
return response.toString();
}
Sounds like JCIFS does not have the right to set a factory for handling your URLs inside Glassfish. You should check the policy settings (checkSetFactory).
The Config#registerSmbURLHandler() might swallow the SecurityException.