is it possible to use range header in HTTP with HTTP GET request?
if yes than how?
I just want to download bytes from server with specified bytes.
i.e if I want to download bytes from 0 to 255.
See this sample code,
HttpConnection connection = null;
InputStream inputstream = null;
try
{
connection = (HttpConnection) Connector.open(url); // Enter your URL here.
//HTTP Request
connection.setRequestMethod(HttpConnection.GET);
connection.setRequestProperty("Content-Type","//text plain");
connection.setRequestProperty("Connection", "close");
// HTTP Response
System.out.println("Status Line Code: " + connection.getResponseCode());
System.out.println("Status Line Message: " + connection.getResponseMessage());
if (connection.getResponseCode() == HttpConnection.HTTP_OK)
{
System.out.println(
connection.getHeaderField(0)+ " " + connection.getHeaderFieldKey(0));
System.out.println(
"Header Field Date: " + connection.getHeaderField("date"));
String str;
inputstream = connection.openInputStream();
int length = (int) connection.getLength();
if (length != -1)
{
byte incomingData[] = new byte[length];
inputstream.read(incomingData);
str = new String(incomingData);
}
else
{
ByteArrayOutputStream bytestream =
new ByteArrayOutputStream();
int ch;
while ((ch = inputstream.read()) != -1)
{
bytestream.write(ch);
}
str = new String(bytestream.toByteArray());
bytestream.close();
}
System.out.println(str);
}
}
catch(IOException error)
{
System.out.println("Caught IOException: " + error.toString());
}
finally
{
if (inputstream!= null)
{
try
{
inputstream.close();
}
catch( Exception error)
{
/*log error*/
}
}
if (connection != null)
{
try
{
connection.close();
}
catch( Exception error)
{
/*log error*/
}
You could try this:
HttpConnection httpConnection = (HttpConnection) Connector.open("http://www.server.com/file");
httpConnection.setRequestMethod(HttpConnection.GET);
httpConnection.setRequestProperty("Range","0-255");
Check the docs out: HttpConnection
Related
I'm making a Java application, and need the user to be able to upload a file to a server through PHP. The problem is that when the user uploads the file, the PHP script doesn't seem to "catch" the file.
This is the code I have so far.
PHP:
<?php
$target_path = "uploads/";
$target_path = $target_path . basename($_FILES['uploadedfile']['name']);
if (move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path)) {
echo "1";
exit();
}
echo "0";
?>
Java:
String filename = "C:\Users\XXX\Pictures\Capture.PNG";
public void uploadFile() {
text = "";
String CrLf = "\r\n";
String filename = filepath.split("/")[filepath.split("/").length-1];
URLConnection conn = null;
OutputStream os = null;
InputStream is = null;
try {
URL con = new URL(connection);
conn = con.openConnection();
conn.setDoOutput(true);
InputStream imgIS = new FileInputStream(filepath);
byte[] imgData = new byte[imgIS.available()];
imgIS.read(imgData);
String message1 = "";
message1 += "-----------------------------4664151417711" + CrLf;
message1 += "Content-Disposition: form-data; name=\"uploadedfile\"; filename=\"Image0001.png\""
+ CrLf;
message1 += "Content-Type: image/png" + CrLf;
message1 += CrLf;
// the image is sent between the messages in the multipart message.
String message2 = "";
message2 += CrLf + "-----------------------------4664151417711--"
+ CrLf;
conn.setRequestProperty("Content-Type",
"multipart/form-data; boundary=---------------------------4664151417711");
// might not need to specify the content-length when sending chunked
// data.
conn.setRequestProperty("Content-Length", String.valueOf((message1
.length() + message2.length() + imgData.length)));
System.out.println("open os");
os = conn.getOutputStream();
System.out.println(message1);
os.write(message1.getBytes());
// SEND THE IMAGE
int index = 0;
int size = 1024;
do {
System.out.println("write:" + index);
if ((index + size) > imgData.length) {
size = imgData.length - index;
}
os.write(imgData, index, size);
index += size;
} while (index < imgData.length);
System.out.println("written:" + index);
System.out.println(message2);
os.write(message2.getBytes());
os.flush();
System.out.println("open is");
is = conn.getInputStream();
char buff = 512;
int len;
byte[] data = new byte[buff];
do {
System.out.println("READ");
len = is.read(data);
if (len > 0) {
System.out.println(new String(data, 0, len));
}
} while (len > 0);
System.out.println("DONE");
} catch (Exception e) {
e.printStackTrace();
} finally {
System.out.println("Close connection");
try {
os.close();
} catch (Exception e) {
}
try {
is.close();
} catch (Exception e) {
}
try {
} catch (Exception e) {
}
}
}
When getting the output from the PHP script, it always returns a "0".
I've tried a lot of different things, but nothing seems to work.
I am saving a file to disk after downloading it from server, but I believe it gets corrupted while saving on the disc. If the same file is downloaded using chrome on mac or using any other method, the file downloads and reads normally. The corruption seems to be in the saving process of the file. I am adding the code to help find out the problem. The file is a css file.
Corruption:
Some whitespace sort of characters appear when reading the file. A surprising thing that I tried and noticed is that if I reduce the BUFFER_SIZE to 32 from 4096, the file does not get corrupt, I couldn't figure out why. Also, reducing BUFFER_SIZE reduces whitespaces / corrupted characters.
Appreciate any pointers in the right direction. Thanks
private static final int BUFFER_SIZE = 4096;
// saves file to disk and returns the contents of the file.
public static String downloadFile(Context context, String filePath, String destParent) {
String content = null;
StringBuilder sb = new StringBuilder();
HttpURLConnection connection = null;
InputStream is = null;
FileOutputStream os = null;
String sUrl = Urls.makeWebAssetUrl(filePath); /// consider this my file URL
String destFile = getContextBaseDir(context) + (destParent != null ? File.separator + destParent : "") + File.separator + filePath;
try {
URL url = new URL(sUrl);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
int responseCode = connection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
File outFile = new File(destFile);
if (!outFile.getParentFile().exists()) {
if (!outFile.getParentFile().mkdirs()) {
throw new RuntimeException("Unable to create parent directories for " + filePath);
}
}
is = connection.getInputStream();
os = new FileOutputStream(outFile);
int bytesRead = 0;
byte[] buffer = new byte[BUFFER_SIZE];
while ((bytesRead = is.read(buffer)) != -1) {
sb.append(new String(buffer, 0, bytesRead, DEFAULT_ENCODING));
os.write(buffer);
}
content = sb.toString();
}
else {
LogUtils.LOGW(TAG, responseCode + " while connecting to " + sUrl + ": " + connection.getResponseMessage());
}
} catch(Exception e) {
LogUtils.LOGE(TAG, "Error while downloading " + sUrl, e);
} finally {
if (is != null) {
try {
is.close();
} catch (IOException e) {
LogUtils.LOGE(TAG, "Error closing inputStream while downloading " + sUrl, e);
}
}
if (os != null) {
try {
os.flush();
} catch (IOException e) {
LogUtils.LOGE(TAG, "Error flushing outputStream while downloading " + sUrl, e);
}
try {
os.close();
} catch (IOException e) {
LogUtils.LOGE(TAG, "Error closing outputStream while downloading " + sUrl, e);
}
}
}
return content;
}
os.write(buffer);
The problem is here. It should be:
os.write(buffer, 0, bytesRead);
I don't know why you are also accumulating the content in a StringBuffer and returning it as a String. That won't scale, and in any cast it's redundant. Remove.
I am trying to serve an mp3 using HttpHandler and getting a broken pipe. It works with Google Chrome on my mac and my iPad but Android cause the HttpHander to just hang after getting the IOException and I have to restart. Using very simple code and works fine with images and html.
try {
String requestURI = t.getRequestURI().toString().substring(1);
if(requestURI.equals("") || requestURI.equals("/"))
requestURI = "index.htm";
requestURI = requestURI.replaceAll("%20", " ");
if(requestURI.contains("mp3")) {
urlToResource = new File(System.getProperty("user.home") + "/test/" +
requestURI).toURI().toURL();
}
System.out.println("Modified requestURI:" + requestURI);
if(requestURI.contains("mp3")) {
sContentType = "audio/mpeg";
} else if(requestURI.contains("png")) {
sContentType = "image/png";
} else if(requestURI.contains("jpg")) {
sContentType = "image/jpg";
} else if(requestURI.contains("favicon.ico")) {
sContentType = "content/unknown";
} else if(requestURI.contains("css")) {
sContentType = "text/css";
} else {
sContentType = "text/html";
}
if(!requestURI.contains("mp3")) {
urlToResource = new File("src/com/daford/web/" + requestURI).toURI().toURL();
}
if(urlToResource != null) {
conn = urlToResource.openConnection();
int size = conn.getContentLength();
System.out.println("file " + requestURI + " size is:" + size);
inConnectionReader = conn.getInputStream();
headers = t.getResponseHeaders();
headers.add("Content-Type", sContentType);
t.sendResponseHeaders(200, size);
os = t.getResponseBody();
int iReadByte = inConnectionReader.read();
while (iReadByte != -1) {
os.write(iReadByte);
iReadByte = inConnectionReader.read();
}
} else {
headers = t.getResponseHeaders();
headers.add("Content-Type", "text/html");
String sErrorMessage = "Error getting webpage.";
t.sendResponseHeaders(404, sErrorMessage.length());
os = t.getResponseBody();
os.write(sErrorMessage.getBytes());
}
if(os != null) {
os.close();
}
} catch (Exception e) {
e.printStackTrace();
}
I am sending json object to azure cloud in java successfully.but the problem is my reciever,the message is recieved well but the problem is when i want to send it back to PHP:
I am sending this message:
{"Id":"914897","Name":"Broken window","Description":"Window
broken","PriorityId":"1"}
As I receive this message I want to first printout the message to verify whether i am getting the results and i sent it.however inside the while loop is printing correct but outside a broken results here is my Code:
try {
Configuration config
= ServiceBusConfiguration.configureWithSASAuthentication(
);
ServiceBusContract service = ServiceBusService.create(config);
ReceiveMessageOptions opts = ReceiveMessageOptions.DEFAULT;
opts.setReceiveMode(ReceiveMode.PEEK_LOCK);
//send object
HttpClient httpClient = new DefaultHttpClient();
Gson gson= new Gson();
while (true) {
ReceiveQueueMessageResult resultQM = service.receiveQueueMessage("mobile",opts);
BrokeredMessage message = resultQM.getValue();
if (message != null && message.getMessageId() != null) {
System.out.println("MessageID: " + message.getMessageId());
// Display the queue message.
System.out.print("From queue:");
byte[] b = new byte[20000000];
String message_from_queue = null;
String thu =null;
String jsonn = null;
int numRead = message.getBody().read(b);
while (-1 != numRead) {
message_from_queue = new String(b);
message_from_queue = message_from_queue .trim();
numRead = message.getBody().read(b);
//System.out.print("inside while" +message_from_queue + **"\n");//{"Id":"914897","Name":"Broken window","Description":"Window broken","PriorityId":"1"}**
try {
HttpPost request = new HttpPost("http://localhost:3308/emlive/index.php/Api/createDefect");
StringEntity params =new StringEntity("defect=" + message_from_queue );
request.addHeader("content-type", "application/x-www-form-urlencoded");
request.addHeader("Accept","application/json");
request.setEntity(params);
HttpResponse response = httpClient.execute(request);
//System.out.printf("---------------------------------Done-------------------------------");
// handle response here...
message.setSessionId("");
System.out.println(org.apache.http.util.EntityUtils.toString(response.getEntity()));
org.apache.http.util.EntityUtils.consume(response.getEntity());
}
catch (Exception ex) {
// handle exception here
} finally {
httpClient.getConnectionManager().shutdown();
}
}
//System.out.print("outside while" +message_from_queue + "\n");//Broken window","Description":"Window broken","PriorityId":"1"}
System.out.println();
System.out.println("Custom Property: "
+ message.getProperty("MyProperty"));
//service.deleteMessage(message);
System.out.println("Deleting this message.");
//service.deleteMessage(message);
} else {
System.out.println("Finishing up - no more messages.");
break;
// Added to handle no more messages.
// Could instead wait for more messages to be added.
}
}
} catch (ServiceException e) {
System.out.print("ServiceException encountered: ");
System.out.println(e.getMessage());
System.exit(-1);
} catch (Exception e) {
System.out.print("Generic exception encountered: ");
System.out.println(e.getMessage());
System.exit(-1);
}
I am getting this results : Printing inside while loop:
while (-1 != numRead) {
message_from_queue = new String(b);
message_from_queue = message_from_queue .trim();
numRead = message.getBody().read(b);
System.out.print("inside while" +message_from_queue + **"\n");//{"Id":"914897","Name":"Broken window","Description":"Window broken","PriorityId":"1"}**
}
Printing outside while loop:
System.out.print("outside while" +message_from_queue + "\n");/*Broken window","Description":"Window broken","PriorityId":"1"}
All Thanks to Dominic Betts from this link https://azure.microsoft.com/en-us/documentation/articles/service-bus-java-how-to-use-queues/#comments
I used the following code to achieve my goal:
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append(message_from_queue );
I think the issue was caused by doing the POST request in the inside while loop. Codes in the inside while loop is for reading messages from queue, So the POST request of HttpClient should be in the outside while loop.
I refered to the doc https://azure.microsoft.com/en-us/documentation/articles/service-bus-java-how-to-use-queues/ and modified your code as below:
try {
Configuration config = ServiceBusConfiguration.configureWithSASAuthentication("<namespace>", "<sas_key_name>",
"<sas_key>", ".servicebus.windows.net");
ServiceBusContract service = ServiceBusService.create(config);
ReceiveMessageOptions opts = ReceiveMessageOptions.DEFAULT;
opts.setReceiveMode(ReceiveMode.PEEK_LOCK);
// send object
// HttpClient httpClient = new DefaultHttpClient();
CloseableHttpClient httpClient = HttpClients.createDefault();
// Gson gson = new Gson();
while (true) {
ReceiveQueueMessageResult resultQM = service.receiveQueueMessage("mobile", opts);
BrokeredMessage message = resultQM.getValue();
if (message != null && message.getMessageId() != null) {
System.out.println("MessageID: " + message.getMessageId());
// Display the queue message.
System.out.print("From queue:");
byte[] b = new byte[20000000];
String message_from_queue = null;
// String thu = null;
// String jsonn = null;
int numRead = message.getBody().read(b);
while (-1 != numRead) {
message_from_queue = new String(b);
message_from_queue = message_from_queue.trim();
numRead = message.getBody().read(b);
// System.out.print("inside while" +message_from_queue +
// **"\n");//{"Id":"914897","Name":"Broken
// window","Description":"Window
// broken","PriorityId":"1"}**
}
// System.out.print("outside while" +message_from_queue +
// "\n");//Broken window","Description":"Window
// broken","PriorityId":"1"}
int statusCode = -1;
try {
HttpPost request = new HttpPost("http://localhost:3308/emlive/index.php/Api/createDefect");
StringEntity params = new StringEntity("defect=" + message_from_queue);
request.addHeader("content-type", "application/x-www-form-urlencoded");
request.addHeader("Accept", "application/json");
request.setEntity(params);
HttpResponse response = httpClient.execute(request);
// System.out.printf("---------------------------------Done-------------------------------");
// handle response here...
message.setSessionId("");
System.out.println(EntityUtils.toString(response.getEntity()));
EntityUtils.consume(response.getEntity());
} catch (Exception ex) {
// handle exception here
} finally {
httpClient.close();
}
System.out.println();
System.out.println("Custom Property: " + message.getProperty("MyProperty"));
if (statusCode == 200) {
// Remove message from queue.
System.out.println("Deleting this message.");
service.deleteMessage(message);
}
} else {
System.out.println("Finishing up - no more messages.");
break;
// Added to handle no more messages.
// Could instead wait for more messages to be added.
}
}
} catch (ServiceException e) {
System.out.print("ServiceException encountered: ");
System.out.println(e.getMessage());
System.exit(-1);
} catch (Exception e) {
System.out.print("Generic exception encountered: ");
System.out.println(e.getMessage());
System.exit(-1);
}
Best Regards
I want to send sms which contain arabic message using java API
mobily provider offers a java api to send sms
I used this code java :
public void sendMessage(String userName,String password,String sender,String message,String numbers){
String para ="mobile=" + userName + "&password=" + password + "&numbers=" + numbers+ "&sender=" + sender + "&msg=" + convertUnicode(message) + "&applicationType=24";
sendURL("http://www.mobily.ws/api/msgSend.php",para,1);
System.out.println(getMessage());
}
public static String convertUnicode(String a) {
int bufSize = 16;
byte[] buffer = new byte[bufSize];
String s = null;
try {
buffer=a.getBytes();
s = bytesToHex(buffer,0,buffer.length);
System.out.println("Hex: "+s);
} catch (Exception e) {
System.out.println(e.toString());
}
return s;
}
public static String bytesToHex(byte[] b, int off, int len) {
StringBuffer buf = new StringBuffer();
for (int j=0; j<len; j++)
buf.append(byteToHex(b[off+j]));
return buf.toString();
}
public static String byteToHex(byte b) {
char[] a = { hexDigit[(b >> 4) & 0x0f], hexDigit[b & 0x0f] };
return forDigits(new String(a));
}
public static String forDigits(String val){
switch (val.length() ){
case 1:return "000"+val;
case 2:return "00"+val;
case 3:return "0"+val;
case 4:return ""+val;
default:return val;
}
}
public void sendURL(String URL,String parameters,int operationNumber){
try {
URL url;
URLConnection urlConnection;
DataOutputStream outStream;
// Create connection
url = new URL(URL);
urlConnection = url.openConnection();
((HttpURLConnection)urlConnection).setRequestMethod("POST");
urlConnection.setDoInput(true);
urlConnection.setDoOutput(true);
urlConnection.setUseCaches(false);
urlConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
urlConnection.setRequestProperty("Content-Length", ""+ parameters.length());
urlConnection.setRequestProperty("User-agent","Mozilla/4.0");
// Create I/O streams
outStream = new DataOutputStream(urlConnection.getOutputStream());
// Send request
outStream.writeBytes(parameters);
outStream.flush();
outStream.close();
// Get Response
BufferedReader rd = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
// - For debugging purposes only!
String buffer;
while((buffer = rd.readLine()) != null) {
try{
selectedMessage(Integer.parseInt(buffer),operationNumber);
}catch(Exception ex){
balance=buffer;
}
}
// Close I/O streams
rd.close();
outStream.close();
}
catch(Exception ex) {
System.out.println("Exception cought:\n"+ ex.toString());
}
}
the problem is that the buffer value is "-1-"
This value is filled in this line :
buffer = rd.readLine()
so I always find myself in this exception
}catch(Exception ex){
balance=buffer;
}
the parameters sent in the sendMessage method:
sender :شارع علي
message :وجهت إلى
numbers : 00966569114455
Updated :
I arrived to send a message in English
sender : test
message : test
in this line while((buffer = rd.readLine()) != null) {
the value of buffer equal to 1
the problem is just for sending messages in Arabic
I try to change my code without success with :
while((buffer = rd.readLine()) != null) {
try{
buffer = buffer.replaceAll("(-?[0-9]+)([^0-9]*)?","$1");
buffer=buffer.replace("-", "");
selectedMessage(Integer.parseInt(buffer),operationNumber);
}catch(Exception ex){
balance=buffer;
}
also in this line in sendURL method:
urlConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=utf-8");
and in this line in convertUnicode method :
buffer=a.getBytes(StandardCharsets.UTF_8);
this is my function which return the final message :
public void selectedMessage(int value,int operationNumber){
switch(operationNumber){
case 1:switch(value){
case 1:msg= "SUCCESS";break;
case 2:msg="ERROR";break;
}break;
}
}
with my modified code I force the buffer value to be equal to 1
in sendURL method the value of parameters is :
mobile=966556541236&password=123654&numbers=966569114455&sender=شارع علي&msg=00D800A700D9008400D9008500D800B900D800A700D9008500D9008400D800A9002000D800B100D9008200D9008500D9008800D800AC00D9008700D800AA002000D800A500D9008400D90089002000D9008600D800B800D800A700D90085002000D9008400D9008400D800AA00D800AF00D800B100D9008A00D800A8&applicationType=24
You might consider doing a RegEx replaceAll on the input first, to filter the input.
Example:
buffer = rd.readLine().replaceAll("(-?[0-9]+)([^0-9]*)","$1");
This will convert input like so:
-1- -> -1
-1 -> -1
1- -> 1