Java how to getString from site - java

Currently I'm trying how to extract this information in the jar file to pass server the information required.
When you trigger this url:
http://ipinfo.io/country
But the return will be in a 2 variable , so my problem is how to extract since it's not a JSON.
try {
URL obj = new URL("http://ipinfo.io/country");
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("GET");
con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
con.setDoOutput(true);
con.setDoInput(true);
int responseCode = con.getResponseCode();
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String joinString = "";
String decodedString;
while ((decodedString = in.readLine()) != null) {
joinString = joinString + decodedString;
}
in.close();
//-- Logging (joinString) & responseCode
this.setCountry(new JSONObject(joinString).getString(""));
} catch (IOException ex) {
Logger.getLogger(RegUserRequest.class.getName()).log(Level.SEVERE, null, ex);
}

the http://ipinfo.io/country get request returns a country code as text output.
So why not simply doing :
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String countryCode = in.readLine();
If it provides directly the data and that you have a single data to retrieve, why do you want to use JSON ?

You can print it with:
System.out.println(joinString);
If you need The GR string is in your joinString as plain text.

They provide a JSON API that returns JSON and the country code.
But please also consider what they tell you about using their service / API:
Free usage of our API is limited to 1,000 API requests per day. If you
exceed 1,000 requests in a 24 hour period we'll return a 429 HTTP
status code to you. If you need to make more requests or custom data,
see our paid plans, which all have soft limits.
(Taken from https://ipinfo.io/developers/getting-started)

Related

How to replicate curl command using java?

Precisely said I want to perform below curl action which returns json with java:
curl -H 'Client-ID: ahh_got_ya' -X GET 'https://api.twitch.tv/helix/streams'
This works just fine in linux shell.
below is my script trying to do above curl using java json:
{String urly = "https://api.twitch.tv/helix/streams";
URL obj = new URL(urly);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("GET");
con.setRequestProperty("Content-Type","application/json");
con.setRequestProperty("Client-ID","Ahh_got_ya");
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes("");
wr.flush();
wr.close();
int responseCode = con.getResponseCode();
System.out.println("Response Code : " + responseCode);
BufferedReader iny = new BufferedReader(
new InputStreamReader(con.getInputStream()));
String output;
StringBuffer jsonres = new StringBuffer();
while ((output = iny.readLine()) != null) {
jsonres.append(output);
}
iny.close();
//printing result from response
System.out.println(response.toString());
}
I am getting: java.io.FileNotFoundException: https://api.twitch.tv/helix/streams Response Code : 404
All replies are much appreciated.
Almost there! You are doing a GET call and do not need to make the connection writeable -- since you are not going to post. You need to remove that section there. Also - to get exactly what your curl call is doing, remove the Content-Type - since it is not used in the curl call. So your code adjusted should be:
{
String urly = "https://api.twitch.tv/helix/streams";
URL obj = new URL(urly);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
//only 2 headers from cURL call
con.setRequestMethod("GET");
con.setRequestProperty("Client-ID","Ahh_got_ya");
int responseCode = con.getResponseCode();
System.out.println("Response Code : " + responseCode);
BufferedReader iny = new BufferedReader(
new InputStreamReader(con.getInputStream()));
String output;
StringBuffer jsonres = new StringBuffer();
while ((output = iny.readLine()) != null) {
jsonres.append(output);
}
iny.close();
//printing result from response
System.out.println(response.toString());
}
The reason for the 404 is if your request does not match what the service endpoint is expecting. Sending a POST request or other types of non-expect stuff will result is a request that does not match. Remove the extra output stuff and give it a go!
The way you state your question is a bit weird. But I assume you want to let a Java program make a cURL call of a JSON file. Now your linux terminal talks BASH not Java. So here is step 1.
You have to use a library.
Options are java.net.URL and/or java.net.URLConnection.
So #include one or either of those.
URL url = new URL("https://api.twitch.tv/helix/streams");
try (BufferedReader reader = new BufferedReader(new
InputStreamReader(url.openStream(), "UTF-8"))) {
for (String line; (line = reader.readLine()) != null;) {
System.out.println(line);
}
}
https://docs.oracle.com/javase/tutorial/networking/urls/readingWriting.html
Another thing you could mean is you want Java to generate JSON and access cURL trough Bash which isn't something I would advise anyone to do. If you feel like you have to it would be something like this.
public class ExecuteShellCommand {
public String executeCommand(String command) {
With the string set to cURL

JSON data not able to capture

I write a program to capture the JSON response from the server which contain some needed information I needed. I discovered that sometime my program will not able to capture the correct JSON string and sometime it's works well with no problem. I try to check my code for capturing the response and have no idea on it. When I check the JSON string from server, it's contain the field I want but my program not able to capture the correct data.
This is my JSON String
"info":{
      "reason":"Fine",
      "boolean":false,
      "post":{
         "actions":"",
         "actions_In_process":"Checked",
         "destination":"C%3ApdfFdoc%20edipdfFdestinationpdfFexample.pdf",
         "file_type":"pdf",
       
      },
This is my program for capture the JSON string and the field I need is action_In_process
String Url1 = "http://IP:port/etc/";
HttpURLConnection con = (HttpURLConnection) Url1.openConnection();
con.setRequestMethod("GET");
con.connect();
int responseCode = con.getResponseCode();
if(responseCode == 200)
{
try
{
InputStream is = con.getInputStream();
BufferedReader read = new BufferedReader (new InputStreamReader(is));
StringBuffer buffer = new StringBuffer();
String data = "" ;
while((data = read.readLine() ) != null )
{
buffer.append(data);
}
String JsonData = buffer.toString();
JSONObject jobj = new JSONObject(JsonData);
JSONObject process_info = jobj.getJSONObject("info");
JSONObject pi = process_info.getJSONObject("post");
String action_run = pi.getString("actions_In_process");
System.out.println("Process:" +action_run);
What I had found out is sometime the Process showing is blank but when I get back the JSON data and I found out the field I need is inside the JSON response. Please share your opinion on this issues
This is the message showing my compiler if I not able to capture the correct JSON string
Process :
If in normal condition
Process : check
BufferedReader's readline() is blocking.

How i can get connected with qc 12 with rest api

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();
}

Android: not getting xml out of http get request with basic authentication

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.

Paypal update invoice rest api HTTP response code: 500

i am currently trying to use REST api provided by Paypal to create my own service using servlet. I manage to transfer the cURL code into HttpsURLConnection using java.
Here is my code:
JSONObject returnJson = new JSONObject();
PrintWriter out = response.getWriter();
JSONParser jparser = new JSONParser();
try{
String inputStr = request.getParameter("input");
System.out.println(inputStr);
JSONObject inputJson = (JSONObject) jparser.parse(inputStr);
String accessToken = (String) inputJson.get("access_token");
String invoiceId = (String) inputJson.get("invoiceId");
String url = "https://api.sandbox.paypal.com/v1/invoicing/invoices/"+invoiceId;
URL obj = new URL(url);
HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();
//add reuqest header
con.setRequestMethod("PUT");
con.setRequestProperty("Accept-Language", "text/html; charset=UTF-8");
con.setRequestProperty("Content-Type", "application/json");
con.setRequestProperty("Authorization", "Bearer "+accessToken);
//Tentatively, the input is hard coded, after integration, the input comes from http request.
//However, only merchant email in mandatory for invoice creation in sand box so far
//For details of invoice attributes please refer to this link--> https://developer.paypal.com/docs/api/#update-an-invoice
String urlJsonString = "{\"id\":\""+invoiceId+"\",\"status\":\"DRAFT\",\"merchant_info\":{\"email\":\"rui.song.2013-facilitator#sis.smu.edu.sg\",\"first_name\":\"Dennis\",\"last_name\":\"Doctor\",\"business_name\":\"MedicalProfessionals,LLC\",\"phone\":{\"country_code\":\"US\",\"national_number\":\"5032141716\"},\"address\":{\"line1\":\"1234MainSt.\",\"city\":\"Portland\",\"state\":\"LALA\",\"postal_code\":\"97217\",\"country_code\":\"US\"}},\"billing_info\":[{\"email\":\"sally-patient#example.com\"}],\"shipping_info\":{\"first_name\":\"Sally\",\"last_name\":\"Patient\",\"business_name\":\"Notapplicable\",\"address\":{\"line1\":\"1234BroadSt.\",\"city\":\"Portland\",\"state\":\"LALA\",\"postal_code\":\"97216\",\"country_code\":\"US\"}},\"items\":[{\"name\":\"Sutures\",\"quantity\":100,\"unit_price\":{\"currency\":\"USD\",\"value\":\"250\"}}],\"invoice_date\":\"2014-01-07PST\",\"payment_term\":{\"term_type\":\"NO_DUE_DATE\"},\"tax_calculated_after_discount\":false,\"tax_inclusive\":false,\"note\":\"MedicalInvoice16Jul,2013PST\",\"total_amount\":{\"currency\":\"USD\",\"value\":\"250\"}}";
System.out.println(urlJsonString);
con.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(con.getOutputStream());
wr.write(urlJsonString);
wr.close();
int responseCode = con.getResponseCode();
System.out.println("Response Code : " + responseCode);
out.print(responseCode);
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer res= new StringBuffer();
while ((inputLine = in.readLine()) != null) {
res.append(inputLine);
}
in.close();
returnJson = (JSONObject) jparser.parse(res.toString());
System.out.println(returnJson);
}catch(Exception e){
e.printStackTrace();
returnJson.put("message", e);
}
out.print(returnJson);
I am testing the service on localhost, and i will manually pass in TWO parameters: "access_token" and "invoiceId" like this:
http://localhost:8080/Authentication/PaypalUpdateInvoiceServlet?input={"access_token":"A015Rv3XNo4fmFh4JC2sJiGjl1oEQ5w-B9azU.H6nlzMm1s","invoiceId":"INV2-9TRP-2S2R-OPBD-XK9T"}
These two pieces of info are obtained by me using the similar code i mentioned above.
I only modified codes in the entier HttpsURLConnection part to correspond with the cURL request and response sample provided in Paypal site. Link -->(https://developer.paypal.com/docs/api/#update-an-invoice)
Thus far, i successfully implement Create, Retrieve for invoice. I use the same way to make the servlet call with the specific parameters required and are able to get the expected response show on Paypal site.
BUT Now i am stuck with update invoice. When i make the servlet call.
i will receive:
500{"message":java.io.IOException: Server returned HTTP response code: 500 for URL: https://api.sandbox.paypal.com/v1/invoicing/invoices/IINV2-9TRP-2S2R-OPBD-XK9T}
Can anyone help me explain why i get this error and how shall i fix this?

Categories