Android: Send a file as an array of bytes using HttpURLConnection - android

I want to send a file via a POST HTTP request but can't find how to handle it first...
I would do this with a string parameter:
String html_params = "myparam=myparam";
byte[] outputInBytes = html_params.getBytes("UTF-8");
URL url = new URL("http://www.myurl.com/senddata.asp");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Accept", "text/html");
OutputStream os = conn.getOutputStream();
os.write(outputInBytes);
os.close();
response = conn.getResponseCode();
However I have no idea of how to transform and send a file as an array of bytes instead of a string...
Thanks for your help

Related

Send a "zip" file from an Android device to web service Rest

Client :
URL url =new URL("http://xxx.xxx.x.xx:8080/wre/zipFile"); // LocalHost
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-type", "application/zip");
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setConnectTimeout(50000);
BufferedOutputStream sout = new BufferedOutputStream(conn.getOutputStream());
FileInputStream bis = new FileInputStream(zipfile);
int i;
byte bytes[]=new byte[4096];
while((i=bis.read(bytes))!=-1){
sout.write(bytes,0,i);
sout.flush();}
sout.close();
bis.close();
is correct code ?
Server:
what is the server side code?
i.e. download the zip file (d: / zipFile /) and then send to the client by mail
thanks.

Connection Failiure when trying to upload an image file

I am trying to upload an image by converting it to a string buffer to a server. But I always get the mentioned error exception when connecting.
isConnected failed: EHOSTUNREACH (No route to host)
Above is the exception I am getting
This is the code I have used to upload image
jsonSendData = new JSONObject();
jsonSendData.put("data", sendData);
URL url = new URL(getFieldTCTEnableStr("URL"));
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
//method
conn.setRequestMethod("POST");
//header
conn.setRequestProperty("Content-Type", "application/json");
OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream());
out.write(jsonSendData.toString());
out.flush();
out.close();
conn.disconnect();

rest data getting cached android

I am using the code below to fetch data from server. When the data is updated on server, I get the old data from this method. When I use the same method in the web browser i get updated data.
Even when I stop the app and start again it reflects old data but when I have cleaned all my tasks using task manager, I get new data.
Is the data being cached on the device as i am making new request each time
String response = null;
InputStream inputStream = null;
HttpURLConnection urlConnection = null;
try {
URL url = new URL(urlString);
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setReadTimeout(10000);
urlConnection.setConnectTimeout(15000);
if (method == POST) {
urlConnection.setDoInput(true);
urlConnection.setDoOutput(true);
urlConnection.setRequestProperty("Accept", "application/json");
urlConnection.setRequestMethod("POST");
OutputStream os = urlConnection.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
writer.write(params);
writer.flush();
writer.close();
os.close();
} else {
urlConnection.setRequestMethod("GET");
}
int statusCode = urlConnection.getResponseCode();
/* 200 represents HTTP OK */
if (statusCode == HttpURLConnection.HTTP_OK) {
inputStream = new BufferedInputStream(urlConnection.getInputStream());
response = convertInputStreamToString(inputStream);
return response;
}
I searched the web and found that use cache is on by default, so these two line might help
urlConnection.setUseCaches(false);
urlConnection.addRequestProperty("Cache-Control", "no-cache");
Append some random parameter i.e. current timestamp to the URL then it will treat as fresh request.
Change This
URL url = new URL(urlString);
To
URL url = new URL(urlString+new Date().getTime());

How to make POST call using HttpURLConnection with JSON data in Android

please help me out with this problem.
I want to make a POST call with JSON data that should appear in body to request but i am not able to do that. I made POST call and getting data but data is not in JSON format.
Code :
data = "{'mobile':'"+mobile_number+"','password':'"+mypassword+"'}";
byte[] dataPost = data.getBytes();
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setDoOutput(true);
urlConnection.setChunkedStreamingMode(0);
urlConnection.setInstanceFollowRedirects(false);
urlConnection.setRequestProperty("Accept", "application/json");
//urlConnection.setRequestProperty("Content-Type", "application/json");
urlConnection.setRequestProperty("charset", "UTF8");
urlConnection.setUseCaches(false);
OutputStream os = urlConnection.getOutputStream();
os.write(dataPost);
os.close();
Result is coming like below
body:
{'a':'b','c':'d'}:""
Please Help me. i am new to android Development.
Thanks

Android HTTPUrlConnection : how to set post data in http body?

I've already created my HTTPUrlConnection :
String postData = "x=val1&y=val2";
URL url = new URL(strURL);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setRequestProperty("Set-Cookie", sessionCookie);
conn.setRequestProperty("Content-Length", "" + Integer.toString(postData.getBytes().length));
// How to add postData as http body?
conn.setUseCaches(false);
conn.setDoInput(true);
conn.setDoOutput(true);
I don't know how to set postData in http body. How to do so? Would I better use HttpPost instead?
Thanks for your help.
If you want to send String only try this way:
String str = "some string goes here";
byte[] outputInBytes = str.getBytes("UTF-8");
OutputStream os = conn.getOutputStream();
os.write( outputInBytes );
os.close();
But if you want to send as Json change Content type to:
conn.setRequestProperty("Content-Type","application/json");
and now our str we can write:
String str = "{\"x\": \"val1\",\"y\":\"val2\"}";
Hope it will help,
Guruparan's link in the comment above gives a really nice answer to this question. I highly recommend looking at it. Here is the principle that makes his solution work:
From what I understand, the HttpURLConnection represents the response body as an OutputStream. So you need to call something like:
get the connection's output stream
OutputStream op = conn.getOuputStream();
write the response body
op.write( [/*your string in bit form*/] );
close the output stream
op.close();
and then carry on your merry way with the connection (which you will still need to close).

Categories

Resources