How to save image in byte[] to sql server(varbinary(max)) windows - image

I'm getting error
implicit conversion from data type varchar to varbinary is not allowed use the convert function
i have used varbinary(max) datatype in ms sql server for storing image and converted image to byte[] and trying to save the image.
public bool InsertProd(PRODUCT_CAT crse)
{
StringBuilder query = new StringBuilder();
bool success;
query.Append("INSERT INTO PRODUCT_CATEGORY (PROD_CATE_ID,PROD_IMAGE) VALUES"('" + crse.Id + "',','" +crse.Image+ "')");
success = dbObj.ExecuteQuery(query.ToString());
return success;
}
public class PRODUCT_CAT
{
public int Id { get; set; }
public byte[] Imge { get; set; }
public PRODUCT_CAT(int id,byte[] image)
{
Id = id;
Imge = image;
}
}
updated code
public int InsertProd(PRODUCT_CAT crse)
{
int success;
string ins = "INSERT INTO PRODUCT_CATEGORY (PROD_CATE_ID,PROD_IMAGE) VALUES" +
" (#id, #img)";
con.Open();
SqlCommand cmd = new SqlCommand(ins, con);
cmd.Parameters.Add(new SqlParameter("#id", crse.Id));
cmd.Parameters.Add(new SqlParameter("#img", crse.Imge));
success = cmd.ExecuteNonQuery();
con.Close();
return success;
}
now byte[] is saved like this

Related

Cannot deserialize the current JSON object into type ObservableCollection because the type requires a JSON array

I'm trying to display a search result API in a ListView.
This is the model which I want to display in the ListView:
public class Video
{
[Key]
public int VideoId { get; set; }
public string Exercice { get; set; }
public string Titre { get; set; }
public int Sexe{ get; set; }
public int Categorie { get; set; }
public int Level { get; set; }
public string FilePath { get; set; }
public DateTime DateUpload { get; set; } = DateTime.Now;
[ForeignKey("Machine")]
public int Machine_Qr { get; set; }
}
This is the get method:
public async Task<ObservableCollection<Video>> search(string qr)
{
string url = Base_url + "machines/" +qr;
try
{
HttpClient client = new HttpClient();
HttpResponseMessage responseMessage = await client.GetAsync(url);
var result = await responseMessage.Content.ReadAsStringAsync();
var json = JsonConvert.DeserializeObject<ObservableCollection<Video>>(result);
return json;
}
catch(Exception ex)
{
Console.WriteLine(ex.Message);
}
return null;
}
the result json value:
[
{
"videoId": 7,
"exercice": "string",
"titre": "string",
"sexe": 0,
"categorie": 0,
"level": 0,
"filePath": "string",
"dateUpload": "2022-07-07T13:13:39.725",
"machine_Qr": 7895,
"machine": null
}
]
This is the View.cs
public partial class SearchResult : INotifyPropertyChanged
{
IMachineService _rest = DependencyService.Get<IMachineService>();
public SearchResult(string value)
{
InitializeComponent();
qr.Text = value;
GetVideos();
}
public async void GetVideos()
{
string value = qr.Text;
var result = await _rest.search(value);
if (result != null)
{
Videos = result;
}
}
public ObservableCollection<Video> videos;
public ObservableCollection<Video> Videos
{
get { return videos; }
set
{
videos = value;
}
}
but I got an exception while debugging this line in the service
HttpResponseMessage responseMessage = await client.GetAsync(url);
and this is the detailed exception:
Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.ObjectModel.ObservableCollection`1[App5.Models.Video]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly.
To fix this error either change the JSON to a JSON array (e.g. [1,2,3]) or change the deserialized type so that it is a normal .NET type (e.g. not a primitive type like integer, not a collection type like an array or List) that can be deserialized from a JSON object. JsonObjectAttribute can also be added to the type to force it to deserialize from a JSON object.
Path 'type', line 1, position 8.
Do this as a test:
public ObservableCollection<Video> search(string qr)
{
try
{
var result = "[ { \"videoId\": 7, \"exercice\": \"string\", \"titre\": \"string\","
+ " \"sexe\": 0, \"categorie\": 0, \"level\": 0, \"filePath\": \"string\","
+ " \"dateUpload\": \"2022-07-07T13:13:39.725\", \"machine_Qr\": 7895, \"machine\": null } ]";
var json = JsonConvert.DeserializeObject<ObservableCollection<Video>>(result);
return json;
}
catch(Exception ex)
{
Console.WriteLine(ex.Message);
}
return null;
}
Put breakpoint on both return statements. To make sure this really is the code that is giving the error. Which breakpoint does it hit now? Does it print the same exception message?

how to save a picker value to the web api using the mvvm properties in the command?

I have a xamarin forms application and would like to save some values ​​that I got from the picker via the web api. The objective is to save this value as well as the other properties in the web api that is linked to the sql server database, but I have issues in how to reference the value selected in the picker through mvvm. I can load the data from the picker but I just don't know how to save these values ​​by referencing the picker in mvvm.
UsuarioModel Class
This is the model class, it has the CodPerfil property which is the foreign key that should be stored in my web api database and must correspond to the value that will be selected in the picker.
public class UsuarioModel
{
public int CodUsuario { get; set; }
public string Nome { get; set; }
public string Senha { get; set; }
public int Telefone { get; set; }
public DateTime DataRegisto { get; set; }
public bool Estado { get; set; }
public int CodPerfil { get; set; }
}
PerfilModel Class
public class PerfilModel
{
public int CodPerfil { get; set; }
public string Titulo { get; set; }
}
Web API Controller to Insert Data
public IHttpActionResult Registo(UsuarioModel usuario)
{
connection();
SqlCommand cmd = new SqlCommand("SpAddNewUser", conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#Nome", usuario.Nome);
cmd.Parameters.AddWithValue("#Senha", usuario.Senha);
cmd.Parameters.AddWithValue("#Telefone", usuario.Telefone);
cmd.Parameters.AddWithValue("#CodPerfil", usuario.CodPerfil);
conn.Open();
cmd.ExecuteNonQuery();
return Ok();
}
Web API Controller to Get Data for Picker in Xamarin
public IEnumerable<PerfilModel> GetPerfisApp()
{
List<PerfilModel> perfilModels = new List<PerfilModel>();
connection();
SqlCommand cmd = new SqlCommand("SpGetPerfilApp", conn);
cmd.CommandType = CommandType.StoredProcedure;
conn.Open();
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
PerfilModel perfil = new PerfilModel();
perfil.CodPerfil = Convert.ToInt32(reader["CodPerfil"]);
perfil.Titulo = reader["Titulo"].ToString();
perfilModels.Add(perfil);
}
conn.Close();
return perfilModels;
}
ViewModel Class
public class AddRegistoUsuarioViewModel : BaseViewModel
{
ApiServices _apiServices = new ApiServices();
string _nome;
public string Nome
{
get
{
return _nome;
}
set
{
if (value != null)
{
_nome = value;
OnPropertyChanged();
}
}
}
string _senha;
public string Senha
{
get
{
return _senha;
}
set
{
if (value != null)
{
_senha = value;
OnPropertyChanged();
}
}
}
int _telefone;
public int Telefone
{
get
{
return _telefone;
}
set
{
_telefone = value;
OnPropertyChanged();
}
}
int _codperfil;
public int CodPerfil
{
get
{
return _codperfil;
}
set
{
_codperfil = value;
OnPropertyChanged();
}
}
public string Message { get; set; }
public ICommand Registar
{
get
{
return new Command(async () =>
{
var usuario = new UsuarioModel
{
Nome = Nome,
Senha = Senha,
Telefone = Telefone,
CodPerfil = SelectedPerfil.CodPerfil
};
await _apiServices.RegistoUsuarioAsync(usuario);
});
}
}
public AddRegistoUsuarioViewModel()
{
GetPerfisApp();
}
public async void GetPerfisApp()
{
using (var client = new HttpClient())
{
var uri = "https://webapiigarbage-ff4.conveyor.cloud/api/Usuario/PerfisApp";
var result = await client.GetStringAsync(uri);
var PerfilList = JsonConvert.DeserializeObject<List<PerfilModel>>(result);
Perfis = new ObservableCollection<PerfilModel>(PerfilList);
}
}
PerfilModel _selectedPerfil;
public PerfilModel SelectedPerfil
{
get
{
return _selectedPerfil;
}
set
{
if (SelectedPerfil != value)
{
_selectedPerfil = value;
OnPropertyChanged();
}
}
}
ObservableCollection<PerfilModel> _perfis;
public ObservableCollection<PerfilModel> Perfis
{
get
{
return _perfis;
}
set
{
_perfis = value;
OnPropertyChanged();
}
}
}
API Service Class
I tried to use this form: CodPerfil = SelectedPerfil.CodPerfil
But I was not successful.
public async Task RegistoUsuarioAsync(UsuarioModel usuario)
{
var client = new HttpClient();
var json = JsonConvert.SerializeObject(usuario);
HttpContent content = new StringContent(json);
content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
var response = await client.PostAsync("https://mywebsite/api/Usuario/Registo", content);
}
RegisterPage.xaml.cs
public RegisterPage()
{
InitializeComponent();
BindingContext = new RegistoUsuarioViewModel();
}
RegisterPage.xaml
<Entry Placeholder="Nome de Usuário"
x:Name="NomeEntry" />
<Picker x:Name="PerfilPicker" Title="Selecione o seu Perfil" FontSize="Large" HorizontalOptions="Center"
ItemsSource="{Binding Perfis}"
ItemDisplayBinding="{Binding Titulo}"
SelectedItem="{Binding SelectedPerfil}" />
<Entry Placeholder="Número de Telemóvel"
x:Name="TelefoneEntry"
Keyboard="Telephone"/>
<Entry Placeholder="Senha" x:Name="SenhaEntry" IsPassword="True"/>
<Button Text="Registar"
TextColor="White"
BackgroundColor="#07E3B0"
x:Name="ButtonLogin"
Command="{Binding Registar}"/>
I would be grateful if someone could help me.
thanks for the tips. what happened was that the viewmodel that was being binded in the Register.xaml.cs class was not the one that contained the Register command. I solve the 'problem' by replacing the viewmodel and it worked!
RegisterPage.xaml.cs
public RegisterPage()
{
InitializeComponent();
BindingContext = new AddRegistoUsuarioViewModel();
}

Parsing Pipe delimited file and Storing data into DB using Spring/Java

I have a pipe delimited file (excel xlsx) that I need to parse for certain data. the data is all in column A. the first row has the date, the last row has the row count, and everything in between is the row data. I want to take the first three fields of each row and the date from the header and store it into my H2 Table. There is extra data in my file in each row. I Need help creating code that will parse the file and insert it into my db. I have a Entity and some code written but am stuck now.
My file
20200310|
Mn1223|w01192|windows|extra|extra|extra||
Sd1223|w02390|linux|extra|extra|extra||
2
My table
DROP TABLE IF EXISTS Xy_load ;
CREATE TABLE Xy_load (
account_name VARCHAR(250) NOT NULL,
command_name VARCHAR(250) NOT NULL,
system_name VARCHAR (250) NOT NULL,
CREATE_DT date (8) DEFAULT NULL
);
entity class
public class ZyEntity {
#Column(name="account_name")
private String accountName;
#Column(name="command_name")
private String commandName;
#Column(name="system_name")
private String systemName;
#Column(name="CREATE_DT")
private int createDt;
public ZyEntity(String accountName, String commandName, String systemName){
this.accountName=accountName;
this.commandName=commandName;
this.systemName=systemName;
}
public String getAccountName() {
return accountName;
}
public void setAccountName(String accountName) {
this.accountName = accountName;
}
public String getCommandName() {
return commandName;
}
public void setCommandName(String commandName) {
this.commandName = commandName;
}
public String getSystemName() {
return systemName;
}
public void setSystemName(String systemName) {
this.systemName = systemName;
}
public int getCreateDt() {
return createDt;
}
public void setCreateDt(int createDt) {
this.createDt = createDt;
}
}
i was able to figure it out with some help
List<DataToInsert> parseData(String filePath) throws IOException {
List<String> lines = Files.readAllLines(Paths.get(filePath));
// remove date and amount
lines.remove(0);
lines.remove(lines.size() - 1);
return lines.stream()
.map(s -> s.split("[|]")).map(val -> new DataToInsert(val[0], val[1], val[2])).collect(Collectors.toList());
}
public void insertZyData(List<ZyEntity> parseData) {
String sql = "INSERT INTO Landing.load (account_name,command_name,system_name)"+
"VALUES (:account_name,:command_name,:system_name)";
for (ZyEntity zyInfo : parseData){
SqlParameterSource source = new MapSqlParameterSource("account_name", zInfo.getAccountName())
.addValue("command_name", zyInfo.getCommandName())
.addValue("system_name", zyInfo.getSystemName());
jdbcTemplate.update(sql, source);
}
}

Retrofit: Image Upload in POST #body

After hours goolging and trying different solutions I gave up and I'm asking for some direction, if possible some example. Here is the problem: I have a class that have a picture atribute. I'm using Retrofit and I want to send the Image as part of the Body of HTTP POST and I'm receiving a error. Bellow the code and the error.
Thank you in advance for your help.
The POJO Class:
public class Class1 {
#SerializedName("Picture")
private Bitmap mPicture;
#SerializedName("Giver")
public Integer mGiver;
public String getPicture() {
return mPicture;
}
public void setPicture (Bitmap picture) {
this.mPicture = picture;
}
public String getLaboratory() {
return mLaboratory;
}
public void setLaboratory(String laboratory) {
this.mLaboratory = laboratory;
}
The Activity:
mClass1.setPicture(mImageBitmap);
mClass1DAO.insertClass1(mClass1, new Callback<Integer>() {
#Override
public void success(Integer uid, Response response) {
mClass1.setUID(uid);
progressDialog.dismiss();
Toast.makeText(getApplicationContext(), R.string.msgThankYou, Toast.LENGTH_LONG).show();
dispatchNavigationDrawerActivity();
}
#Override
public void failure(RetrofitError error) {
progressDialog.dismiss();
showErrorDialog(error.getLocalizedMessage());
}
});
The API
#POST("/Service.svc/Insert")
void insert(#Body Class1 class1, Callback<Integer> cb);
The WebService in c#
[OperationContract]
[WebInvoke(Method = "POST", BodyStyle = WebMessageBodyStyle.Bare, RequestFormat = WebMessageFormat.Json,
ResponseFormat = WebMessageFormat.Json, UriTemplate = "InsertMedicineToDonate")]
Int32 insertMedicineToDonate(MedicineToDonate medicineToDonate);
//insertMedicineToDonate
public Int32 insertMedicineToDonate(MedicineToDonate medicineToDonate)
{
UserService mUserService = new UserService();
if (mUserService.isUserAuthorized())
{
return this.insertMedicineToDonateAuth(medicineToDonate);
}
else
{
errorDetail = new CustomHttpError(003);
throw new WebFaultException<CustomHttpError>(errorDetail, HttpStatusCode.Forbidden);
}
}
Web Service POJO Class
namespace DoarMed
{
[DataContract]
public class MedicineToDonate
{
[DataMember]
public Int32 UID { get; set; }
[DataMember]
public Bitmap Picture { get; set; }
THE ERROR
In the debug when I open the class and look at the attributes all of them are correct but the Picture is wrong.
See the Picture information bellow:
- Picture {System.Drawing.Bitmap} System.Drawing.Bitmap
+ Flags '((System.Drawing.Image)(medicineToDonate.Picture)).Flags' threw an exception of type 'System.ArgumentException' int {System.ArgumentException}
+ FrameDimensionsList '((System.Drawing.Image)(medicineToDonate.Picture)).FrameDimensionsList' threw an exception of type 'System.ArgumentException' System.Guid[] {System.ArgumentException}
+ Height '((System.Drawing.Image)(medicineToDonate.Picture)).Height' threw an exception of type 'System.ArgumentException' int {System.ArgumentException}
and so on
When I try to save the Picture to the DataBase the code throw System.ArgumentException
What am I missing here?
Thank you in advance
This is the solution, after 3 days trying. I hope it can save your time. if it does save your time, please give me +1.
Client Android
Class
public class MedicineToDonate {
#SerializedName("Picture")
private String mPicture;
#SerializedName("DateTimeInsert")
public Long mDateTimeInsert;
public Bitmap getPicture() {
return Global.convertStringToBitmap(mPicture);
}
public void setPicture(Bitmap picture) {
this.mPicture = Global.convertBitmapToString(picture);
}
Retrofit
mMedicineToDonateDAO.getGiverAllMedicineToDonate(mGlobal.getUserUID(), new Callback<List<MedicineToDonate>>() {
#Override
public void success(List<MedicineToDonate> mMedicineToDonateList, Response response) {
if (mMedicineToDonateList != null) {
for (int i = 1; i <= mMedicineToDonateList.size(); i++) {
mMedicineToDonate = mMedicineToDonateList.get(i - 1);
mAdapter.add(mMedicineToDonate);
}
}
progressDialog.dismiss();
Fragment mFragment = mFragmentManager.findFragmentByTag(Global.OPTION_DONATE);
FragmentTransaction ft = mFragmentManager.beginTransaction();
ft.detach(mFragment)
.attach(mFragment)
.commit();
mFragmentManager.executePendingTransactions();
}
#Override
public void failure(RetrofitError error) {
progressDialog.dismiss();
showErrorDialog(error.getLocalizedMessage());
}
});
Global
public static String convertBitmapToString(Bitmap imageBitmap){
ByteArrayOutputStream stream = new ByteArrayOutputStream();
if(imageBitmap != null) {
imageBitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
byte[] byteArray = stream.toByteArray();
return Base64.encodeToString(byteArray, Base64.URL_SAFE);
}else{
return null;
}
}
public static Bitmap convertStringToBitmap (String encodedString) {
try {
byte[] data = Base64.decode(encodedString, Base64.URL_SAFE);
return BitmapFactory.decodeByteArray(data, 0, data.length);
} catch(Exception e) {
e.getMessage();
return null;
}
}
Server Side (C#/IIS/Postgresql)
Class
[DataContract]
public class MedicineToDonate
{
[DataMember]
public string Picture { get; set; }
[DataMember]
public Int64 DateTimeInsert { get; set; }
[DataMember]
INSERT:
NpgsqlParameter addPictureParameter = new NpgsqlParameter("#" + Global.MEDICINETODONATE_COL_picture, NpgsqlDbType.Bytea);
byte[] byteArrayPicture = Global.convertStringToByteArray(medicineToDonate.Picture);
addPictureParameter.Value = byteArrayPicture;
SELECT:
byte [] pictureByteArray = (byte[]) reader[12];
mMedicineToDonate.Picture = Global.convertByteArrayToString(pictureByteArray);
Global
public static string convertByteArrayToString(byte[] bytes)
{
char[] chars = new char[bytes.Length / sizeof(char)];
System.Buffer.BlockCopy(bytes, 0, chars, 0, bytes.Length);
return new string(chars);
}

How to post image data from j2me to ASP.net MVC 3?

I'm making a j2me mobile application which can post images (as byte[]) and other simple data (strings, ints, floats, etc) on a ASP.net MVC 3 website. Currently the application and website are nearly done, except the part where the app can post the image data on the website.
Here is the datamodel I'd like to post to the website (j2me):
public class DataModel {
private String description = null;
private float latitude = 0;
private float longitude = 0;
private long timestamp = 0;
private String userName = null;
private byte[] imageData = null;
private String contentType = null;
// getters and setters...
}
This is the model my website expects (ASP.net MVC3 C#):
public class Model
{
public string Description { get; set; }
public float Latitude { get; set; }
public float Longitude { get; set; }
public long Timestamp { get; set; }
public string UserName { get; set; }
public byte[] Image { get; set; }
}
This is the (simplified) code I use to send the data (j2me):
InputStream in = null;
OutputStream out = null;
// url contains all the simple data
String encodedUrl = UrlEncoder.encodeUrl(url);
this.connection = (HttpConnection)Connector.open(encodedUrl);
byte[] imageData = DataModel.getImageData();
this.connection.setRequestMethod(HttpConnection.POST);
this.connection.setRequestProperty("Content-Length", imageData.length + "");
out = this.connection.openOutputStream();
out.write(imageData);
int responseCode = this.connection.getResponseCode();
if(responseCode != HttpConnection.HTTP_OK) {
throw new IOException("Transmission failed as server responded with response code: " + responseCode);
}
// process response here...
I've found some sollutions online for handling a post request from a j2me application which doens't do what I want and it's in VB. But maybe there's some useful code in there, which should be placed in the page-load event:
' the stream will be ASCII encoded'
Dim ascii As ASCIIEncoding = New ASCIIEncoding
'Get ASCII into reg. string here'
strmContent = ascii.GetString(strArr)
Label1.Text = strArr.ToString()
'write the received data to a text file'
Dim FILE_NAME As String = "C:\\NP\\received.txt"
Dim objWriter As New System.IO.StreamWriter(FILE_NAME, True)
objWriter.WriteLine(strmContent)
objWriter.WriteLine()
objWriter.Close()
I have no clue how I can receive the image data on my website. What code do I need to put in my Controller Action to be able to receive all the data? Do I need to change anything in my application code?
I'm splitting up the simple data from the image data. Is that even the right way to work here?
Thanks alot!
I am not an expert of j2me but you could simply make a multipart/form-data request as shown in this article which allows you to send files in addition to simple values in an HTTP request. So your code will look something along the lines of:
byte[] fileBytes = DataModel.getImageData();
Hashtable params = new Hashtable();
params.put("Description", "some description");
params.put("Latitude", "5");
params.put("Longitude", "6");
params.put("Timestamp", "123");
params.put("UserName", "john smith");
HttpMultipartRequest req = new HttpMultipartRequest(
"http://example.com/home/upload",
params,
"Image", "original_filename.png", "image/png", fileBytes
);
byte[] response = req.send();
Then on your ASP.NET MVC side your view model will simply look like this:
public class MyViewModel
{
public string Description { get; set; }
public float Latitude { get; set; }
public float Longitude { get; set; }
public long Timestamp { get; set; }
public string UserName { get; set; }
public HttpPostedFileBase Image { get; set; }
}
and your controller action:
[HttpPost]
public ActionResult Upload(MyViewModel model)
{
...
}
And here's the HttpMultipartRequest code (in case Nokia's site goes down):
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Enumeration;
import java.util.Hashtable;
import javax.microedition.io.Connector;
import javax.microedition.io.HttpConnection;
public class HttpMultipartRequest
{
static final String BOUNDARY = "----------V2ymHFg03ehbqgZCaKO6jy";
byte[] postBytes = null;
String url = null;
public HttpMultipartRequest(String url, Hashtable params, String fileField, String fileName, String fileType, byte[] fileBytes) throws Exception
{
this.url = url;
String boundary = getBoundaryString();
String boundaryMessage = getBoundaryMessage(boundary, params, fileField, fileName, fileType);
String endBoundary = "\r\n--" + boundary + "--\r\n";
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bos.write(boundaryMessage.getBytes());
bos.write(fileBytes);
bos.write(endBoundary.getBytes());
this.postBytes = bos.toByteArray();
bos.close();
}
String getBoundaryString()
{
return BOUNDARY;
}
String getBoundaryMessage(String boundary, Hashtable params, String fileField, String fileName, String fileType)
{
StringBuffer res = new StringBuffer("--").append(boundary).append("\r\n");
Enumeration keys = params.keys();
while(keys.hasMoreElements())
{
String key = (String)keys.nextElement();
String value = (String)params.get(key);
res.append("Content-Disposition: form-data; name=\"").append(key).append("\"\r\n")
.append("\r\n").append(value).append("\r\n")
.append("--").append(boundary).append("\r\n");
}
res.append("Content-Disposition: form-data; name=\"").append(fileField).append("\"; filename=\"").append(fileName).append("\"\r\n")
.append("Content-Type: ").append(fileType).append("\r\n\r\n");
return res.toString();
}
public byte[] send() throws Exception
{
HttpConnection hc = null;
InputStream is = null;
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] res = null;
try
{
hc = (HttpConnection) Connector.open(url);
hc.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + getBoundaryString());
hc.setRequestMethod(HttpConnection.POST);
OutputStream dout = hc.openOutputStream();
dout.write(postBytes);
dout.close();
int ch;
is = hc.openInputStream();
while ((ch = is.read()) != -1)
{
bos.write(ch);
}
res = bos.toByteArray();
}
catch(Exception e)
{
e.printStackTrace();
}
finally
{
try
{
if(bos != null)
bos.close();
if(is != null)
is.close();
if(hc != null)
hc.close();
}
catch(Exception e2)
{
e2.printStackTrace();
}
}
return res;
}
}

Resources