Coverting java request to c# - java

I am trying to convert this request written java to c#(Xamarin android) , java one seems to be working , but c# one is failing with bad request(400) .
Could you please point out if i am translating rightly ?
Java code
String url = "https://someUrl";
try {
URL url1 = new URL(url);
URLConnection uc = url1.openConnection();
String basicAuth = Base64.encodeToString((APIKEY).getBytes("UTF-8"), Base64.NO_WRAP);
uc.setRequestProperty("Authorization", basicAuth);
InputStream in = uc.getInputStream();
// Log.e(TAG, "response: " + response);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
C# code
String url = "https://someUrl";
// Add custom implementation here as needed.
var uri = new Uri(url);
var authHeaderValue = Convert.ToBase64String(Encoding.UTF8.GetBytes (API_KEY), Base64FormattingOptions.None);
try
{
using(var client = new HttpClient())
{
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Authorization", authHeaderValue);
var response = await client.GetAsync(uri);
}
}
catch (Exception e)
{
Log.Debug ("TokenSending", "failed to send token" + e);
}

Related

How can I get youtubeVideo Title from URL for android studio?

I want to get the youtube video title from a url so I found this code below (IOUtils) is depreciated any other way to do this
public class SimpleYouTubeHelper {
public static String getTitleQuietly(String youtubeUrl) {
try {
if (youtubeUrl != null) {
URL embededURL = new URL("http://www.youtube.com/oembed?url=" +
youtubeUrl + "&format=json"
);
return new JSONObject(IOUtils.toString(embededURL)).getString("title");
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
second way i tried
class getYoutubeJSON extends Thread {
String data = " ";
#Override
public void run() {
try {
URL url = new URL("http://www.youtube.com/oembed?url="+" https://www.youtube.com/watch?v=a4NT5iBFuZs&ab_channel=FilipVujovic"
+ "&format=json");
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = bufferedReader.readLine()) != null){
data =data + line;
}
if(!data.isEmpty()){
JSONObject jsonObject = new JSONObject(data);
// JSONArray users = jsonObject.getJSONArray("author_name");
Log.d("RT " , jsonObject.toString());
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
}
}
This code gets a an error Cleartext HTTP traffic to www.youtube.com not permitted
so I found this answer Android 8: Cleartext HTTP traffic not permitted but I am still getting some error I don't understand.
I solved this problem by using the volley library.
My requested url was:
String Video_id = "jhjgN2d7yok";
String url = "https://www.youtube.com/oembed?url=youtube.com/watch?v=" +Video_id+ "&format=json";

Java HTTP Request for PHP

So i am trying to send some variables to my localhost which runs a php file which should output the variable.
URL url = null;
try {
String charset = "UTF-8";
String MontagMittagVorspeise = "value1";
String query = String.format("param1=%s", URLEncoder.encode(MontagMittagVorspeise, charset));
url = new URL("127.0.0.1/Haunsbot/Hauns.php");
URLConnection connection = new URL(url + "?" + query).openConnection();
connection.setRequestProperty("Accept-Charset", charset);
InputStream response = connection.getInputStream();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
And this is my PHP:
<?php
if(isset($_GET["MontagMittagVorspeise"]))
{echo "Vehicle :".$_GET["MontagMittagVorspeise"];}
?>
And IntelliJ gives me the following error: java.net.MalformedURLException: no protocol: 127.0.0.1/Haunsbot/Hauns.php
Can someone help me?:)

The given code is returning me an empty JSON output

void url_get(double lati,double longi) {
URL url = null;
try {
url = new URL("https://maps.googleapis.com/maps/api/place/search/json?&location="+lati+","+longi+"&radius=1000&types=hospital&sensor=true&key=MY_KEY);
} catch (MalformedURLException e) {
e.printStackTrace();
}
HttpURLConnection urlConnection = null;
try {
urlConnection = (HttpURLConnection) url.openConnection();
} catch (IOException e) {
e.printStackTrace();
}
try {
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
TextView json = (TextView) findViewById(R.id.json3);
String theString = IOUtils.toString(in, "UTF-8");
json.setText(theString);
//System.out.println(in);
} catch (IOException e) {
e.printStackTrace();
} finally {
urlConnection.disconnect();
}
}
The code was working fine when I had hardcoded the latitude and longitude values.However when I tried to pass the values of latitutde and longitude through the function,It dint get recognized.I suppose the URL wasnt built properly.Could you please suggest a way to build my url with the values of latitude and longitude?
You should convert the values to string using:
Double.toString(double);
or:
String.valueOf(double);
So your string should be something like this:
url = new URL("https://maps.googleapis.com/maps/api/place/search/json?&location="+String.valueOf(lati)+","+String.valueOf(longi)+"&radius=1000&types=hospital&sensor=true&key=MY_KEY");
Note
In your code a " is missing at the end of the string.

Using Java (HttpURLConnection) to authenticate to Restheart (for Mongodb)

I am using restheart to provide a restful interface to mongodb. The interface is set up and running and provides the correct answer if a GET request is sent through Chrome. However if I use the following java code using a HttpURLConnection I get a 201 response with no content.
try {
videos = new URL("http://www.example.com:8080/myflix/videos");
} catch (Exception et) {
System.out.println("Videos URL is broken");
return null;
}
HttpURLConnection hc = null;
try {
hc = (HttpURLConnection) videos.openConnection();
String login="admin:admin";
final byte[] authBytes = login.getBytes(StandardCharsets.UTF_8);
final String encoded = Base64.getEncoder().encodeToString(authBytes);
hc.addRequestProperty("Authorization", "Basic "+encoded);
hc.setDoInput(true);
hc.setDoOutput(true);
hc.setUseCaches(false);
hc.setRequestMethod("GET");
hc.setRequestProperty("Accept-Encoding", "gzip, deflate, sdch");
hc.setRequestProperty("Content-Type", "application/json");
hc.setRequestProperty("Accept", "application/json,text/html,application/hal+json,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*");
} catch (Exception et) {
System.out.println("Can't prepare http URL con");
return (null);
}
BufferedReader br = null;
try {
OutputStreamWriter writer = new OutputStreamWriter(
hc.getOutputStream());
} catch (Exception et) {
System.out.println("Can't get reader to videos stream");
}
String inputLine;
String sJSON = null;
try {
int rc = hc.getResponseCode();
What is the correct way to authenticate using Java to the resthert interface? (Details on the restheart authentication is here Restheart authentication
I made few changes (look for inline comments starting with <==) and it works:
The way you generate the authentication request header is correct. When I run your code I actually got 415 Unsupported Media Type, that went away commenting out hc.setDoOutput(true). A GET is a input operation, in fact you were also trying to get an OutStream from the connection: you need to get an InputStream actually.
URL url;
try {
url = new URL("http://127.0.0.1:8080/test/huge");
} catch (Exception et) {
System.out.println("Videos URL is broken");
Assert.fail(et.getMessage());
return;
}
HttpURLConnection hc = null;
try {
hc = (HttpURLConnection) url.openConnection();
String login = "admin:admin";
final byte[] authBytes = login.getBytes(StandardCharsets.UTF_8);
final String encoded = Base64.getEncoder().encodeToString(authBytes);
hc.addRequestProperty("Authorization", "Basic " + encoded);
System.out.println("Authorization: " + hc.getRequestProperty("Authorization"));
hc.setDoInput(true);
//hc.setDoOutput(true); <== removed, otherwise 415 unsupported media type
hc.setUseCaches(false);
hc.setRequestMethod("GET");
hc.setRequestProperty("Accept-Encoding", "gzip, deflate, sdch");
hc.setRequestProperty("Accept", "application/json,text/html,application/hal+json,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*");
} catch (Exception et) {
System.out.println("Can't prepare http URL con");
}
System.out.println(hc.toString());
BufferedReader br = null;
try {
InputStreamReader reader = new InputStreamReader(hc.getInputStream()); // <== the request is a GET, data is in input
} catch (Exception et) {
System.out.println("Can't get reader to videos stream");
}
int rc = hc.getResponseCode();
System.out.println("response code: " + rc);
System.out.println("response message: " + hc.getResponseMessage());
Assert.assertEquals(200, rc);

Integrate Avaya IVRS with Service now using rest web-service

I have to integrate Avaya IVRS with Service now through java rest web-service. If user calls through Avaya IVRS, he should have option to choose from menu via their phone keypad and do the following functions :- 1. Add a ticket 2. Update a ticket 3. Close a ticket
I have written code to create and update ticket but i don't know how to integrate with service now.
/////////////////////////////////////////////////
// POST OPERATION -- Create a new Incident ticket
/////////////////////////////////////////////////
String endpointPOST = baseURI + "/in";
PostMethod post = new PostMethod(endpointPOST);
post.addRequestHeader("X-AccessKey", accessKey);
post.addRequestHeader("Accept" , "application/xml");
post.addRequestHeader("Content-Type", "application/xml; charset=UTF-8");
post.setRequestBody("<in>" + "<customer COMMON_NAME=\"System_SD_User\"/>" +
"<description>Created from REST API Java Samples code</description>" + "</in>");
try {
System.out.println("Execute POST request for " + endpointPOST);
// Execute POST request
int result = client.executeMethod(post);
System.out.println("Response status code: " + result);
System.out.println("Response body: ");
System.out.println(post.getResponseBodyAsString());
System.out.println();
} catch (HttpException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
post.releaseConnection();
}
//////////////////////////////////////////////////////
// PUT OPERATION -- Update an existing Incident ticket
//////////////////////////////////////////////////////
String endpointPUT = baseURI + "/in/400001";
PutMethod put = new PutMethod(endpointPUT);
put.addRequestHeader("X-AccessKey", accessKey);
put.addRequestHeader("Accept" , "application/xml");
put.addRequestHeader("Content-Type", "application/xml; charset=UTF-8");
put.setRequestBody(
"<in>" + "<summary>Updated from REST API Java Samples code</summary>" + "</in>");
try {
System.out.println("Execute PUT request for " + endpointPUT);
// Execute PUT request
int result = client.executeMethod(put);
System.out.println("Response status code: " + result);
System.out.println("Response body: ");
System.out.println(put.getResponseBodyAsString());
System.out.println();
} catch (HttpException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
put.releaseConnection();
}
you can integrate REST API default option given in OD or you can write customize java code or create a jar of your application call that in OD
try the below code it's tested in Avaya lab
String webServiceURl="https://XXXXXXXXXX/services/OceanaDataoceana/data/context/schema";
try{
URL url = new URL(webServiceURl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json");
String input ="{""}";//pass paramenter for request
OutputStream os = conn.getOutputStream();
os.write(input.getBytes());
os.flush();
System.out.println("conn.getResponseCode() ::::"+conn.getResponseCode());
if (conn.getResponseCode() != 200) {
throw new RuntimeException("Failed : HTTP error code : "+ conn.getResponseCode());
}
BufferedReader br = new BufferedReader(new InputStreamReader(
(conn.getInputStream())));
String output;
System.out.println("Output from Server .... \n");
while ((output = br.readLine()) != null) {
JSONObject object;
try {
object = new JSONObject(output);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("json response::: "+output);
conn.disconnect();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
If you are talking about Experience Portal then you have two choices. You can use the Orchestration Designer's built-in REST client (File/New/Web Service Operation File (REST)) or you implement it in a separate project and attach the rest client to your OD project.

Categories

Resources