How to fix javax.net.ssl.SSLHandShakeException accessing JIRA - java

I want to match issues in JIRA with other datasource.
I can use curl:
curl -u myname:mypassword
https://jira.myorganization.com/rest/api/latest/issue/TR-1234
This will return info about the issue, for exampel TR-1234, that I want to check some data for.
In java I want to do the same thing but I get javax.net.ssl.SSLHandShakeException
The program I try to run:
import javax.net.ssl.HttpsURLConnection;
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 Main {
public static void main(String[] args) {
URL url = null;
try {
url = new URL("https://jira.myorganization.com/rest/api/latest/issue/TR-1234");
HttpsURLConnection con = (HttpsURLConnection) url.openConnection();
String userpass = "myusername:mypassword";
String basicAuth = "Basic " + new String(Base64.getEncoder().encode(userpass.getBytes()));
con.setRequestProperty ("Authorization", basicAuth);
con.setRequestMethod("GET");
con.setRequestProperty("Accept", "application/json");
System.out.println("Resp="+ con.getResponseCode()+" "+con.getResponseMessage());
String contentType = con.getHeaderField("Content-Type");
BufferedReader br = new BufferedReader(new InputStreamReader(
(con.getInputStream())));
String output;
System.out.println("Output from Server .... \n");
while ((output = br.readLine()) != null) {
System.out.println(output);
}
con.disconnect();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Can I somehow pass userid and password to the URL. The application is a tool and it would be ok to let the user input his name and password.

Related

Minecraft auth server returning 403?

So I'm trying to make a custom launcher for my custom Minecraft client but I need a session id to launch the game. This is the code I'm using to try and get a session ID:
package net.arachnamc;
import org.json.JSONObject;
import java.io.*;
import java.net.*;
import java.nio.charset.StandardCharsets;
import java.util.UUID;
public class Main {
public static void main(String[] args) throws IOException {
String AUTH_SERVER = "https://authserver.mojang.com/authenticate";
String json = String.format(
"{" +
"\"clientToken\":\"%s\"," +
"\"username\":\"%s\"," +
"\"password\":\"%s\"" +
"}",
UUID.randomUUID().toString(),
"Koolade446",
"MyPasswordCensored"
);
JSONObject jso = new JSONObject(json);
System.out.println(json);
URL url = new URL(AUTH_SERVER);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("POST");
urlConnection.setDoInput(true);
urlConnection.setDoOutput(true);
urlConnection.setRequestProperty("Content-Type", "application/json");
OutputStream os = urlConnection.getOutputStream();
os.write(json.getBytes(StandardCharsets.UTF_8));
os.close();
BufferedReader br = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
br.close();
urlConnection.disconnect();
}
}
However, the server returns a 403 forbidden every time. I use a Microsoft account but I can't find any documentation on how to authenticate a Microsoft account so I assumed this was it. Any help is appreciated.

Java and REST POST method - how to transform URL POST request to JSON Body POST Request?

I have class which works completely and sends POST request successfully toward the external system.
paramaters which are sent currently in the class are:
username:maxadmin
password:sm
DESCRIPTION: REST API test
Now I want to do copy paste of this class and transform it in that way so I could POST request using the JSON body but I am not sure how to do it.
I saw that I should probably have conn.setRequestProperty("Content-Type", "application/json"); instead of application/x-www-form-urlencoded
Can someone please transform my code in order to POST REQUEST using JSON body for parameters sending instead of URL?
This is my 'URL' working class (you will see username/password are in URL while parameters are send in array I have currently only one attribute DESCRIPTION which I am sending)
package com.getAsset;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import org.json.*;
public class GETAssetsPOST {
public static String httpPost(String urlStr, String[] paramName,
String[] paramVal) throws Exception {
URL url = new URL(urlStr);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setUseCaches(false);
conn.setAllowUserInteraction(false);
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
OutputStream out = conn.getOutputStream();
Writer writer = new OutputStreamWriter(out, "UTF-8");
for (int i = 0; i < paramName.length; i++) {
writer.write(paramName[i]);
writer.write("=");
writer.write(URLEncoder.encode(paramVal[i], "UTF-8"));
writer.write("&");
}
writer.close();
out.close();
if (conn.getResponseCode() != 200) {
throw new IOException(conn.getResponseMessage());
}
// Buffer the result into a string
BufferedReader rd = new BufferedReader(
new InputStreamReader(conn.getInputStream()));
StringBuilder sb = new StringBuilder();
String line;
while ((line = rd.readLine()) != null) {
sb.append(line);
}
rd.close();
conn.disconnect();
return sb.toString();
}
public static void main(String[] args) throws Exception {
String[] attr = new String[1];
String[] value = new String[1];
attr[0] = "DESCRIPTION";
value[0] = "REST API test";
String description = httpPost("http://192.168.150.18/maxrest/rest/os/mxasset/123?_lid=maxadmin&_lpwd=sm",attr,value);
System.out.println("\n"+description);
}
}
Thank you

JSON post encoding in Elasticsearch through maven

I want to make insert in java.Maven with http post to Elasticsearch server.
My code is:
package com.server.java.Webping;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
public class ReadAndWrite extends Server {
public static void main(String[] args) throws IOException {
try {
URL url = new URL("http://192.168.1.126:9200/shakespeare/_bulk?pretty' --data-binary #shakespeare.json");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json");
File file = new File("shakespeare.json");
FileReader reader = new FileReader(file);
#SuppressWarnings("resource")
BufferedReader br = new BufferedReader(reader);
String input = null;
StringBuilder builder = new StringBuilder();
while(br.readLine( ) != null)
{
String txt = br.readLine( );
builder.append(txt);
}
input = builder.toString();
OutputStream os = (OutputStream) conn.getOutputStream();
os.write(input.getBytes());
os.flush();
if (conn.getResponseCode() != HttpURLConnection.HTTP_CREATED) {
throw new RuntimeException("Failed : HTTP error code : "
+ conn.getResponseCode());
}
BufferedReader br1 = new BufferedReader(new InputStreamReader(
(conn.getInputStream())));
String output;
System.out.println("Output from Server .... \n");
while ((output = br1.readLine()) != null) {
System.out.println(output);
}
conn.disconnect();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
However when I execute the post method, java return me an error:
java.io.IOException: Error writing to server
at sun.net.www.protocol.http.HttpURLConnection.writeRequests(HttpURLConnection.java:699)
at sun.net.www.protocol.http.HttpURLConnection.writeRequests(HttpURLConnection.java:711)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream0(HttpURLConnection.java:1567)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1474)
at java.net.HttpURLConnection.getResponseCode(HttpURLConnection.java:480)
at com.server.java.Webping.ReadAndWrite.main(ReadAndWrite.java:38)
I have also checked my server connection with pinging socket request and its working .
code for pinging request:
package com.server.java.Webping;
import java.net.InetAddress;
import java.net.Socket;
public class WebPing {
public static void main(String[] args) {
try {
InetAddress addr;
Socket sock = new Socket("192.168.1.126", 9200); // elastic search - 9200 , kibana - 5601
addr = sock.getInetAddress();
System.out.println("Connected to " + addr);
sock.close();
} catch (java.io.IOException e) {
System.out.println("Can't connect to " + args[0]);
System.out.println(e);
}
}
}
and output returns as :
Connected to /192.168.1.126
Can anyone help me out that what is wrong in my code ?

RESTful program not working

I'm trying to convert this curl sentence:
curl -tlsv1.2 -k -X POST -H "Content-Type: application/json" -u myuser:mypass --data-binary #prueba_token.txt https://192.168.1.13/vts/rest/v1.0/tokenize
into a java program:
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLSession;
import org.apache.commons.codec.binary.Base64;
public class VormetricClientToken {
public static void main(String[] args) throws NoSuchAlgorithmException, KeyManagementException, UnsupportedEncodingException {
new VormetricClientToken().DoIt();
}//main
private void DoIt() throws NoSuchAlgorithmException, KeyManagementException, UnsupportedEncodingException{
String credential = Base64.encodeBase64String("myuser:mypass".getBytes("UTF-8"));
try{
String https_url = "https://192.168.1.13/vts/rest/v1.0/tokenize/";
URL myurl = new URL(https_url);
HttpsURLConnection con = HttpsURLConnection)myurl.openConnection();
con.setHostnameVerifier(new HostnameVerifier(){
#Override
public boolean verify(String hostname, SSLSession session){
return true;
}
});
String ccNum = "9876-5432-1098-7654";
String jStr = "{\"tokengroup\" : \"pruebas\" , \"data\" : \""+ccNum+"\", \"format\" : \"random-luhn\"}";
con.setRequestProperty("Content-length", String.valueOf(jStr.length()));
con.setRequestProperty("Content-Type","application/json; charset=UTF-8");
byte[] ptext = jStr.getBytes("UTF-8");
con.setRequestProperty("Authorization","Basic "+credential);
con.setRequestMethod("POST");
con.setDoOutput(true);
try (DataOutputStream output = new DataOutputStream(con.getOutputStream())) {
output.write(jStr.getBytes());
}
int responseCode = con.getResponseCode();
System.out.println("Response Code : " + responseCode);
BufferedReader rd= new BufferedReader(new InputStreamReader(con.getInputStream()));
String line = "";
String strResponse = "";
while((line = rd.readLine()) != null) {
strResponse=strResponse+line;
}
con.disconnect();
System.out.println("POST response: "+strResponse);
}catch(MalformedURLException e) {
System.out.println("error vormetric token client malformed:"+e);
}catch(IOException e1){
System.out.println("error vormetric token client ioexception:"+e1);
e1.printStackTrace();
}//catch
}//doit
}//vormetricclienttoken
I keep receiving this message:
ioexception:java.io.IOException: Server returned HTTP response code: 400 for URL: https://192.168.1.13/vts/rest/v1.0/tokenize/
I'd already tried using Httpclient but the result is the same, I know code 400 means that the web service doesn't understand the text I'm sending. But it's the same text I'm using in curl.
A little help of what could it be wrong will be much appreciated, thanks
DataOutputStream is for serializing Java objects, you don't want that.
Just write to the stream returned by con.getOutputStream().
Also, Content-Length is with uppercase L, and the value should be the length in bytes.
You declare and initialize ptext, but don't use it.
Change to:
byte[] ptext = jStr.getBytes("UTF-8");
con.setRequestProperty("Content-length", String.valueOf(ptext.length));
// more code
try (OutputStream output = con.getOutputStream()) {
output.write(ptext);
}

when open connection of URL by Java API it is working fine in development side,but not working on UAT,the error is showing Connection timed out

when open connection of URL by Java API it is working fine in development side,but not working on UAT,the error is showing Connection timed out.Please suggest what to do?
Here given userID,password proxyip and port are not actual because it is the client url.
package qc.los.util;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.util.Random;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.apache.log4j.Logger;
import qc.dal.DAL;
import qc.dal.dto.ParameterDTO;
import qc.los.controller.action.NewProspectAction;
import qc.sso.util.UserLockingFilter;
public class Utils {
protected static Logger log = Logger.getLogger(Utils.class);
public static void main(String[] args)
{
Utils Utilss=new Utils();
Utilss.sendVerificationCodeToCustomer("","9811937492","myTestras",true,"properhost","properport");
}
public String sendVerificationCodeToCustomer(String prospectId,String mobileNumber, String verificationCode, boolean proxyEnabled, String proxyHost, String proxyPort)
{
log.info("Start");
Properties systemSettings = System.getProperties();
try
{
//UPdated by for user id password
String urlStr ="http://www.example.com/SendSMS/sendmsg.php?uname=rahul&pass=rahul&send=Tag&dest="+mobileNumber+"&msg=Your%20verification%20code%20is%20"+verificationCode+"&concat=1";
log.info("urlStr "+urlStr);
URL u = new URL (urlStr);
log.info("proxyHost and proxyPort "+proxyHost+" "+proxyPort);
if(proxyEnabled)
{
log.info("proxyEnabled with proxyHost and proxyPort "+proxyHost+" "+proxyPort);
systemSettings.put("proxySet", "true");
systemSettings.put("proxyHost", proxyHost);
systemSettings.put("proxyPort", proxyPort);
}
HttpURLConnection con = (HttpURLConnection) u.openConnection ();
con.setDoInput(true);
con.setRequestMethod("GET");
log.info("Connection start");
con.connect();
log.info("Connection connected");
InputStream is = con.getInputStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
String line;
StringBuffer response = new StringBuffer();
while((line = rd.readLine()) != null)
{
response.append(line);
response.append("<br>");
}
rd.close();
log.info("End:Message sucessfull with response "+response.toString());
return response.toString();
}
catch(Exception e)
{
String proxySetting = proxyEnabled + ":" + proxyHost + ":" + proxyPort;
e.printStackTrace();
log.error("exception while sending sms:("+proxySetting+")"+" "+e.getMessage());
return "exception while sending sms:("+proxySetting+")"+e.getMessage();
}
finally
{
if(proxyEnabled)
{
systemSettings.remove("proxySet");
systemSettings.remove("proxyHost");
systemSettings.remove("proxyPort");
}
log.info("End");
}
}
}

Categories