Getting "SocketException Connection Reset" while invoking Jenkins API - java

I have a sample Java Program which connects to a particular Jenkins URL connection and calls one API. The program was working few days ago, but suddenly it has started showing SocketException Connection Reset for all the calls. I am unable to figure out what configuration has gone for a change in Jenkins Config.
Note: The below piece of code is working for all other URLs except this Jenkins setup. What could have gone wrong? Even I am able to call the API via postman.
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class Main {
public static String getReq(String URL, String serviceName) {
StringBuffer response = new StringBuffer();
try {
URL obj = new URL(
"https://jenkins.abcdef.com/cid/jobs/abc/config.xml");
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("GET"); //$NON-NLS-1$
con.setRequestProperty("User-Agent", "Mozilla/5.0"); //$NON-NLS-1$ //$NON-NLS-2$
int responseCode = con.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
}
} catch (Exception e) {
e.printStackTrace();
}
return response.toString();
}
public static void main(String[] args) {
getReq(null, null);
}
}

Seems that you are missing a:
con.connect();
right before this line:
int responseCode = con.getResponseCode();

Related

How to resolve: Server redirected too many times?

Looked through stackoverflow for resolutions, and found this but that didn't help.
Getting this exception
java.net.ProtocolException: Server redirected too many times (20)
at java.base/sun.net.www.protocol.http.HttpURLConnection.getInputStream0(HttpURLConnection.java:1932)
at java.base/sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1520)
at java.base/sun.net.www.protocol.https.HttpsURLConnectionImpl.getInputStream(HttpsURLConnectionImpl.java:250)
at GetMailStatus.main(GetMailStatus.java:27)
for this block of code that's trying to access an InformedDelivery url with credentials
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.*;
import java.util.Base64;
public class GetMailStatus {
public static void main(String[] args) {
try {
URL url = new URL ("https://informeddelivery.usps.com/.........");
String encoding = Base64.getEncoder().encodeToString(("xxxx:yyyy").getBytes("UTF-8"));
CookieManager msCookieManager = new java.net.CookieManager(null, CookiePolicy.ACCEPT_ALL);
CookieHandler.setDefault(msCookieManager);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setDoOutput(true);
connection.setRequestProperty ("Authorization", "Basic " + encoding);
InputStream content = (InputStream)connection.getInputStream();
BufferedReader in =
new BufferedReader (new InputStreamReader (content));
String line;
while ((line = in.readLine()) != null) {
System.out.println(line);
}
} catch(Exception e) {
e.printStackTrace();
}
}
}
The code was modified based on the referenced stackoverflow discussion. I'm assuming I'm still not managing cookies correctly. Any suggestions?

DB2: The user defined function or procedure was unable to map to a single Java method

It seems as if the procedure is not able to find the java method inside the jar file,
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import org.json.JSONObject;
public class SecurityServiceClient {
private static String executePost(String targetURL, String urlParameters) {
HttpURLConnection connection = null;
try {
// create connection
URL url = new URL(targetURL);
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.setRequestProperty("Content-Length", Integer.toString(urlParameters.getBytes().length));
connection.setRequestProperty("Content-Language", "en-US");
connection.setUseCaches(false);
connection.setDoOutput(true);
// send request
DataOutputStream wr = new DataOutputStream(connection.getOutputStream());
wr.writeBytes(urlParameters);
wr.close();
// check response code
InputStream is = null;
int responseCode = connection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK)
is = connection.getInputStream();
else
is = connection.getErrorStream();
// get response
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
StringBuilder response = new StringBuilder();
String line;
while ((line = rd.readLine()) != null) {
response.append(line);
response.append(System.lineSeparator());
}
rd.close();
return response.toString();
}
catch (Exception e) {
e.printStackTrace();
return null;
}
finally {
if (connection != null)
connection.disconnect();
}
}
public static String getSecurityServiceAccessToken(String host, String userName, String password, String applicationInfo) {
String targetURL = String.format("https://some/rest/service/call");
String urlParameters = String.format("username=%1$s&password=%2$s&applicationInfo=\"%3$s\"", userName, password, applicationInfo);
JSONObject response = new JSONObject(executePost(targetURL, urlParameters));
return response.getString("accessToken");
}
}
This class has 2 methods:
-getSecurityServiceAccessToken() - internally calls method
-executePost()
I am trying to call the above code from the below procedure:
CREATE OR REPLACE PROCEDURE schema.PROC_TEST2 (IN HOST VARCHAR(255), IN USERNAME VARCHAR(255))
LANGUAGE JAVA
EXTERNAL NAME 'jarID:SecurityServiceClient.getSecurityServiceAccessToken'
PARAMETER STYLE JAVA
Getting the following error:
Received error code:
DB21034E The command was processed as an SQL statement because it was
not a valid Command Line Processor command. During SQL processing it
returned: SQL20204N The user defined function or procedure
"schema.PROC_TEST2" was unable to map to a single Java method. LINE
NUMBER=2. SQLSTATE=46008

I want to get result json from goeuro api

I am developing API in java to get json from GoEuro API is available at github. i want to know parameter i need to send with POST method and get result as json and combined with my custom logic.
Here is my java code to call api.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
public class JsonEncodeDemo {
public static void main(String[] args) {
try {
URL url = new URL("http://www.goeuro.com/GoEuroAPI/rest/api/v3/search?departure_fk=318781&departure_date=16%2F04%2F2017&arrival_fk=380553&trip_type=one-way&adults=1&children=0&infants=0&from_filter=Coventry+%28COV%29%2C+United+Kingdom&to_filter=London%2C+United+Kingdom&travel_mode=bus&ab_test_enabled=");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
// conn.setRequestMethod("GET");
conn.setRequestProperty("Accept", "application/json");
if (conn.getResponseCode() != 200) {
throw new RuntimeException("Failed : HTTP error code : " + conn.getResponseCode());
}
BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream()), "UTF-8"));
String output;
System.out.println("Output from Server .... \n");
while ((output = br.readLine()) != null) {
System.out.println(output);
}
conn.disconnect();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
I am not good in nodejs. Any Help would be appreciated.
First of all the url needs to be only this http://www.goeuro.com/GoEuroAPI/rest/api/v3/search
Then you need to add parameters using params in request.
Your if response != 200 has to be after you make the request.
public static void main(String[] args) {
try {
URL url = new URL("http://www.goeuro.com/GoEuroAPI/rest/api/v3/search);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("POST");
con.setRequestProperty("Accept", "application/json");
String urlParameters = "departure_fk=318781&departure_date=16%2F04%2F2017&arrival_fk=380553&trip_type=one-way&adults=1&children=0&infants=0&from_filter=Coventry+%28COV%29%2C+United+Kingdom&to_filter=London%2C+United+Kingdom&travel_mode=bus&ab_test_enabled=";
// Send post request
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(urlParameters);
wr.flush();
wr.close();
int responseCode = con.getResponseCode();
System.out.println("\nSending 'POST' request to URL : " + url);
System.out.println("Post parameters : " + urlParameters);
System.out.println("Response Code : " + responseCode);
BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
//print result
System.out.println(response.toString());
}
However, i found my answers from github issue.
Here are required params and there expected json format.
{
"arrivalPosition":{
"positionId":380244
},
"currency":"EUR",
"departurePosition":{
"positionId":380553
},
"domain":"com",
"inboundDate":"2017-04-19T00:00:00.000",
"locale":"en",
"outboundDate":"2017-04-18T00:00:00.000",
"passengers":[
{
"age":18,
"rebates":[]
}
],
"resultFormat":{
"splitRoundTrip":true
},
"searchModes":[
"directbus"
]
}

Reading REST Request Output using HttpURLConnection

I am trying to do REST request on the StackExchange API on java and I have some problems to read the output. I made a small code example to see if I can read properly:
package Utils;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class RestClient
{
public static void main(String[] args)
{
try
{
URL url = new URL("https://api.stackexchange.com/2.2/questions?order=desc&sort=activity&site=stackoverflow");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
System.out.println(conn.getResponseCode());
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String output;
while ((output = reader.readLine()) != null)
{
System.out.println(output);
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
Below is a sample output from the website:
{"items":[{"tags":["c++","templates","covariant"],"owner":{"reputation":3,"user_id":7447292,"user_type":"registered","profile_image":"https://www.gravatar.com/avatar/8979f1b328b9b0f786dec8b4edd514bc?s=128&d=identicon&r=PG&f=1","display_name":"B.Oudot","link":"http://stackoverflow.com/users/7447292/b-oudot"}
However when I print the output of my java program, I get the status code 200 and then the rest is just bunch of non-ascii characters. I am new with REST and JSON. I would like to not use any 3rd party library if possible.
EDIT
I have put the output of my program as an image.
you need to use GZIPInputStream api, when the content encoding used gZip. it is also an inputstream.
i used gipinput stream to your response and i see output in json.
public static void main(String[] args){
try
{
URL url = new URL("https://api.stackexchange.com/2.2/questions?order=desc&sort=activity&site=stackoverflow");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
System.out.println(conn.getResponseCode());
GZIPInputStream gzis = new GZIPInputStream(conn.getInputStream());
InputStreamReader reader = new InputStreamReader(gzis);
BufferedReader in = new BufferedReader(reader);
String readed;
while ((readed = in.readLine()) != null) {
System.out.println(readed);
}
//BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String output;
while ((output = in.readLine()) != null)
{
System.out.println(output);
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
it worked for me.

HttpURLConnection GET call with parameters not working

I have a very simple code which is not working.
Class HttoCon:
package test;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
public class HttpCon {
public static void main(String[] args) {
try {
sendGet();
} catch (Exception e) {
e.printStackTrace();
}
}
// HTTP GET request
private static void sendGet() throws Exception {
String url = "http://myweb.com/public/resource/data/stream";
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
// optional default is GET
con.setRequestMethod("GET");
//add request header
con.setRequestProperty("begin", "1430295300000");
con.setRequestProperty("end", "1430297279988");
con.setRequestProperty("id", "140621");
con.setRequestProperty("time", "FIFTEEN_MINUTE");
int responseCode = con.getResponseCode();
System.out.println("\nSending 'GET' request to URL : " + url);
System.out.println("Response Code : " + responseCode);
BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
//print result
System.out.println(response.toString());
}
}
Error Trace:
{"fault":{"exceptionType":"MissingServletRequestParameterException","host":"12.205.101.123","cause":"Required Long parameter 'id' is not present","status":"400","query":"/public/resource/data/stream","stackTrace":"org.springframework.web.bind.MissingServletRequestParameterException: Required Long parameter 'id' is not present\n\tat org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter$ServletHandlerMethodInvoker.raiseMissingParameterException(AnnotationMethodHandlerAdapter.java:774)\n\tat org.springframework.web.bind.annotation.support.HandlerMethodInvoker.resolveRequestParam(HandlerMethodInvoker.java:509)\n\tat
NOTE:
If I hit the url directly in browser it works fine.
http://myweb.com/public/resource/data/stream?begin=1430295300000&end=1430297279988&id=140621&time=FIFTEEN_MINUTE
UPDATE:
Using curl:
curl -X GET http://myweb.com/public/resource/data/stream?begin=1430295300000&end=1430297279988&id=140621&time=FIFTEEN_MINUTE
Above curl doesn't work and the exception is same -
curl -X GET 'http://myweb.com/public/resource/data/stream?begin=1430295300000&end=1430297279988&id=140621&time=FIFTEEN_MINUTE'
This curl works fine.
You create a String containing the parameters, which then gets appended onto the URL. Create a URL Obj from this. For example :-
String this.url = "http://myweb.com/public/resource/data/stream";
this.url += "?begin=1430295300000&end=1430297279988&id=140621
&time=FIFTEEN_MINUTE";
this.urlObj = new URL(this.url);
Then you create the connection as in your original example.
openConnection will establish the connection and issue the GET. Subsequent settings of GET parameters on the returned URLConnection object are ignored, since the URL has already been open.
Add the parameters to the URL as query string params just as the link above and open that link
or
try to post the parameters to the server (which is even better)

Categories

Resources