Can u please help me to understand with simple piece of java code to get connect wth qc 12 using rest api.
I gone thorough the rest api documentation but am not clear with how to start with.but it will be helpful if people can show me a simple java code for authentication(login,logout or getting defect details) using rest api. Also want to know do i need to include any jars in my build path.
Thanks a lot friends.
I don't quite get what you're asking, but if you want to connect to a REST API, there are several ways... I usually use HttpURLConnection, here's an example of a get:
public String getProfile(String URL) throws IOException {
URL getURL = new URL(url);
//Establish a https connection with that URL.
HttpURLConnection con = (HttpURLConnection) getURL.openConnection();
//Select the request method, in this case GET.
con.setRequestMethod("GET");
//Add the request headers.
con.setRequestProperty("header", headerValue);
System.out.println("\nSending 'GET' request to URL : " + url);
int responseCode;
try {
responseCode = con.getResponseCode();
System.out.println("Response Code : " + responseCode);
} catch (Exception e) {
System.out.println("Error: Connection problem.");
}
InputStreamReader isr = new InputStreamReader(con.getInputStream());
BufferedReader br = new BufferedReader(isr);
StringBuffer response = new StringBuffer();
String inputLine;
while ((inputLine = br.readLine()) != null) {
//Save the response.
response.append(inputLine + '\n');
}
br.close();
return response.toString();
}
Related
I added an open extension to an event in a calendar and am trying to read it back.
Here is the url:
https://graph.microsoft.com/v1.0/users/{userid}/calendars/{calendarId}=/events?$expand=Extensions($filter=Id eq 'c.i.m.p.server.entities.outlook.Event')
I cannot get this to work in a Java program. The following combinations do work:
It works my Java program if I remove the $expand... parameter. I can also ask for certain fields, that works too.
The request works in Postman (I just have to set the token)
The request works in Graph Explorer when I log in as the owner of the calendar
Here is the extension (inside one of the events) when I use Postman to read the event. It is the last item in the event:
"extensions#odata.context": "https://graph.microsoft.com/v1.0/$metadata#users('{userid}')/calendars('{calendarId}')/events('{eventId})/extensions",
"extensions": [
{
"#odata.type": "#microsoft.graph.openTypeExtension",
"id": "Microsoft.OutlookServices.OpenTypeExtension.c.i.m.p.server.entities.outlook.Event",
"extensionName": "c.i.m.p.server.entities.outlook.Event",
"adherentId": "12346",
"timeSlotID": "346463"
}
]
Here is the Java code (Java 8, using java.io and java.net libraries):
private static void doSomething(String _accessToken) throws IOException {
String urlString = "https://graph.microsoft.com/v1.0/users/{userId}/calendars/{calendarId}/events?$expand=Extensions($filter=Id eq 'c.i.m.p.server.entities.outlook.Event')";
URL url = new URL(urlString);
Proxy webProxy
= new Proxy(Proxy.Type.HTTP, new InetSocketAddress({proxy-address}, {port}));
HttpURLConnection connection = (HttpURLConnection) url.openConnection(webProxy);
// Set the appropriate header fields in the request header.
connection.setRequestProperty("Authorization", "Bearer " + _accessToken);
connection.setRequestProperty("Accept", "application/json");
connection.setDoOutput(true);
connection.setReadTimeout(5000);
connection.setRequestMethod(HttpMethod.GET);
try {
connection.connect();
int responseCode = connection.getResponseCode();
System.out.println("execute(), response code = " + responseCode);
String responseMessage = connection.getResponseMessage();
System.out.println("execute(), response Message = " + responseMessage);
String responseString = null;
try {
InputStream ins = connection.getInputStream();
BufferedReader br=new BufferedReader(new InputStreamReader(ins));
StringBuffer sb=new StringBuffer();
String line;
while ((line=br.readLine()) != null) {
sb.append(line);
}
responseString = sb.toString();
} catch (Exception e) {
System.out.println("Could not get input stream from response, error is " + e.toString());
}
System.out.println("execute(), httpResult = " + responseString);
} catch (IOException e) {
System.out.println(".execute(), IOException : " + e.toString());
} finally {
connection.disconnect();
}
}
How do I fix this? Thanks!
400 means bad request. It could be because of url encoding. Url encode the query string.
Something like
String query = "Extensions($filter=Id eq 'c.i.m.p.server.entities.outlook.Event'";
String url = "https://graph.microsoft.com/v1.0/users/{userId}/calendars/{calendarId}/events?
$expand=" + URLEncoder.encode(query, StandardCharsets.UTF_8.name());
Alternatively you could use graph service java api based on your need which will help abstract all the interactions for you or you could use any of the rest clients available.
First of all, you should provide more info on the error - Stacktrace and error message. But 400 code indicates that was a user mistake, meaning that you are sending an invalid request. Since you say that postman request works then compare all the headers that are sent by postman and see if your code misses some hearer. As for the code, instead of coding your own Http client functionality I would suggest using 3d party Http client. Here are a few suggestions:
Apache Http client - very popular and well known 3d party Http Client
OK Http client - Open-source Http client. Here is tutorial
MgntUtils Http client - very simple 3d party HttpClient: Provided in MgntUtils Open source library (written by me). Very simple in use. Take a look at Javadoc. Library itself provided as Maven artifacts and on Git (including source code and Javadoc).
My goal is to get the xml from an API. The API uri I use, including parameters is http://webservices.ns.nl/ns-api-treinplanner?fromStation=Roosendaal&toStation=Eindhoven. I am given a username and password, for what I think probably is basic authorization.
I tried various things like something with an Authenticator, the format http://username:password#webservices.ns.nl/ns-api-treinplanner, but at the end of a lot of SO searching I ended up with something with a setRequestProperty with the basic authorization.
I put the code into an AsyncTask which seems to work correctly so I will just put the code from inside doInBackground in here.
As the java FileNotFoundException I first got didn't give me much information, I found out how to use the getErrorStream to find out more.
InputStream in;
int resCode;
try {
URL url = new URL("http://webservices.ns.nl/ns-api-treinplanner?fromStation=Roosendaal&toStation=Eindhoven");
String userCredentials = "username:password";
String encoding = new String(android.util.Base64.encode(userCredentials.getBytes(), Base64.DEFAULT));
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestProperty("Authorization", "Basic " + encoding);
urlConnection.setRequestMethod("GET");
urlConnection.setDoOutput(true);
try {
resCode = urlConnection.getResponseCode();
if (resCode == HttpURLConnection.HTTP_OK) {
Log.i("rescode","ok");
in = urlConnection.getInputStream();
} else {
Log.i("rescode","not ok");
in = urlConnection.getErrorStream();
}
BufferedReader bufferedReader = new BufferedReader(
new InputStreamReader(in));
StringBuilder stringBuilder = new StringBuilder();
String line;
while ((line = bufferedReader.readLine()) != null) {
stringBuilder.append(line).append("\n");
}
bufferedReader.close();
return stringBuilder.toString();
}
finally{
urlConnection.disconnect();
}
}
catch(Exception e) {
Log.e("ERROR", e.getMessage(), e);
return null;
}
Then, in onPostExecute I print the response, but the response I get is
<?xml version="1.0"?>
<soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope" soap:encodingStyle="http://www.w3.org/2003/05/soap-encoding">
<soap:Header></soap:Header>
<soap:Body><soap:Fault>
<faultcode>soap:Server</faultcode>
<faultstring>006:No customer found for the specified username and password</faultstring></soap:Fault>
</soap:Body></soap:Envelope>
This is of course not right, it should give a full xml of in this case a train voyage recommendation.
I tested with my browsers, and also using a HTTP request tool called Postman which returned the correct xml so all the uri's, parameters, username and password are correct.
The encoding used is wrong. The base64 encoding used randomly returns whitespaces in the middle, adding encoding = encoding.replaceAll("\\s+",""); actually fixed it.
so I'm trying to do a GET Request to my web service, and since I saw that the HttpGet class is being deprecated, I try to use the HttpURLConnection class instead, and I used it successfully with a 'POST' method... however when I try to do a simple 'GET' request - I get a 405 error (bad method).
I tested the link in DHC, and the link is fine.
Here's my method:
public JSONObject getClientByDeviceId (String link) {
try {
URL url = new URL(link);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
// conn.setRequestMethod("GET");
// conn.setDoOutput(true);
// conn.setDoInput(true);
// conn.setUseCaches(false);
// conn.setAllowUserInteraction(false);
// conn.setRequestProperty("Content-Type", "application/json");
OutputStream outputStream = conn.getOutputStream();
outputStream.close();
if (conn.getResponseCode() != 200) {
Log.e("conn", "Error code: " + conn.getResponseCode());
BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuilder sb = new StringBuilder();
String line;
while ((line = br.readLine()) != null) {
sb.append(line);
}
br.close();
conn.disconnect();
JSONObject returnedObject = new JSONObject(sb.toString());
if (returnedObject != null) {
Log.e("conn", "If 400, this is the object gained: " + returnedObject.getString("Message"));
} else {
Log.e("conn", "didn't get any JSON object");
}
conn.disconnect();
return returnedObject;
}
else {
BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
Log.e("conn", "GREAT SUCCESS !!: " + conn.getResponseCode());
StringBuilder sb = new StringBuilder();
String line;
while ((line = br.readLine()) != null) {
sb.append(line);
}
br.close();
conn.disconnect();
JSONObject returnedObject = new JSONObject(sb.toString());
return returnedObject;
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
Normally I would say that this problem is caused by trying to do a 'GET' request in a 'POST' URL. But without the two HttpGet and HttpPost classes I don't really know where to turn, all the properties that are commented out are like that because I tried them in the POST request and now I deleted one by one to try to get the method to work.
Any ideas ? or reference to an updated guide on how to properly use that HttpURLConnection class, since I couldn't find one.
Thanks in advance !
Solved it, apparently this code needed to be removed:
OutputStream outputStream = conn.getOutputStream();
outputStream.close();
I guess it was because I gave a GET URL and put that outputStream in my code and that caused the issues.
I still however don't understand why I got the "405: method GET not allowed" whereas I think I should have gotten the opposite: "POST" not allowed...
Anyway that is my solution, thanks a lot for your help guys !
HTTP 405 is caused by bad method call (Method not Allowed). That means you called GET method on POST request or vice-versa. You should add handling for you GET method on your Web-Service to get it working.
For anyone still reaching here from a search engine, my solution was similar -
I removed the line "conn.setDoOutput(true);" (or set it to false)
Is it possible to use HTTP API and perform HTTP Get request for Google maps in order to overcome the limits of using Geocoder API when requesting latitude and longitude of places?
Something like-
URL url = new URL("https://www.google.com/maps/place/Paris/");
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setRequestMethod("GET");
System.out.println("Value" + connection.getResponseCode());
System.out.println(connection.getResponseMessage());
System.out.println("content"+connection.getContent());
or
URL url = new URL("https://www.google.com/maps/place/Paris/");
BufferedReader br = new BufferedReader(new InputStreamReader(url.openStream()));
String strTemp = "";
while (null != (strTemp = br.readLine())) {
System.out.println(strTemp);
}
Expecting the response to contain the lat and long of the place as in Google maps site, that way my client appears as a regular web client of google maps.
The Places API request has quota limit too, you can see the detail in this page: https://developers.google.com/places/webservice/usage
Also, you need an API key to do your Places API request, a sample way to do a Places API URL request in Android should be like this:
URL placeUrl = new URL("https://maps.googleapis.com/maps/api/place/textsearch/json?query=restaurants+in+Sydney&key=AddYourOwnKeyHere");
HttpURLConnection connection = (HttpURLConnection)placeUrl.openConnection();
connection.setRequestMethod("GET");
connection.connect();
responseCode = connection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
BufferedReader reader = null;
InputStream inputStream = connection.getInputStream();
StringBuffer buffer = new StringBuffer();
if (inputStream == null) {
// Nothing to do.
return null;
}
reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null) {
buffer.append(line + "\n");
}
if (buffer.length() == 0) {
return null;
}
Log.d(TAG, buffer.toString());
}
else {
Log.i(TAG, "Unsuccessful HTTP Response Code: " + responseCode);
}
You should do this URL request in background thread, for example, in the doInBackground() method of AsyncTask.
You can also visit this tutorial for more detail about how to use Places API in Android.
I have a question about making a POST request with Java, and since this is my first attempt at something of this magnitude, please bear with me. I am working on a third party application in Java to connect to a website and make POST requests. Am I doing this correctly? Here is what I have so far:
Website Code:
(This is the code the website has for "bumping a trade" which simply sends 2 pieces of data to a php file. The URL is http://cdn.dota2lounge.com/script/trades.js)
function bumpTrade(trade, code) {
$.ajax({
type: "POST",
url: "ajax/bumpTrade.php",
data: "trade=" + trade + "&code=" + code
});
}
My Java Code:
private void sendPost() throws Exception {
//String url = "https://www.cdn.dota2lounge.com/script/ajax/bumpTrade.php";
String url = "https://www.cdn.dota2lounge.com/script/ajax/bumpTrade.php";
URL obj = new URL(url);
HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();
//add request header
con.setRequestMethod("POST");
con.setRequestProperty("User-Agent", USER_AGENT);
con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
String urlParameters = "trade=96510389&code=94cebd9";
// 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 am receiving a connection timeout error when attempting to connect. I would be very grateful if someone could point me in the right direction!
The Java client code seems to be on the right track. But it looks like the URL in the code was the wrong URL.
Using the url "http://www.dota2lounge.com/ajax/bumpTrade.php" and HttpUrlConnection, I was able to get a 200 response (OK):
Sending 'POST' request to URL : http://www.dota2lounge.com/ajax/bumpTrade.php
Post parameters : trade=96510389&code=94cebd9
Response Code : 200
However nothing beyond that. Not sure of the API of the remote site but hopefully that's some help.