How to pass token from Nodejs to backend Java code - node.js

I am new to Nodejs .
I am trying to pass JWT token from Nodejs to java service class.
I am getting JWT token in a variable in Nodejs code that I need to pass to spring mvc application service class.
can anyone please help me on this?
And having confusion with how to integrate Nodejs with java if i pass variable from Nodejs to java?
Node code is,
module.exports = {
verifyReq: function (req, res, next) {
if (req.headers.authorization) {
res.setHeader('Content-Type', 'text/html');
res.write('<div id="_mscontent"><script src="URL"></script>');
var notAuthorized = false;
var authorization = req.headers.authorization;
console.log("authorization: " + authorization);
if (authorization) {
req.isAuthorized = true;
}
try {
var decodedJWT = JWT.decode(authorization.split(' ')[1], "", true);
} catch (e) {
notAuthorized = true;
}
else {
req.isAuthorized = false;
res.status(401);
res.end('Not Authorized!');
return;
}
return req.isAuthorized === true;
}
};
Java Code,
public class GetCarAssetValuesService {
private static String output;
private static String token;
private static Asset[] myObjects;
public void getAssets(String tokenToPass)
throws JsonParseException, JsonMappingException, IOException, JSONException {
System.out.println("In service");
HttpsURLConnection myURLConnection = null;
InputStream inputStream = null;
InputStreamReader inputStreamReader = null;
BufferedReader bufferedReader = null;
StringBuilder strBuilder = new StringBuilder();
JSONObject jsonObj = new JSONObject(tokenToPass);
System.out.println("success_token= " + jsonObj);
token = jsonObj.getString("access_token");
System.out.println("Print token= " + token);
try {
URL url = new URL(
"Third Party URL");
myURLConnection = (HttpsURLConnection) url.openConnection();
String bearerAuth = "Bearer " + token;
myURLConnection.setRequestProperty("Authorization", bearerAuth);
myURLConnection.setRequestMethod("GET");
myURLConnection.setRequestProperty("Content-Type", "application/json");
myURLConnection.setDoOutput(true);
inputStream = myURLConnection.getInputStream();
inputStreamReader = new InputStreamReader(inputStream);
bufferedReader = new BufferedReader(inputStreamReader);
if (myURLConnection.getResponseCode() != 200) {
throw new RuntimeException("Failed : HTTP error code : " + myURLConnection.getResponseCode());
}
System.out.println("Here the control cars...");
System.out.println("Output from Server .... \n");
while ((output = bufferedReader.readLine()) != null) {
strBuilder.append(output);
System.out.println(output);
}
myURLConnection.disconnect();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
String mindsphereResponse = strBuilder.toString();
System.out.println("Responsesssssss" + mindsphereResponse);
ObjectMapper mapper = new ObjectMapper();
myObjects = mapper.readValue(mindsphereResponse, Asset[].class);
}
Here instead of passing "tokenToPass" i want to get this token from node js i.e.decodeJWT. This "tokenToPass" i am getting from other java service now i want it from Nodejs.
Thanks in Advance..!!!

You can set the JWT token in the HTTP Request header ( nodejs ) and API endpoint ( java ) can be get it from there.
HelloController.java
#Controller
public class HomeController {
#Autowire
private HomeService homeService;
#GetMapping("/hello")
public String home(HttpServletRequest request, Model model) {
helloService.invoke(request.getHeader('JWT_TOKEN_KEY'));
}
}
HelloService.java
#Service
public class HelloService {
public void invoke(jwtToken) {
// Use this jwttoken
}
}
NodeJS.js
var options = {
host: 'your_java_api_endpoint',
port: 80,
path: '/hello',
headers:{
'JWT_TOKEN_KEY':'json web token here'
}
};
http.get(options, function(res) {
res.on("data", function(responseData) {
console.log("data: " + responseData);
});
}).on('error', function(e) {
console.log("http error : " + e);
});

Related

Integrate SharePoint Office 365 into .net core project

I would like to share some bit of experience and troubles that I met while doing a folder creation and moving by using RESTful API.
**Create a Folder: **
You will need sharePoint Token
public async Task<JObject> getSharePointToken()
{
var sharPointTokenRequestUrl = "https://accounts.accesscontrol.windows.net/" + _configuration["MicrosoftGraph: TenantId"] + "/tokens/OAuth/2";
var parameters = new Dictionary<string, string>();
parameters["grant_type"] = "client_credentials";
parameters["client_id"] = "your client id";
parameters["client_secret"] = "your client secret";
parameters["resource"] = "resource id";
var par = new FormUrlEncodedContent(parameters);
using (var httpClient = new HttpClient())
{
using (var request = new HttpRequestMessage(new HttpMethod("POST"), sharPointTokenRequestUrl))
{
var response = await httpClient.PostAsync(sharPointTokenRequestUrl, par);
string responseBody = await response.Content.ReadAsStringAsync();
var result = JObject.Parse(responseBody);
return result;
}
}
}
Also You will need XRequest Digest
public async Task<JObject> getXRequestDigest()
{
var sharPointXRequestDigesttUrl = "https://your site /_api/contextinfo";
var sharePointTokenString = getSharePointToken().Result.ToString();
var sharePointToken = JsonConvert.DeserializeObject<SharePointTokenDto>(sharePointTokenString);
var parameters = new Dictionary<string, string>();
var par = new FormUrlEncodedContent(parameters);
using (var httpClient = new HttpClient())
{
httpClient.DefaultRequestHeaders.Add("Authorization", "Bearer " + sharePointToken.access_token);
httpClient.DefaultRequestHeaders.Add("Accept", "application/json;odata=verbose");
using (var request = new HttpRequestMessage(new HttpMethod("POST"), sharPointXRequestDigesttUrl))
{
var response = await httpClient.PostAsync(sharPointXRequestDigesttUrl, par);
string responseBody = await response.Content.ReadAsStringAsync();
var result = JObject.Parse(responseBody);
return result;
}
}
}
Then you could Crate Folder In SharePoint
namespace Sharepoint.Dtos
{
public class SharePointTokenDto
{
public string token_type { get; set; }
public string expires_in { get; set; }
public string not_before { get; set; }
public string expires_on { get; set; }
public string resource { get; set; }
public string access_token { get; set; }
}
}
public async Task<Boolean> CrateFolderInSharePoint(string folderPath)
{
var sharePointTokenString = getSharePointToken().Result.ToString();
var sharePointToken = JsonConvert.DeserializeObject<SharePointTokenDto>(sharePointTokenString);
var xRequestDigest = await getXRequestDigest();
var FormDigestValue = xRequestDigest["d"]["GetContextWebInformation"]["FormDigestValue"];
var siteUrl = "https://yoursites-url/sites/SiteName/_api/web/folders";
var folderUrl = "/sites/SiteName/Shared Documents" + folderPath;
var body = new Dictionary<string, string>
{
{ "ServerRelativeUrl", folderUrl }
};
string bodyString = JsonConvert.SerializeObject(body);
bodyString.Insert(0, " \"__metadata\": { \"type\": \"SP.Folder\" } ");
var content = new StringContent(bodyString, Encoding.UTF8, "application/json");
using (var httpClient = new HttpClient())
{
httpClient.DefaultRequestHeaders.Add("Authorization", "Bearer " + sharePointToken.access_token);
httpClient.DefaultRequestHeaders.Add("Accept", "application/json;odata=verbose");
httpClient.DefaultRequestHeaders.Add("X-RequestDigest", FormDigestValue.ToString());
using (var request = new HttpRequestMessage(new HttpMethod("POST"), siteUrl))
{
var response = await httpClient.PostAsync(siteUrl, content);
string responseBody = await response.Content.ReadAsStringAsync();
var result = JObject.Parse(responseBody);
if (response.IsSuccessStatusCode)
{
return true;
}
else
{
return false;
}
}
}
}

Export Datatable to Excel using .Net core

I am trying to export datatable to excel. I am facing problem with Tempdata and ActionResult. I am getting the following error:
Failed to load resource: the server responded with a status of 500 () at the ExportExcelGrid() Action method.
[HttpPost]
public void ExportExcelGrid(DataTableAjaxPostModel dataTableAjaxPostModel)
{
try
{
byte[] fileContent = null;
fileContent = _specFinderExportFlow.ConvertToExportable(dataTableAjaxPostModel, User.Identity.Name);
TempData["FileContent"] = fileContent;
}
catch (Exception ex)
{
throw ex;
}
}
[HttpGet]
public ActionResult ExportExcelGrid()
{
try
{
if (TempData["FileContent"] != null)
{
byte[] fileContent = (byte[])TempData["FileContent"];
string dateTime = DateTime.Now.ToString("ddMMyyyy");
string fileDownloadName = UserConstants.EXPORT_FILE_NAME + dateTime + UserConstants.EXPORT_FILE_EXT;
return File(fileContent, ExcelExportHelper.ExcelContentType, fileDownloadName);
}
else
return null;
}
catch (Exception ex)
{
throw ex;
}
}
And in my script I have used ajax call to get the datatable.
$('#productexport').on('click', function () {
$.ajax({
type: "POST",
url: $("#ExportExcelGrid").val(),
data: findertable.ajax.params(),
success: function (response) {
window.location.href = $("#ExportExcelGrid").val();
},
failure: function (response) {
},
error: function (response) {
}
});
});
After ExportExcelGrid(DataTableAjaxPostModel dataTableAjaxPostModel) method ExportExcelGrid() has to be called. But it is not getting called. If I use ViewData it is null. Can anyone tell me where I am wrong.

How to catch an exception from Azure Mobile App Backend?

In my Azure Mobile App backend, I have a validation for the data in a post method. In certains circunstances, the backend server throw an exception, but, in the app side, I can't get catch this exception. How can I do that?
That's my method
// POST tables/Paciente
public async Task<IHttpActionResult> PostPaciente(Paciente novoPaciente)
{
//other things
if (paciente != null)
{
var responseMessage = new HttpResponseMessage(HttpStatusCode.BadRequest)
{
Content = new StringContent("Já existe um paciente com esse token cadastrado.")
};
//throw new HttpResponseException(responseMessage);
return InternalServerError(new Exception("Já existe um paciente com esse token cadastrado."));
}
}
I tried throw HttpResponseException and return InternalServerException, but none works.
You need to check the status code of the response to your http call (there should be a IsSuccesStatusCode property to check).
I recommend using EnsureSuccessStatusCode() which exists in the HttpResponseMessage class. This method will throw an exception if the StatusCode is not OK (or some variant of a 200-level status code).
Below is a generic class, BaseHttpClientServices, that I use for making REST API requests in all of my projects. It follows all of the best practices for using HttpClient like Reusing HttpClient, Deserializing JSON using Stream, and using ConfigureAwait(false).
Sending A Post Request in Xamarin.Forms
public abstract class HttpClientServices : BaseHttpClientServices
{
const string apiUrl = "your api url";
public static void PostPaciente(Paciente novoPaciente)
{
try
{
var response = await PostObjectToAPI(apiUrl, novoPaciente);
response.EnsureSuccessStatusCode();
}
catch(Exception e)
{
//Handle Exception
}
}
}
Generic HttpClient Implementation
using System;
using System.IO;
using System.Net;
using System.Text;
using System.Net.Http;
using System.Threading.Tasks;
using System.Net.Http.Headers;
using System.Runtime.CompilerServices;
using Newtonsoft.Json;
using Xamarin.Forms;
namespace NameSpace
{
public abstract class BaseHttpClientService
{
#region Constant Fields
static readonly Lazy<JsonSerializer> _serializerHolder = new Lazy<JsonSerializer>();
static readonly Lazy<HttpClient> _clientHolder = new Lazy<HttpClient>(() => CreateHttpClient(TimeSpan.FromSeconds(60)));
#endregion
#region Fields
static int _networkIndicatorCount = 0;
#endregion
#region Properties
static HttpClient Client => _clientHolder.Value;
static JsonSerializer Serializer => _serializerHolder.Value;
#endregion
#region Methods
protected static async Task<T> GetObjectFromAPI<T>(string apiUrl)
{
using (var responseMessage = await GetObjectFromAPI(apiUrl).ConfigureAwait(false))
return await DeserializeResponse<T>(responseMessage).ConfigureAwait(false);
}
protected static async Task<HttpResponseMessage> GetObjectFromAPI(string apiUrl)
{
try
{
UpdateActivityIndicatorStatus(true);
return await Client.GetAsync(apiUrl).ConfigureAwait(false);
}
catch (Exception e)
{
Report(e);
throw;
}
finally
{
UpdateActivityIndicatorStatus(false);
}
}
protected static async Task<TResponse> PostObjectToAPI<TResponse, TRequest>(string apiUrl, TRequest requestData)
{
using (var responseMessage = await PostObjectToAPI(apiUrl, requestData).ConfigureAwait(false))
return await DeserializeResponse<TResponse>(responseMessage).ConfigureAwait(false);
}
protected static Task<HttpResponseMessage> PostObjectToAPI<T>(string apiUrl, T requestData) => SendAsync(HttpMethod.Post, apiUrl, requestData);
protected static async Task<TResponse> PutObjectToAPI<TResponse, TRequest>(string apiUrl, TRequest requestData)
{
using (var responseMessage = await PutObjectToAPI(apiUrl, requestData).ConfigureAwait(false))
return await DeserializeResponse<TResponse>(responseMessage).ConfigureAwait(false);
}
protected static Task<HttpResponseMessage> PutObjectToAPI<T>(string apiUrl, T requestData) => SendAsync(HttpMethod.Put, apiUrl, requestData);
protected static async Task<TResponse> PatchObjectToAPI<TResponse, TRequest>(string apiUrl, TRequest requestData)
{
using (var responseMessage = await PatchObjectToAPI(apiUrl, requestData).ConfigureAwait(false))
return await DeserializeResponse<TResponse>(responseMessage).ConfigureAwait(false);
}
protected static Task<HttpResponseMessage> PatchObjectToAPI<T>(string apiUrl, T requestData) => SendAsync(new HttpMethod("PATCH"), apiUrl, requestData);
protected static async Task<TResponse> DeleteObjectFromAPI<TResponse>(string apiUrl)
{
using (var responseMessage = await DeleteObjectFromAPI(apiUrl).ConfigureAwait(false))
return await DeserializeResponse<TResponse>(responseMessage).ConfigureAwait(false);
}
protected static Task<HttpResponseMessage> DeleteObjectFromAPI(string apiUrl) => SendAsync<object>(HttpMethod.Delete, apiUrl);
static HttpClient CreateHttpClient(TimeSpan timeout)
{
HttpClient client;
switch (Device.RuntimePlatform)
{
case Device.iOS:
case Device.Android:
client = new HttpClient();
break;
default:
client = new HttpClient(new HttpClientHandler { AutomaticDecompression = DecompressionMethods.GZip });
break;
}
client.Timeout = timeout;
client.DefaultRequestHeaders.AcceptEncoding.Add(new StringWithQualityHeaderValue("gzip"));
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
return client;
}
static async Task<HttpResponseMessage> SendAsync<T>(HttpMethod httpMethod, string apiUrl, T requestData = default)
{
using (var httpRequestMessage = await GetHttpRequestMessage(httpMethod, apiUrl, requestData).ConfigureAwait(false))
{
try
{
UpdateActivityIndicatorStatus(true);
return await Client.SendAsync(httpRequestMessage).ConfigureAwait(false);
}
catch (Exception e)
{
Report(e);
throw;
}
finally
{
UpdateActivityIndicatorStatus(false);
}
}
}
static void UpdateActivityIndicatorStatus(bool isActivityIndicatorDisplayed)
{
if (isActivityIndicatorDisplayed)
{
Device.BeginInvokeOnMainThread(() => Application.Current.MainPage.IsBusy = true);
_networkIndicatorCount++;
}
else if (--_networkIndicatorCount <= 0)
{
Device.BeginInvokeOnMainThread(() => Application.Current.MainPage.IsBusy = false);
_networkIndicatorCount = 0;
}
}
static async ValueTask<HttpRequestMessage> GetHttpRequestMessage<T>(HttpMethod method, string apiUrl, T requestData = default)
{
var httpRequestMessage = new HttpRequestMessage(method, apiUrl);
switch (requestData)
{
case T data when data.Equals(default(T)):
break;
case Stream stream:
httpRequestMessage.Content = new StreamContent(stream);
httpRequestMessage.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
break;
default:
var stringPayload = await Task.Run(() => JsonConvert.SerializeObject(requestData)).ConfigureAwait(false);
httpRequestMessage.Content = new StringContent(stringPayload, Encoding.UTF8, "application/json");
break;
}
return httpRequestMessage;
}
static async Task<T> DeserializeResponse<T>(HttpResponseMessage httpResponseMessage)
{
httpResponseMessage.EnsureSuccessStatusCode();
try
{
using (var contentStream = await httpResponseMessage.Content.ReadAsStreamAsync().ConfigureAwait(false))
using (var reader = new StreamReader(contentStream))
using (var json = new JsonTextReader(reader))
{
if (json is null)
return default;
return await Task.Run(() => Serializer.Deserialize<T>(json)).ConfigureAwait(false);
}
}
catch (Exception e)
{
Report(e);
throw;
}
}
static void Report(Exception e, [CallerMemberName]string callerMemberName = "") => Debug.WriteLine(e.Message);
#endregion
}
}

How to Set User login Windows Phone 8 using sqlite database?

Hi i am using windows phone 8 app. i want to set existing user login, i can add user registration but i can't do user login my code is give below.
public partial class LoginPage : PhoneApplicationPage
{
public LoginPage()
{
InitializeComponent();
}
public static class dal
{
public static SQLiteAsyncConnection connection;
public static bool isDatabaseExisting;
public static async void ConnectToDB()
{
try
{
StorageFile storageFile = await ApplicationData.Current.LocalFolder.GetFileAsync("Bestin.sqlite");
isDatabaseExisting = true;
}
catch (Exception ex)
{
isDatabaseExisting = false;
}
if (!isDatabaseExisting)
{
try
{
StorageFile databaseFile = await Package.Current.InstalledLocation.GetFileAsync("Bestin.sqlite");
await databaseFile.CopyAsync(ApplicationData.Current.LocalFolder);
isDatabaseExisting = true;
}
catch (Exception ex)
{
isDatabaseExisting = false;
}
}
if (isDatabaseExisting)
{
connection = new SQLiteAsyncConnection(Path.Combine(ApplicationData.Current.LocalFolder.Path, "Bestin.sqlite"), true);
}
}
}
private void Click_Login(object sender, RoutedEventArgs e)
{
dal.ConnectToDB();
var query = dal.connection.QueryAsync<Task>("SELECT * FROM Task Where Email=" + "\'" + txtEmailaddress.Text + "\'" + "and Password=" + "\'" + txtPassword.Password + "\'").Result;
if (query == null)
{
// invalid Login credentials
}
else
{
// do login
}
}
}
I am using your code.I got error The system cannot find the file specified. (Exception from HRESULT: 0x80070002)
ok so do this ....
public static class dal
{
public static SQLiteAsyncConnection connection;
public static bool isDatabaseExisting;
public static async void ConnectToDB()
{
try
{
StorageFile storageFile = await ApplicationData.Current.LocalFolder.GetFileAsync("Bestin.sqlite");
isDatabaseExisting = true;
}
catch (Exception ex)
{
isDatabaseExisting = false;
}
if (!isDatabaseExisting)
{
try
{
StorageFile databaseFile = await Package.Current.InstalledLocation.GetFileAsync("Bestin.sqlite");
await databaseFile.CopyAsync(ApplicationData.Current.LocalFolder);
isDatabaseExisting = true;
}
catch (Exception ex)
{
isDatabaseExisting = false;
}
}
if (isDatabaseExisting)
{
connection = new SQLiteAsyncConnection(Path.Combine(ApplicationData.Current.LocalFolder.Path, "Bestin.sqlite"), true);
}
}
}
make a class like above code for your database connection and call this at your application startup like this dal.ConnectToDB();
then in your loginpage do like this...
private void Click_Login(object sender, RoutedEventArgs e)
{
var query = dal.connection.QueryAsync<Task>("SELECT * FROM Task Where Email=" + "\'" + txtEmailaddress.Text + "\'" + "and Password=" + "\'" + txtPassword.Password + "\'").Result;
if(query == null)
{
// invalid Login credentials
}
else
{
// do login
}
}
you can try this ..
private void Click_Login(object sender, RoutedEventArgs e)
{
dbConn = new SQLiteConnection(DB_PATH);
var query = dbconn.QueryAsync<Task>("SELECT * FROM Task Where Email=" + "\'" + txtEmailaddress.Text + "\'" + "and Password=" + "\'" + txtPassword.Password + "\'").Result;
if(query == null)
{
// invalid Login credentials
}
else
{
// do login
}
}
Hi i got solution in my question..,
using (var dbConn = new SQLiteConnection(DB_PATH))
{
var existing = dbConn.Query<Userlist>("select * from Userlist Where Email=" + "\'" + txtEmailaddress.Text + "\'" + "and Password=" + "\'" + txtPassword.Text + "\'").FirstOrDefault();
if (existing != null)
{
NavigationService.Navigate(new Uri("/Input.xaml?selectedItem=", UriKind.Relative));
}
else
{
MessageBox.Show("invalid login");
}
}

foursquare adding a tip exception

I am working on foursquare API v2 in Android.
In my application User can check-in and add a tip.
check- in method is working good but add a tip method got error.
private void methodTipAdd(String venueId, String tip, boolean auth) {
StringBuilder urlBuilder = new StringBuilder("https://api.foursquare.com/v2/");
urlBuilder.append("tips/add");
urlBuilder.append('?');
try{
urlBuilder.append("venueId").append('=');
urlBuilder.append(URLEncoder.encode(venueId, "UTF-8")).append('&');
}catch(Exception e) {
e.printStackTrace();
}
try{
urlBuilder.append("text").append('=');
urlBuilder.append(URLEncoder.encode(tip, "UTF-8")).append('&');
}catch(Exception e) {
e.printStackTrace();
}
if (auth) {
urlBuilder.append("oauth_token=");
urlBuilder.append(getAccessToken());
} else {
urlBuilder.append("client_id=");
urlBuilder.append(CLIENT_ID);
urlBuilder.append("&client_secret=");
urlBuilder.append(CLIENT_SECRET);
}
urlBuilder.append("&v=" + getVersion());
String url = urlBuilder.toString();
String result = null;
try {
URL aUrl = new URL(url);
HttpURLConnection connection = (HttpURLConnection) aUrl.openConnection();
try {
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setRequestMethod("POST");
connection.connect();
int code = connection.getResponseCode();
if (code == 200) {
InputStream inputStream = connection.getInputStream();
result = convertStreamToString(inputStream);
android.util.Log.e(tag, "result: " + result);
// handle tip
} else {
android.util.Log.e(tag, "HttpURLConnection response code: " + code);
}
} finally {
connection.disconnect();
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
request url : https://api.foursquare.com/v2/tips/add?venueId=[venue id]&text=[utf-8 encoded text]&oauth_token=[my_oauth_token]&v=20120730
ex) https://api.foursquare.com/v2/tips/add?venueId=XXX123YYY&text=Good&oauth_token=XXX123YYY&v=20120730
http response code: 400
I want to know why i got the HTTP_BAD_REQUEST response code.
when doing a POST the parameters should not be part of the URL (specify them as parameters to the POST).
I solved the problem.
private void methodTipAdd3(String venueId, String tip) {
String url = "https://api.foursquare.com/v2/tips/add";
StringBuilder sb = new StringBuilder();
sb.append("oauth_token=");
sb.append(getAccessToken()).append('&');
try{
sb.append("venueId").append('=');
sb.append(URLEncoder.encode(venueId, "UTF-8")).append('&');
}catch(Exception e) {
e.printStackTrace();
}
try{
sb.append("text").append('=');
sb.append(URLEncoder.encode(tip, "UTF-8")).append('&');
}catch(Exception e) {
e.printStackTrace();
}
sb.append("v=" + getVersion());
String params = sb.toString();
String result = null;
int httpcode = 200;
try {
URL aUrl = new URL(url);
HttpURLConnection connection = (HttpURLConnection) aUrl.openConnection();
try {
connection.setDoInput(true);
connection.setRequestMethod("POST");
connection.setRequestProperty("Accept", "application/json");
byte buf[] = params.getBytes("UTF-8");
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.setRequestProperty("Content-Length", String.valueOf(buf.length));
connection.setDoOutput(true);
OutputStream outputstream = connection.getOutputStream();
outputstream.write(buf);
outputstream.flush();
outputstream.close();
httpcode = connection.getResponseCode();
if (httpcode == 200) {
InputStream inputStream = connection.getInputStream();
result = convertStreamToString(inputStream);
// handle tip
android.util.Log.e(tag, "result: " + result);
} else {
android.util.Log.e(tag, "http response code: " + httpcode);
}
} finally {
connection.disconnect();
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}

Resources