How to get Audio file through HTTP get? - java

I am trying to get an Audio file through http get from a secure restful service, I have successfully receive and parse text XML service but a bit confused that how to do with Audio file.
code to call the secure restful service with XML response
String callWebService(String serviceURL) {
// http get client
HttpClient client = getClient();
HttpGet getRequest = new HttpGet();
try {
// construct a URI object
getRequest.setURI(new URI(serviceURL));
} catch (URISyntaxException e) {
Log.e("URISyntaxException", e.toString());
}
// buffer reader to read the response
BufferedReader in = null;
// the service response
HttpResponse response = null;
try {
// execute the request
response = client.execute(getRequest);
} catch (ClientProtocolException e) {
Log.e("ClientProtocolException", e.toString());
} catch (IOException e) {
Log.e("IO exception", e.toString());
}
try {
in = new BufferedReader(new InputStreamReader(response.getEntity()
.getContent()));
} catch (IllegalStateException e) {
Log.e("IllegalStateException", e.toString());
} catch (IOException e) {
Log.e("IO exception", e.toString());
}
StringBuffer buff = new StringBuffer("");
String line = "";
try {
while ((line = in.readLine()) != null) {
buff.append(line);
}
} catch (IOException e) {
Log.e("IO exception", e.toString());
return e.getMessage();
}
try {
in.close();
} catch (IOException e) {
Log.e("IO exception", e.toString());
}
// response, need to be parsed
return buff.toString();
}

may this one help you..
public static void downloadFile(String fileURL, String fileName) {
try {
// fileURL=fileURL.replaceAll("amp;", "");
Log.e(fileURL, fileName);
String RootDir = Environment.getExternalStorageDirectory()
.toString();
File RootFile = new File(RootDir);
new File(RootDir + Commons.dataPath).mkdirs();
File file = new File(RootFile + Commons.dataPath + fileName);
if (file.exists()) {
file.delete();
}
file.createNewFile();
URL u = new URL(fileURL);
HttpURLConnection c = (HttpURLConnection) u.openConnection();
c.setRequestMethod("GET");
c.setDoOutput(true);
c.connect();
FileOutputStream f = new FileOutputStream(new File(
"mnt/sdcard"+Commons.dataPath + fileName));
InputStream in = c.getInputStream();
byte[] buffer = new byte[1024];
int len1 = 0;
while ((len1 = in.read(buffer)) > 0) {
f.write(buffer, 0, len1);
}
f.close();
} catch (Exception e) {
e.printStackTrace();
}
}

Related

Show data from Database Using HttURLConnection

I'm show data from database but is not work.
That is get me the Exception : FileNotFound but the path is well.
But when I put the URL from the browser it works normally
There is my code :
#Override
protected String doInBackground(String... parametro)
{
try
{
URL url = new URL(urlMostrarClientes);
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
InputStream inputStream = connection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
StringBuffer buffer = new StringBuffer();
String linha = "";
while ((linha = bufferedReader.readLine()) != null)
{
buffer.append(linha + "\n");
}
inputStream.close();
bufferedReader.close();
progressDialog.dismiss();
return buffer.toString().trim();
} catch (MalformedURLException e)
{
e.printStackTrace();
progressDialog.dismiss();
Log.v("vampiro","ERRO : " + e.toString());
} catch (ProtocolException e)
{
e.printStackTrace();
progressDialog.dismiss();
Log.v("vampiro","ERRO : " + e.toString());
} catch (IOException e) {
e.printStackTrace();
progressDialog.dismiss();
Log.v("vampiro","ERRO : " + e.toString());
}
return "ERRO";
}
Three ways of solving problem :
file:///yourFilePath
Paths.get(yourPath).toUri().toURL() //java nio way
File(“path_to_file”).toURI().toURL();
//java io way

SOAP Message as a String Sent to End Point in Java

I have a String which is a SOAP message.
String message = "<?xml version="1.0" encoding="UTF-8"?><SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/">
<SOAP-ENV:Header>
<xyz:Config xmlns:hal="http://example.com/xyz" applicationId="Client" conversationId="000" host="ENDPOINT">
</xyz:Config>
</SOAP-ENV:Header>
<SOAP-ENV:Body>
<PaymentRQ xmlns="http://www.iata.org/IATA/4/0"
xmlns:common="http://www.iata.org/IATA/common/4/0">
<PaymentDetails>
<PaymentDetail>
<common:PaymentCard CardNumber="1233444444444" CardType="100" ExpireDate="1120" SeriesCode="123">
</PaymentDetail>
</PaymentDetails>
</PaymentRQ>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>
";
I need to send this as a SOAP request to a local server running on 8080
So, url would be http://localhost:8080/XYZService/xyz
Then fetch the SOAP response and read its values.
Kindly assist on how I can send the String as a SOAP message to the aforementioned url. Thanks in advance.
You can pass null to SOAPAction if you don't have one.
for serverAddress pass serverIp + ServerPort(ex: 172...*:8088).
public String sendSoapRequest(String serverAdress, String message , String SOAPAction)
{
OutputStream httpOutputStream = null;
byte[] byteArrayStream = message .getBytes();
URL url = null;
try {
url = new URL("http://"+serverAdress);
} catch (MalformedURLException e) {
e.printStackTrace();
}
HttpURLConnection httpURLConnection = null;
try {
httpURLConnection = (HttpURLConnection)url.openConnection();
} catch (IOException e) {
e.printStackTrace();
}
// Set the appropriate HTTP parameters.
httpURLConnection.setRequestProperty("Content-Length",
String.valueOf(byteArrayStream.length));
httpURLConnection.setRequestProperty("Content-Type", "text/xml; charset=utf-8");
httpURLConnection.setRequestProperty("SOAPAction", SOAPAction);
try {
httpURLConnection.setRequestMethod("POST");
} catch (ProtocolException e) {
e.printStackTrace();
}
httpURLConnection.setDoOutput(true);
httpURLConnection.setDoInput(true);
try {
httpOutputStream = httpURLConnection.getOutputStream();
} catch (IOException e) {
e.printStackTrace();
}
//Write the content of the request to the outputstream of the HTTP Connection.
try {
httpOutputStream.write(byteArrayStream);
httpOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
BufferedReader httpInputBuufferedReader = null;
try {
httpInputBuufferedReader = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream()));
} catch (IOException e) {
e.printStackTrace();
Log.e(LOG_TAG,"IOException reading HTTP Input message ");
return null;
}
//Write the SOAP message response to a String.
StringBuilder returnOutputString = new StringBuilder();
try {
String line = "";
while ((line = httpInputBuufferedReader.readLine()) != null) {
returnOutputString.append(line);
}
} catch (IOException e) {
e.printStackTrace();
Log.e(LOG_TAG, "IOEception while reading HTTP input buffered reading");
}
return returnOutputString.toString();
}

Why isn't my node.js restful api recieving this output stream from Java Android?

I have a class audio sender which makes a connection to the nodejs server and uploads an audio file in POST method mode.
public class AudioSender implements Callable<JSONObject> {
String outputFile;
AudioSender(String fileLocation){
outputFile=fileLocation;
}
public JSONObject call(){
URL url = null;
HttpURLConnection urlConnection = null;
InputStream audioInputStream=null;
JSONObject response=null;
byte buffer[]=new byte[16];
try {
url = new URL("http://192.168.0.106:3000/upload");
} catch (MalformedURLException e) {
e.printStackTrace();
} finally {
try {
urlConnection = (HttpURLConnection) url.openConnection();
} catch (IOException e) {
e.printStackTrace();
} finally {
urlConnection.setDoOutput(true);
urlConnection.setChunkedStreamingMode(16);
urlConnection.setRequestProperty("Content-Type","multipart/form-data");
urlConnection.setRequestProperty("Connection", "Keep-Alive");
urlConnection.setRequestProperty("Cache-Control", "no-cache");
urlConnection.setRequestProperty(
"Content-Type", "multipart/form-data;boundary=*****");
try {
OutputStream out = new BufferedOutputStream(urlConnection.getOutputStream());
try {
audioInputStream = new BufferedInputStream(new FileInputStream(outputFile));
Log.d("hello","audioinputstream");
} catch (FileNotFoundException e) {
e.printStackTrace();
} finally {
while(audioInputStream.read(buffer)!=-1) {
out.write(buffer);
Log.d("buffer",buffer.toString());
}
try {
audioInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
StringBuilder total = new StringBuilder();
while(in.read(buffer)!=-1)
total.append(buffer);
Log.d("response",total.toString());
try {
response = new JSONObject(total.toString());
}catch(JSONException e){
Log.e("Response Parse Error", "Could not parse malformed JSON");
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
return response;
}
This is the upload that executes the AudioSender callable.
public void upload() {
JSONObject response=null;
AudioSender sender=new AudioSender(outputFile);
FutureTask<JSONObject> uploadTask=new FutureTask<JSONObject>(sender);
ExecutorService executorService= Executors.newFixedThreadPool(1);
executorService.execute(uploadTask);
Log.d("s","was here");
while(true){
if(uploadTask.isDone()){
try{
response=uploadTask.get();
}catch(InterruptedException|ExecutionException e){
e.printStackTrace();
Log.e("ee","ee",e.getCause());
}
}
}
}
I pretty much know this isn't node js's fault but here's the server code:
app.post('/upload',function(req,res){
console.log("someone called!");
req.on('data',function(chunk){
console.log('res');
console.log(chunk);
});
req.on('end',function(){
console.log("done!");
res.send({'name':'sg'});
});});
When I call upload(), the server console prints
someone called!
done!
I was debugging and found that indeed I am receiving the responded json object from the server. And I don't know if out.write(buffer) is doing the job, but debugging it shows that the buffer value is changing and is in par with my audio file's size.
Please do not suggest using ION or anything else.
I solved the problems by setting up the URLConnection as follows:
boundary = "===" + System.currentTimeMillis() + "===";
urlConnection.setUseCaches(false);
urlConnection.setDoOutput(true); // indicates POST method
urlConnection.setDoInput(true);
urlConnection.setRequestProperty("Content-Type","multipart/form-data; boundary=" + boundary);

How to get Java script variable from HTML using HttpClient

I need to get the js variable from HTML. I get html from server using HttpCLient, and try to search "src" in stringBuilder.
I want to get image URL shown on page.
Thml sting that i parsed.
How to get this variable?
< img id="h5" src="8.jpg" border="0">
#Override
protected String doInBackground(Void... params) {
HttpParams httpParameters = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParameters, 30 * 1000);
HttpConnectionParams.setSoTimeout(httpParameters, 30 * 1000);
httpclient = new DefaultHttpClient(httpParameters);
httpGet = new HttpGet(url);
httpGet.setHeader("Accept-Encoding", "gzip");
//Запрос
HttpResponse response = null;
try {
response = httpclient.execute(httpGet);
} catch (IOException e) {
e.printStackTrace();
}
InputStream instream = null;
try {
instream = response.getEntity().getContent();
} catch (IOException e) {
e.printStackTrace();
}
Header contentEncoding = response.getFirstHeader("Content-Encoding");
if ((contentEncoding != null) && contentEncoding.getValue().equalsIgnoreCase("gzip")) {
try {
instream = new GZIPInputStream(instream);
} catch (IOException e) {
e.printStackTrace();
}
}
BufferedReader reader = null;
try {
reader = new BufferedReader(new InputStreamReader(instream, "utf-8"), 8);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
StringBuilder sb = new StringBuilder();
String line;
try {
while ((line = reader.readLine()) != null) {
if (line.contains("\" src"))
{
sb.append(line).append("\n");
}}
} catch (IOException e) {
e.printStackTrace();
}
try {
instream.close();
} catch (IOException e) {
e.printStackTrace();
}
String result = sb.toString();
Log.i("Do id back", " ");
return result;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
txtUrl.setText(result.toString());
Log.i("on Post"," ");
}
}
You can use an HTML parser, e.g. jsoup.

How to send httpRequest to server with GZIP DATA

I have a json file that I am sending to the server as a POST but it has to be gzipped
I dont know how to do it
I found the potential solution here GZip POST request with HTTPClient in Java
but I dont know how to merge the methodology they used in the second part of the answer with my makeHttpRequest method (they are using a multipart entity and Im using a urlencoded entity)
EDIT: Here is how I get jsonAsBytes
public static byte[] stringToGZIPByteArray (String string) {
Log.d("string to be gzipped", string);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
GZIPOutputStream gzos = null;
try {
gzos = new GZIPOutputStream(baos);
gzos.write(string.getBytes("UTF-8"));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (gzos != null) {
try {
gzos.close();
} catch (IOException ignore) {
};
}
}
return baos.toByteArray();
} // End of stringToGZIPByteArray
This is where I use that method
jsonParser.sendGzippedJSONviaHTTP(context, API.JSON_ACCEPT, UtilityClass.stringToGZIPByteArray(jsonObject.toString()), context.getResources());
and this is sendGzippedJSONviaHTTP
public JSONObject sendGzippedJSONviaHTTP(Context context, String url, byte[] gzippedJSON, Resources res) {
if (httpClient == null) {
try {
httpClient = new HttpClientBuilder().setConnectionTimeout(10000)
.setSocketTimeout(60000) //
.setHttpPort(80)//
.setHttpsPort(443)//
.setCookieStore(new BasicCookieStore())//
.pinCertificates(res, R.raw.keystore, null) //
.build();
} catch (CertificateException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (KeyStoreException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
// Making HTTP request
try {
// request method is POST
// defaultHttpClient
HttpPost httpPost = new HttpPost(url);
httpPost.setHeader("Content-Encoding", "gzip");
httpPost.setHeader("Content-Type", "application/json");
httpPost.setEntity(AndroidHttpClient.getCompressedEntity(gzippedJSON, context.getContentResolver()));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
inputStream = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
inputStream.close();
reader.close();
json = sb.toString();
} catch (ClientProtocolException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
// try parse the string to a JSON object
try {
jsonObject = new JSONObject(json);
} catch (JSONException e) {
e.printStackTrace();
}
// return JSON String
return jsonObject;
} // End of makeHttpRequest
Take a look at AndroidHttpClient. You can use it instead of appache's DefaultHttpClient. It has a static method getCompressedEntity(byte[] data, ContentResolver resolver)
So, you can write:
HttpPost httpPost = new HttpPost(url);
post.setEntity( AndroidHttpClient.getCompressedEntity( jsonAsBytes, null ) );
httpClient.execute(httpPost);
UPDATE:
this is the code from AndroidHttpClient:
public static AbstractHttpEntity getCompressedEntity(byte data[], ContentResolver resolver)
throws IOException {
AbstractHttpEntity entity;
if (data.length < getMinGzipSize(resolver)) {
entity = new ByteArrayEntity(data);
} else {
ByteArrayOutputStream arr = new ByteArrayOutputStream();
OutputStream zipper = new GZIPOutputStream(arr);
zipper.write(data);
zipper.close();
entity = new ByteArrayEntity(arr.toByteArray());
entity.setContentEncoding("gzip");
}
return entity;
}
should give you some insights

Categories