OK I am writing my first Mobile 6 App, based on compact framework 2, obviously finding some differences from Framwork vs compact when dealing with reading and writting simple values to xml;
Here is what I want to do: write two textbox values to xml as follows:
<settings>
<hostip>192.168.0.14</hostip>
<hostport>8011</hostport>
</settings>
So I got the above accomplished using the following code:
--------------------
string hstip = "";
string hstport = "";
hstip = this.HostIP.Text.ToString();
hstport = this.HostPort.Text.ToString();
XmlWriterSettings xml_settings = new XmlWriterSettings();
xml_settings.Indent = true;
xml_settings.OmitXmlDeclaration = false;
xml_settings.Encoding = Encoding.UTF8;
xml_settings.ConformanceLevel = ConformanceLevel.Auto;
using (XmlWriter xml = XmlTextWriter.Create(GetApplicationDirectory() + @"\settings.xml", xml_settings))
{
xml.WriteStartElement("settings");
//xml.WriteStartAttribute("hostip", "");
xml.WriteElementString("hostip", hstip);
//xml.WriteString(hstip);
//xml.WriteEndAttribute();
xml.WriteElementString("hostport", hstport);
//xml.WriteStartAttribute("hostport", "");
//xml.WriteString(hstport);
//xml.WriteEndAttribute();
xml.WriteEndElement();
//ds.WriteXml(xml);
xml.Close();
}
-----------end of write code------------
Now the part I am stumped on as I have tried all varietions to get the data back into the textboxes, I either get and exception or blank values in the textboxes.
Here is the code:
------------------
private void SrvSettings_Load(object sender, EventArgs e)
{
XmlReaderSettings xml_settings = new XmlReaderSettings();
xml_settings.IgnoreComments = true;
xml_settings.IgnoreProcessingInstructions = true;
xml_settings.IgnoreWhitespace = true;
xml_settings.CloseInput = true;
try
{
using (XmlReader xml = XmlTextReader.Create(GetApplicationDirectory() + @"\settings.xml", xml_settings))
{
xml.ReadStartElement("settings");
xml.Read();
xml.ReadElementString(,,)
//xml.ReadToFollowing("hostip");
this.HostIP.Text = xml.GetAttribute("hostip","");
//this.HostIP.Text = xml.GetAttribute("hostip");
//xml.ReadToFollowing("hostport");
this.HostPort.Text = xml.GetAttribute("hostport","");
// Close it out----------------
xml.ReadEndElement();
xml.Close();
//ds.ReadXml(xml);
// }
}
}
catch (Exception ex)
{
System.Windows.Forms.MessageBox.Show(
ex.ToString(), "Error Loading IP settings");
}
}
------------end of read code
obviously I get an exception with this:
"System.xml.xmlexception:
"Text" is an invalid XmlNoteType. Line 2, posistion 11 at
System.xml.xmlReader.ReadEndElement()"
-----
I suspect I need to use ReadElementString, but I have tried and no workie...
Somebody have an example/class for both reading and writing per my requirements above, I would really appreciate the help..
Use XmlDocument
Try using the XmlDocument instead. It's alot easier to use for simple xml reading/writing.
Well Partially working now - I get the Hostport populated but for some reason hostip is blank even though it appears it falls through it in the case statement.. wierd..
DataSet ds = new DataSet();
XmlReaderSettings xml_settings = new XmlReaderSettings();
xml_settings.IgnoreComments = true;
xml_settings.IgnoreProcessingInstructions = true;
xml_settings.IgnoreWhitespace = true;
xml_settings.CloseInput = true;
try
{
using (XmlReader xml = XmlTextReader.Create(GetApplicationDirectory() + @"\settings.xml", xml_settings))
{
xml.MoveToContent();
xml.ReadStartElement("settings");
while (xml.Read())
{
//xml.Read();
switch (xml.Name)
{
case "hostip":
HostIP.Text = xml.ReadString(); <--I get Blank text
break;
case "hostport":
HostPort.Text = xml.ReadString(); <--POpulated OK
break;
default:
break;
}
// Close it out----------------
//xml.ReadEndElement();
}
xml.Close();
//ds.ReadXml(xml);
// }
}
}
Solved, Had to remove the line: xml.ReadStartElement("settings");
Thanks..
Just out of curiosity, what will your app do ?
I'm writing a WPF Windows App that monitors Server Services, IPs, Websites for up or down status; buiding a client server component to it, so the end goal will be to use the mobile app to connect to the host and download status on said servers being monitored and populate them in a listview whith thier up or done status.
Simple app but still in the works.
if you can make it customizable (to set up parametres, adreses) it wil be useful for many website administrators
a cool little app
Related
Hi all,
I'm trying to have transparent PNGs on my screen.
What is the best way to doing this ? I'm in C#, I tried DirectX, but it doesn't work.
What am I doing wrong ?
My code :
Code:
using System;
using System.Drawing;
using System.Windows.Forms;
using Microsoft.WindowsMobile.DirectX;
using Microsoft.WindowsMobile.DirectX.Direct3D;
using System.Runtime.InteropServices;
namespace Microsoft.Samples.MD3DM
{
// The main class for this sample
public class SimpleSMS : Form
{
// Our global variables for this project
Device device = null;
Texture texture = null;
Sprite sprite = null;
Rectangle rect;
public SimpleSMS()
{
// Set the caption
this.Text = "SimpleSMS";
this.MinimizeBox = false;
}
// Prepare the rendering device
public bool InitializeGraphics()
{
try
{
// Now let's setup our D3D parameters
PresentParameters presentParams = new PresentParameters();
presentParams.Windowed = true;
presentParams.SwapEffect = SwapEffect.Discard;
device = new Device(0, DeviceType.Default, this, CreateFlags.None, presentParams);
this.OnCreateDevice(device, null);
}
catch (DirectXException)
{
return false;
}
return true;
}
void OnCreateDevice(object sender, EventArgs e)
{
texture = TextureLoader.FromFile(device, @"badge.png");
sprite = new Sprite(device);
rect = new Rectangle(0, 0, 48, 48);
}
// All rendering for each frame occurs here
private void Render()
{
if (device != null)
{
device.Clear(ClearFlags.Target, System.Drawing.Color.Black, 1.0f, 0);
//Begin the scene
device.BeginScene();
device.RenderState.SourceBlend = Blend.SourceAlpha;
device.RenderState.DestinationBlend = Blend.InvSourceAlpha;
device.RenderState.AlphaBlendEnable = true;
sprite.Begin(SpriteFlags.AlphaBlend);
sprite.Draw(texture, rect, new Vector3(0.0f, 0.0f, 0.0f), new Vector3(100.0f, 100.0f, 0.0f), Color.White.ToArgb());
sprite.End();
//End the scene
device.EndScene();
device.Present();
}
}
// Called to repaint the window
protected override void OnPaint(System.Windows.Forms.PaintEventArgs e)
{
// Render on painting
this.Render();
// Render again
this.Invalidate();
}
// Called to repaint the window background
protected override void OnPaintBackground(
System.Windows.Forms.PaintEventArgs e)
{
// Do nothing to ensure that the rendering area is not overdrawn
}
// Close the window when Esc is pressed
protected override void OnKeyPress(
System.Windows.Forms.KeyPressEventArgs e)
{
// Esc was pressed
if ((int)(byte)e.KeyChar == (int)System.Windows.Forms.Keys.Escape)
this.Close();
}
/// <summary>
/// The main entry point for the application.
/// </summary>
static void Main()
{
SimpleSMS frm = new SimpleSMS();
// Initialize Direct3D
if (!frm.InitializeGraphics())
{
MessageBox.Show("Could not initialize Direct3D. " +
"This tutorial will exit.");
return;
}
Application.Run(frm);
}
}
}
Thanks for answers,
Scuse my bad english :-/
Not sure this helps, but RLTODAY works very well with transparent pngs in any WM version, and recently he released the source code:
http://rotlaus-software.de/forum/index.php?topic=1847.0
You can use ImagingFactory in OpenNETCF or other wrapper over the internet. PNGs with alpha work work for me.
AlphaControls
There is a project on Codeplex that can help you with transparency called AlphaControls. Also have a look on codeproject at the iPhone app clone
moneytoo said:
You can use ImagingFactory in OpenNETCF or other wrapper over the internet. PNGs with alpha work work for me.
Click to expand...
Click to collapse
Thank you all for answers ...
I tried OpenNetCF, without any result.
Do you have a piece of code in example ?
Try this:
http://www.codeplex.com/alphamobilecontrols
Or this:
http://johan.andersson.net/blog/2007/10/solution-for-transparent-images-on.html
Hello,
I'm trying to establish connection to the internet using the following code, but not sure that this code is good.
I want to keep my connection for hours (it's a voip program), but the tcp sockets in my application are dropped every one hour or two. Although there is a disconnection, the device still has IP and still shows that it's connected to internet in the status bar on the top. I tried on lots of HTC devices (HD2, Pro2, Pro, etc...)
Can somebody tell if there is something wrong in the code?
Thanks,
Emil.
Code:
void Connect()
{
CONNMGR_CONNECTIONINFO ConnectionInfo;
ZeroMemory (&ConnectionInfo, sizeof (ConnectionInfo));
ConnectionInfo.cbSize = sizeof (ConnectionInfo);
ConnectionInfo.dwParams = CONNMGR_PARAM_GUIDDESTNET;
ConnectionInfo.dwFlags = CONNMGR_FLAG_PROXY_HTTP;
ConnectionInfo.dwPriority = CONNMGR_PRIORITY_USERINTERACTIVE;
ConnectionInfo.bExclusive = TRUE;
ConnectionInfo.guidDestNet = GetNetworkForURL (L"http://www.msn.com");
return ConnMgrEstablishConnectionSync (&ConnectionInfo, &m_hConnection, 30000, dwStatus);
}
void Disconnect()
{
HRESULT hr = ConnMgrReleaseConnection(m_hConnection, TRUE);
m_hConnection = NULL;
}
GUID ConnectionsManager::GetNetworkForURL (LPCTSTR url)
{
DWORD dwIndex = 0;
GUID rv;
if (!SUCCEEDED (ConnMgrMapURL (url, &rv, &dwIndex)))
rv = GUID_NULL;
return rv;
}
I love Android. I want to learn to develop apps. I keep reading tutorials. I got dissapointed and read about HTML frameworks (phonegap, etc). I came back to Android Native Java. I want to learn from the roots. However, some things discourages me....
All this part of the code is just for making a request to the Openweather API and get the json data (plus a little debugging stuff); which in Python or similar languages you only have to care about
- importing the library that handles http requests
- make the request in one function and save it into a json object
Code:
HttpURLConnection urlConnection = null;
BufferedReader reader = null;
// Will contain the raw JSON response as a string.
String forecastJsonStr = null;
String format = "json";
String units = "metric";
int numDays = 7;
try {
final String FORECAST_BASE_URL =
"<the-domain>/data/2.5/forecast/daily?";
final String QUERY_PARAM = "q";
final String FORMAT_PARAM = "mode";
final String UNITS_PARAM = "units";
final String DAYS_PARAM = "cnt";
Uri builtUri = Uri.parse(FORECAST_BASE_URL).buildUpon()
.appendQueryParameter(QUERY_PARAM, params[0])
.appendQueryParameter(FORMAT_PARAM, format)
.appendQueryParameter(UNITS_PARAM, units)
.appendQueryParameter(DAYS_PARAM, Integer.toString(numDays))
.build();
URL url = new URL(builtUri.toString());
Log.v(LOG_TAG, "Built URI " + builtUri.toString());
// Create the request to OpenWeatherMap, and open the connection
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.connect();
// Read the input stream into a String
InputStream inputStream = urlConnection.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) {
// Stream was empty. No point in parsing.
return null;
}
forecastJsonStr = buffer.toString();
Log.v(LOG_TAG, "Forecast string: " + forecastJsonStr);
} catch (IOException e) {
Log.e(LOG_TAG, "Error ", e);
// If the code didn't successfully get the weather data, there's no point in attemping
// to parse it.
return null;
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
if (reader != null) {
try {
reader.close();
} catch (final IOException e) {
Log.e(LOG_TAG, "Error closing stream", e);
}
}
}
This is the complete Class:
Code:
public class FetchWeatherTask extends AsyncTask<String, Void, String[]> {
private final String LOG_TAG = FetchWeatherTask.class.getSimpleName();
/* The date/time conversion code is going to be moved outside the asynctask later,
* so for convenience we're breaking it out into its own method now.
*/
private String getReadableDateString(long time){
// Because the API returns a unix timestamp (measured in seconds),
// it must be converted to milliseconds in order to be converted to valid date.
Date date = new Date(time * 1000);
SimpleDateFormat format = new SimpleDateFormat("E, MMM d");
return format.format(date).toString();
}
/**
* Prepare the weather high/lows for presentation.
*/
private String formatHighLows(double high, double low) {
// For presentation, assume the user doesn't care about tenths of a degree.
long roundedHigh = Math.round(high);
long roundedLow = Math.round(low);
String highLowStr = roundedHigh + "/" + roundedLow;
return highLowStr;
}
/**
* Take the String representing the complete forecast in JSON Format and
* pull out the data we need to construct the Strings needed for the wireframes.
*
* Fortunately parsing is easy: constructor takes the JSON string and converts it
* into an Object hierarchy for us.
*/
private String[] getWeatherDataFromJson(String forecastJsonStr, int numDays)
throws JSONException {
// These are the names of the JSON objects that need to be extracted.
final String OWM_LIST = "list";
final String OWM_WEATHER = "weather";
final String OWM_TEMPERATURE = "temp";
final String OWM_MAX = "max";
final String OWM_MIN = "min";
final String OWM_DATETIME = "dt";
final String OWM_DESCRIPTION = "main";
JSONObject forecastJson = new JSONObject(forecastJsonStr);
JSONArray weatherArray = forecastJson.getJSONArray(OWM_LIST);
String[] resultStrs = new String[numDays];
for(int i = 0; i < weatherArray.length(); i++) {
// For now, using the format "Day, description, hi/low"
String day;
String description;
String highAndLow;
// Get the JSON object representing the day
JSONObject dayForecast = weatherArray.getJSONObject(i);
// The date/time is returned as a long. We need to convert that
// into something human-readable, since most people won't read "1400356800" as
// "this saturday".
long dateTime = dayForecast.getLong(OWM_DATETIME);
day = getReadableDateString(dateTime);
// description is in a child array called "weather", which is 1 element long.
JSONObject weatherObject = dayForecast.getJSONArray(OWM_WEATHER).getJSONObject(0);
description = weatherObject.getString(OWM_DESCRIPTION);
// Temperatures are in a child object called "temp". Try not to name variables
// "temp" when working with temperature. It confuses everybody.
JSONObject temperatureObject = dayForecast.getJSONObject(OWM_TEMPERATURE);
double high = temperatureObject.getDouble(OWM_MAX);
double low = temperatureObject.getDouble(OWM_MIN);
highAndLow = formatHighLows(high, low);
resultStrs[i] = day + " - " + description + " - " + highAndLow;
}
for (String s : resultStrs) {
Log.v(LOG_TAG, "Forecast entry: " + s);
}
return resultStrs;
}
@Override
protected String[] doInBackground(String... params) {
// If there's no zip code, there's nothing to look up. Verify size of params.
if (params.length == 0) {
return null;
}
// These two need to be declared outside the try/catch
// so that they can be closed in the finally block.
HttpURLConnection urlConnection = null;
BufferedReader reader = null;
// Will contain the raw JSON response as a string.
String forecastJsonStr = null;
String format = "json";
String units = "metric";
int numDays = 7;
try {
// Construct the URL for the OpenWeatherMap query
// Possible parameters are avaiable at OWM's forecast API page
final String FORECAST_BASE_URL =
"<the-domain>/data/2.5/forecast/daily?";
final String QUERY_PARAM = "q";
final String FORMAT_PARAM = "mode";
final String UNITS_PARAM = "units";
final String DAYS_PARAM = "cnt";
Uri builtUri = Uri.parse(FORECAST_BASE_URL).buildUpon()
.appendQueryParameter(QUERY_PARAM, params[0])
.appendQueryParameter(FORMAT_PARAM, format)
.appendQueryParameter(UNITS_PARAM, units)
.appendQueryParameter(DAYS_PARAM, Integer.toString(numDays))
.build();
URL url = new URL(builtUri.toString());
Log.v(LOG_TAG, "Built URI " + builtUri.toString());
// Create the request to OpenWeatherMap, and open the connection
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.connect();
// Read the input stream into a String
InputStream inputStream = urlConnection.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) {
// Since it's JSON, adding a newline isn't necessary (it won't affect parsing)
// But it does make debugging a *lot* easier if you print out the completed
// buffer for debugging.
buffer.append(line + "\n");
}
if (buffer.length() == 0) {
// Stream was empty. No point in parsing.
return null;
}
forecastJsonStr = buffer.toString();
Log.v(LOG_TAG, "Forecast string: " + forecastJsonStr);
} catch (IOException e) {
Log.e(LOG_TAG, "Error ", e);
// If the code didn't successfully get the weather data, there's no point in attemping
// to parse it.
return null;
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
if (reader != null) {
try {
reader.close();
} catch (final IOException e) {
Log.e(LOG_TAG, "Error closing stream", e);
}
}
}
try {
return getWeatherDataFromJson(forecastJsonStr, numDays);
} catch (JSONException e) {
Log.e(LOG_TAG, e.getMessage(), e);
e.printStackTrace();
}
// This will only happen if there was an error getting or parsing the forecast.
return null;
}
}
I mean, I know this code can be reduced, but I'm angry about the way it works. Everything needs to be passed to another object! And even rembember all those castings! Castings everywhere!
- The builded URI to the URL.
- The URL to the HttpConection variable.
- Once you connect, save that into the InputStream.
- Make a StringBuffer because we are going to send line by line everything.
- Then create the reader = new BufferedReader(new InputStreamReader(inputStream)).
- Append the lines to the buffer and return if it's ok.
- Else catch all the errors and be sure to close all the connections.
Damn Java !
Forgive me. You'll hate me.
Java is readable, that's the truth... but don't tell me that it is easy for a normal person.
Am I the only one?
If you are a beginner and will straight move to these classes. You will obviously find Java difficult. But Java is very easy if you move step by step from start
Sent from my XT1033 using XDA Premium 4 mobile app
---------- Post added at 04:18 PM ---------- Previous post was at 04:16 PM ----------
And that library also does the same thing inside. Only difference is, your work is already done by author of the library.
Sent from my XT1033 using XDA Premium 4 mobile app
Java is definitely a very verbose language but it's also widely used and so you will find many libraries that do tasks like grab JSON data from a service that have already been implemented for you
manwoman said:
Damn Java !
Forgive me. You'll hate me.
Java is readable, that's the truth... but don't tell me that it is easy for a normal person.
Am I the only one?
Click to expand...
Click to collapse
I don't think you're the only one. It's easy to get scared away by the many too verbose examples available, the key is to look at what you're trying to achieve and then break it up into those parts.
Your code listing is (I think) an attempt to show all steps to get the forecast data, but if that would have been broken up into smaller steps I don't think you'd look at it as quite as bad.
You would then have methods like
Code:
URL getForecastUrl(String parameter);
Code:
BufferedReader getUrl(URL url) { }
Code:
String readAll(BufferedReader reader) {}
Each of which would have had something like 6-7 lines of simple, cohesive code.
I understand your point, but in this particular scenario I think you're the victim of a poorly structured code sample rather than a too verbose language.
If you think the default implementation is too complicated, here are also many java libraries which will make your life easier.
I have an android application that is receiving a string from an arduino via Bluetooth, names the string "data" and displays it by setting a TextView to the string "data". I want a chronometer to start when the incoming string matches a predefined string.
For example:
Code:
if data.equals(startChrono)){
chronometerLeft.setBase(SystemClock.elapsedRealtime());
chronometerLeft.start();
I actually have the arduino sending a "g" and am setting my string goL to be "g" but cannot get the chronometer to start when the g is received. My TextView shows the g. Code is below. I've tried several things and at a loss. Using same code for chronometer.start() with onClickListener with a button works great. I just need it to start the chronometer when i receive a specific string from the arduino.
Code:
beginListenForData();
// text.setText("Bluetooth Opened");
}
void beginListenForData() {
final Handler handler = new Handler();
final byte delimiter = 10; // This is the ASCII code for a newline
// character
stopWorker = false;
readBufferPosition = 0;
readBuffer = new byte[1024];
workerThread = new Thread(new Runnable() {
public void run() {
while (!Thread.currentThread().isInterrupted() && !stopWorker) {
try {
int bytesAvailable = mmInputStream.available();
if (bytesAvailable > 0) {
byte[] packetBytes = new byte[bytesAvailable];
mmInputStream.read(packetBytes);
for (int i = 0; i < bytesAvailable; i++) {
byte b = packetBytes[i];
if (b == delimiter) {
byte[] encodedBytes = new byte[readBufferPosition];
System.arraycopy(readBuffer, 0,
encodedBytes, 0,
encodedBytes.length);
final String data = new String(
encodedBytes, "US-ASCII");
readBufferPosition = 0;
handler.post(new Runnable() {
public void run() {
text.setText(data);
String goL = "g";
String goR = "f";
chronometerLeft = (Chronometer)findViewById(R.id.chronometerLeft);
chronometerRight = (Chronometer)findViewById(R.id.chronometerRight);
if(data.equals(goL)){
chronometerLeft.setBase(SystemClock.elapsedRealtime());
chronometerLeft.start();
if(data.equals(goR))
chronometerRight.setBase(SystemClock.elapsedRealtime());
chronometerRight.start();
}
}
});
} else {
readBuffer[readBufferPosition++] = b;
}
}
}
} catch (IOException ex) {
stopWorker = true;
}
}
}
});
workerThread.start();
}
Sorry to bother, but in your while loop condition, what does the '!' before Thread do?
I hope someone can help me.
I'm having trouble getting an Apple WeatherKit REST request working. I'm trying to follow all of the requirements listed on https://developer.apple.com/documen...equest_authentication_for_weatherkit_rest_api, but I still get a 403 response code -- and I can't locate any Java samples to follow. I've been sweating this for weeks and haven't gotten anywhere.
Here's what I have:
URL url = new URL ("https://weatherkit.apple.com/api/v1/weather/en/40.75/-73.00?dataSets=currentWeather&timezone=Europe/London");
PrivateKey pkey = getPrivateKey ("AuthKey_CXXXXXXXXX.p8");
String jwts = getJwtsString (pkey);
HttpURLConnection conn = getConnection (url, jwts);
conn.connect();
int responsecode = conn.getResponseCode();
Just in case I've got something wrong, here are the three functions I'm calling. First, the one that creates the PrivateKey from the p8 file (I'm pretty sure this one is OK):
private PrivateKey getPrivateKey (String filename) {
PrivateKey privateKey = null;
try {
AssetManager assetManager = this.getAssets();
InputStream stream = assetManager.open(filename);
byte[] bytes = new byte[stream.available()];
int bytesRead = stream.read(bytes);
byte[] pkcs8EncodedKey = new byte[0];
pkcs8EncodedKey = Base64.getDecoder().decode(bytes);
KeyFactory factory = KeyFactory.getInstance("EC");
privateKey = factory.generatePrivate(new PKCS8EncodedKeySpec(pkcs8EncodedKey));
} catch (Exception e) { }
return privateKey;
}
Next, creating the JWTS string:
private String getJwtsString(PrivateKey privateKey) {
long t1 = System.currentTimeMillis();
return Jwts.builder()
.setHeaderParam ("alg", "ES256")
.setHeaderParam ("kid", "CXXXXXXXXX")
.setHeaderParam ("id", "QXXXXXXXXX.com.mydomain.myproject")
.claim ("iss", "Q5DC438ZG4")
.claim ("iat", t1)
.claim ("exp", t1 + 60000)
.claim ("sub", "com.mydomain.myproject") // obviously, replaced with my project info
.signWith (privateKey, SignatureAlgorithm.ES256)
.compact ();
}
And finally, creating the connection:
private HttpURLConnection getConnection(URL url, String jws) {
HttpURLConnection conn = (HttpURLConnection) Objects.requireNonNull(url).openConnection();
conn.setRequestMethod ("GET")
conn.setRequestProperty ("Authorization", "Bearer "+ jws);
conn.setRequestProperty ("Content-Type", "application/x-www-form-urlencoded");
conn.setRequestProperty ("Content-Language", "en-US");
conn.setUseCaches (false);
conn.setDoInput (true);
conn.setDoOutput (true);
conn.setConnectTimeout (30000); //set timeout to 30 seconds
return conn;
}
Obviously, this is the first time I've tried creating an authenticated http call, so I wouldn't be at all surprised if this is wrong.
Can anybody supply some sample code that I could follow?
Thanks in advance...