0

I am writing a program which would connect to a Https url and will authenticate using username and password and the send a Post request Query and get output in Json. I have been stuck up in authentication part and sending Post request. Please help me with it. how and where do I add username password?

Also I need to add headers=("application/json")

public static void main(String a[]) throws IOException{


            URL url = new URL("https://url");
            URLConnection connection = url.openConnection();
            connection.connect();
            HttpsURLConnection httpsConnection = (HttpsURLConnection) connection;
            httpsConnection.setAllowUserInteraction(true);



         StringEntity input = new StringEntity("{'query': 'select i.interfaceid, i.node.caption as node_name, i.node.nodeid as nodeid, i.caption as interface_name, i.interfacelastchange, i.operstatus, i.adminstatus from orion.npm.interfaces i where (i.unmanaged = 0 and i.status <> 1) and daydiff(i.interfacelastchange, getdate()) >= 90 and (i.operstatus > 1 or i.adminstatus > 1)', 'parameters': ''}");

 request.setRequestMethod("POST");
 OutputStream post = request.getOutputStream();
 input.writeTo(post);
 post.flush();

BufferedReader in = new BufferedReader(new InputStreamReader(request.getInputStream()));
 String inputLine, response = "";
 while ((inputLine = in.readLine()) != null) {
  response += inputLine;
 }
 post.close();
}
Arnav
  • 41
  • 8
  • take a look here [Can you pass user/pass for HTTP Basic Authentication in URL parameters?](http://serverfault.com/questions/371907/can-you-pass-user-pass-for-http-basic-authentication-in-url-parameters) based on this you can not do this. For this there is always authentication API up front in app. which give you token and through that token as part of your request you can retrieve info from server. – JBaba Aug 04 '15 at 16:30
  • Hi, thanks for the reply but I am not intending to pass an Authentication parameters in URL. I was able to run this program on python and wanted to do the same in Java. I will post my Python code and hopefully it will be clear. – Arnav Aug 04 '15 at 16:56
  • i have added Python code and want to do the same on Java. – Arnav Aug 04 '15 at 16:59
  • Only two ways you can do this. Try this, [Basic Url Authentication](http://www.avajava.com/tutorials/lessons/how-do-i-connect-to-a-url-using-basic-authentication.html) or Using [Authenticator](http://stackoverflow.com/questions/496651/connecting-to-remote-url-which-requires-authentication-using-java) – JBaba Aug 04 '15 at 17:30

1 Answers1

0
import requests
import json
from getpass import getpass


class SwisClient:
    def __init__(self, hostname, username, password):
        self.url = "https://%s:17778/SolarWinds/....." % (hostname)
        self.credentials = (username, password)

    def query(self, query, **params):
        return self._req("POST", "Query", {'query': query, 'parameters': params}).json()



    def _req(self, method, frag, data=None):
        return requests.request(method, self.url + frag, 
            data=json.dumps(data), 
            verify=False, 
            auth=self.credentials, 
            headers={'Content-Type': 'application/json'})

def samplecode(npm_server,username,password):
    swis = SwisClient(npm_server,username,password)



    print ("Query Test:")
    results = swis.query("select i.interfaceid, i.node.caption as node_name, i.node.nodeid as nodeid, i.caption as interface_name, i.interfacelastchange, i.operstatus, i.adminstatus from orion.npm.interfaces i where (i.unmanaged = 0 and i.status <> 1) and daydiff(i.interfacelastchange, getdate()) >= 90 and (i.operstatus > 1 or i.adminstatus > 1)") # set valid NodeID!
    #uri = results['results'][0]['Uri']
    print (results)



def main():
    npm_server = input("IP address of NPM Server: ")
    username = input("Username: ")
    password = getpass("Password: ")
    samplecode(npm_server,username,password)


if __name__ == "__main__":
    main()
Arnav
  • 41
  • 8