Hindi decoding error while sending message. Output is something like व� हव�� व�हव ��व� हवहব व�ह - java

static String username = "######";
static String password = "#####";
static String senderid = "###";
static String message = "वउह";
static String mobileNo = "08447475458";
static String mobileNos = "08447475458,08447475458";
static String scheduledTime = "20110701 02:27:00";
static HttpURLConnection connection = null;
public static void main(String[] args) {
try {
URL url = new URL("http://msdgweb.mgov.gov.in/esms/sendsmsrequest");
connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setRequestMethod("POST");
connection.setFollowRedirects(true);
connection = sendSingleSMS(username, password, senderid,
mobileNo, message);
System.out.println("Resp Code:" + connection.getResponseCode());
System.out.println("Resp Message:"
+ connection.getResponseMessage());
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
// Method for sending single SMS.
public static HttpURLConnection sendSingleSMS(String username,
String password, String senderId,
String mobileNo, String message) {
try {
byte[] bytes = message.getBytes("UTF-8");
String smsservicetype = "singlemsg"; // For single message.
String query = "username=" + URLEncoder.encode(username)
+ "&password=" + URLEncoder.encode(password)
+ "&smsservicetype=" + URLEncoder.encode(smsservicetype)
+ "&content=" + URLDecoder.decode(message,"utf-8") + "&mobileno="
+ URLEncoder.encode(mobileNo) + "&senderid="
+ URLEncoder.encode(senderId);
connection.setRequestProperty("Content-length", String
.valueOf(query.length()));
connection.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded;charset = utf-8");
connection.setRequestProperty("User-Agent",
"Mozilla/4.0 (compatible; MSIE 5.0; Windows 98; DigExt)");
DataOutputStream output = new DataOutputStream(connection
.getOutputStream());
int queryLength = query.length();
output.writeBytes(query);
System.out.println(query);
DataInputStream input = new DataInputStream(connection
.getInputStream());
for (int c = input.read(); c != -1; c = input.read())
System.out.print((char) c);
input.close();
} catch (Exception e) {
System.out.println("Something bad just happened.");
System.out.println(e);
e.printStackTrace();
}
return connection;
I am using this code to send sms from gateway but this code is fine if the text is english but if I give some hindi text then its not able to read it and user gets some characters.
the output is something like
व� हव�� व�हव ��व� हवहব व�ह

The DataInputStream is reading bytes, but then you have to properly convert those bytes to characters using the correct encoding. For that, you could construct a String using the constructor as follows:
String hindiCharSequence = new String(bytes, "UTF-8");

The answer from #ChthonicProject is the correct answer to accept, here a bit code. It uses a ByteArrayOutputStream to collect the bytes. A DataInputStream is more useful for reading binary ints and such. Better use just a buffering. And/or read a byte[] buffer of say 160 bytes.
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try (BufferedInputStream input = new BufferedInputStream(connection
.getInputStream())) {
for (int c = input.read(); c != -1; c = input.read()) {
baos.write(c);
}
} // Closes input.
String msg = new String(baos.toByteArray(), StandardCharsets.UTF_8);
System.out.print(msg);
What you did, was considering every byte as a char. But with UTF-8 several bytes may make up a char, which is 16 bit.

May be the problem is with the SMS encoding. By default it uses GSM 7-bit alphabet.
Check if you can specify which encoding will be used in SMS encoding.

Applied this belore query string and its done
System.out.println(message);
String finalmessage = "";
String sss = "";
char ch = 0;
for(int i = 0 ; i < message.length();i++){
ch = message.charAt(i);
int j = (int) ch;
// System.out.println("iiii::"+j);
sss = "&#"+j+";";
finalmessage = finalmessage+sss;
}
System.out.println("ddd"+finalmessage);
message=finalmessage;
System.out.println("unicoded message=="+message);

Related

Uploading file to server with Java and PHP

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.

java.lang.NumberFormatException: For input string: "-1-"

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

uploading file to server saves file with invalid characters

I am uploading a file to a php server from my java application and it uploads everything fine but I have noticed if it has a character such as ' in it then the in the file it will be \' not '
for example if I upload the file with the following code in java:
public static void main(String[] args)
{
FILE tmpFile = new FILE(EncryptionUtil.EncryptAndZip("tes't file.txt").getAbsoluteFile().toString());
postData
(
UPLOAD_URL + "?filename=" + URLEncoder.encode(file.getFileName() + ".zip", "utf-8"),
tmpFile.getFileName() + ".zip",
tmpFile.getFileLoader().readAllBytes() // FILE.getFileLoader().readAllBytes() is just a wrapper and reads all bytes from a file to byte[]
);
}
private static final String CrLf = "\r\n";
public static void postData(String url, String filename, byte[] byteData) throws IOException
{
URLConnection conn = null;
InputStream is = null;
OutputStream os = null;
try
{
URL obj = new URL(url);
System.out.println("url:" + obj);
conn = obj.openConnection();
conn.setDoOutput(true);
String message1 = "";
message1 += "-----------------------------4664151417711" + CrLf;
message1 += "Content-Disposition: form-data; name=\"uploadedfile\"; filename=\"" + filename + "\""
+ CrLf;
message1 += "Content-Type: application/octet-stream" + CrLf;
message1 += CrLf;
String message2 = "";
message2 += CrLf + "-----------------------------4664151417711--"
+ CrLf;
conn.setRequestProperty("Content-Type",
"multipart/form-data; boundary=---------------------------4664151417711");
conn.setRequestProperty("Content-Length", String.valueOf((message1
.length() + message2.length() + byteData.length)));
os = conn.getOutputStream();
os.write(message1.getBytes());
int index = 0;
int size = 1024;
do
{
if ((index + size) > byteData.length)
{
size = byteData.length - index;
}
os.write(byteData, index, size);
index += size;
}
while (index < byteData.length);
os.write(message2.getBytes());
os.flush();
is = conn.getInputStream();
char buff = 512;
int len;
byte[] data = new byte[buff];
do
{
len = is.read(data);
if (len > 0)
{
System.out.println(new String(data, 0, len));
}
}
while (len > 0);
}
catch (Exception e)
{
e.printStackTrace();
}
finally
{
try
{
os.close();
}
catch (Exception e)
{
}
try
{
is.close();
}
catch (Exception e)
{
}
try
{
}
catch (Exception e)
{
}
}
}
response from server
url: http://127.0.0.1/cloudstore/upload.php?filename=tes%27t+.txt.zip
name of file user wants to save as: tes\'t file.txt.zip
actual save name: tes\'t file.txt.zip
Array
(
[name] => tes't file.txt.zip
[type] => application/octet-stream
[tmp_name] => /tmp/phpgYl0QT
[error] => 0
[size] => 1274598
)
and below is my php file upload.php
<?php
$target_path = "" . $_GET['filename'];
echo ' name of file user wants to save as: '.$target_path.'<br/>';
if (!file_exists(dirname($target_path))) {
mkdir(dirname($target_path), 0777, true);
}
if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path)) {
echo "actual save name: ".basename( $_FILES['uploadedfile']['name'])." <br/>";
} else{
echo "There was an error uploading the file, please try again!<br />";
}
print_r($_FILES['uploadedfile']);
?>
what would be causing this issue I think it is php trying to sanitize the input? how would I stop this from occurring?
As wished by the OP, to close the question.
Use stripslashes()
It helps to un-quote a quoted string, which is the cause.
It will change tes\'t to tes't if desired to be saved as such, and if so desired.
From the manual:
An example use of stripslashes() is when the PHP directive magic_quotes_gpc is on (it was on by default before PHP 5.4), and you aren't inserting this data into a place (such as a database) that requires escaping. For example, if you're simply outputting data straight from an HTML form.
I would usually just prefer to turn off magic quotes if it is on. By the way it's already deprecated in newer PHP versions.

Java java.io.IOException: Not in GZIP format

I searched for an example of how to compress a string in Java.
I have a function to compress then uncompress. The compress seems to work fine:
public static String encStage1(String str)
{
String format1 = "ISO-8859-1";
String format2 = "UTF-8";
if (str == null || str.length() == 0)
{
return str;
}
System.out.println("String length : " + str.length());
ByteArrayOutputStream out = new ByteArrayOutputStream();
String outStr = null;
try
{
GZIPOutputStream gzip = new GZIPOutputStream(out);
gzip.write(str.getBytes());
gzip.close();
outStr = out.toString(format2);
System.out.println("Output String lenght : " + outStr.length());
} catch (Exception e)
{
e.printStackTrace();
}
return outStr;
}
But the reverse is complaining about the string not being in GZIP format, even when I pass the return from encStage1 straight back into the decStage3:
public static String decStage3(String str)
{
if (str == null || str.length() == 0)
{
return str;
}
System.out.println("Input String length : " + str.length());
String outStr = "";
try
{
String format1 = "ISO-8859-1";
String format2 = "UTF-8";
GZIPInputStream gis = new GZIPInputStream(new ByteArrayInputStream(str.getBytes(format2)));
BufferedReader bf = new BufferedReader(new InputStreamReader(gis, format2));
String line;
while ((line = bf.readLine()) != null)
{
outStr += line;
}
System.out.println("Output String lenght : " + outStr.length());
} catch (Exception e)
{
e.printStackTrace();
}
return outStr;
}
I get this error when I call with a string return from encStage1:
public String encIDData(String idData)
{
String tst = "A simple test string";
System.out.println("Enc 0: " + tst);
String stg1 = encStage1(tst);
System.out.println("Enc 1: " + toHex(stg1));
String dec1 = decStage3(stg1);
System.out.println("unzip: " + toHex(dec1));
}
Output/Error:
Enc 0: A simple test string
String length : 20
Output String lenght : 40
Enc 1: 1fefbfbd0800000000000000735428efbfbdefbfbd2defbfbd495528492d2e51282e29efbfbdefbfbd4b07005aefbfbd21efbfbd14000000
Input String length : 40
java.io.IOException: Not in GZIP format
at java.util.zip.GZIPInputStream.readHeader(GZIPInputStream.java:137)
at java.util.zip.GZIPInputStream.<init>(GZIPInputStream.java:58)
at java.util.zip.GZIPInputStream.<init>(GZIPInputStream.java:68)
A small error is:
gzip.write(str.getBytes());
takes the default platform encoding, which on Windows will never be ISO-8859-1. Better:
gzip.write(str.getBytes(format1));
You could consider taking "Cp1252", Windows Latin-1 (for some European languages), instead of "ISO-8859-1", Latin-1. That adds comma like quotes and such.
The major error is converting the compressed bytes to a String. Java separates binary data (byte[], InputStream, OutputStream) from text (String, char, Reader, Writer) which internally is always kept in Unicode. A byte sequence does not need to be valid UTF-8. You might get away by converting the bytes as a single byte encoding (ISO-8859-1 for instance).
The best way would be
gzip.write(str.getBytes(StandardCharsets.UTF_8));
So you have full Unicode, every script may be combined.
And uncompressing to a ByteArrayOutputStream and new String(baos.toByteArray(), StandardCharsets.UTF_8).
Using BufferedReader on an InputStreamReader with UTF-8 is okay too, but a readLine throws away the newline characters
outStr += line + "\r\n"; // Or so.
Clean answer:
public static byte[] encStage1(String str) throws IOException
{
try (ByteArrayOutputStream out = new ByteArrayOutputStream())
{
try (GZIPOutputStream gzip = new GZIPOutputStream(out))
{
gzip.write(str.getBytes(StandardCharsets.UTF_8));
}
return out.toByteArray();
//return out.toString(StandardCharsets.ISO_8859_1);
// Some single byte encoding
}
}
public static String decStage3(byte[] str) throws IOException
{
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try (GZIPInputStream gis = new GZIPInputStream(new ByteArrayInputStream(str)))
{
int b;
while ((b = gis.read()) != -1) {
baos.write((byte) b);
}
}
return new String(baos.toByteArray(), StandardCharset.UTF_8);
}
usage of toString/getBytes for encoding/decoding is a wrong way. try to use something like BASE64 encoding for this purpose (java.util.Base64 in jdk 1.8)
as a proof try this simple test:
import org.testng.annotations.Test;
import java.io.ByteArrayOutputStream;
import static org.testng.Assert.assertEquals;
public class SimpleTest {
#Test
public void test() throws Exception {
final String CS = "utf-8";
byte[] b0 = {(byte) 0xff};
ByteArrayOutputStream out = new ByteArrayOutputStream();
out.write(b0);
out.close();
byte[] b1 = out.toString(CS).getBytes(CS);
assertEquals(b0, b1);
}
}

HTTPS login? Java

I am trying to write a segment of code that will attempt to login to twitter to check if user name is correct and then return if it is true or false. It is not working due to the fact that if I put in the correct user name and pass that I still get the sign in page.
public class httpConnect {
//Variables
public Boolean correctCredentials(String site, String user, String pass) {
String data = connect(site, user, pass);
char[] charArray = data.toCharArray();
try {
File log = new File("C:\\Users\\________\\Desktop" + "\\" + "log.txt");
if (log.exists()) {
Scanner scan = new Scanner(log);
while (scan.hasNextLine()) {
String temp = scan.nextLine();
temp = charArray.toString() + (char) 10 + (char) 10 + (char) 10 + temp;
charArray = temp.toCharArray();
}
}
BufferedWriter out = new BufferedWriter(new FileWriter("C:\\Users\\________\\Desktop" + "\\" + "log.txt", true)); //bufferedWriter for speed
out.append((char) 10);
for (int x = 0; x < charArray.length; x++) {
out.append(charArray[x]);
}
out.flush();
out.close();
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e + "\nSorry, could not write File"); //gives error if path does not exist
}
return false;
}
public String connect(String site, String user, String pass) {
StringBuilder response = new StringBuilder();
;
try {
String encodedUser = URLEncoder.encode(user, "UTF-8");
String encodedPass = URLEncoder.encode(pass, "UTF-8");
/*
* commit - LOGIN_ACTION_NAME
* session[username_or_email] - LOGIN_USER_NAME_PARAMETER_NAME
* session[password] - LOGIN_PASSWORD_PARAMETER_NAME
*/
String content = "login=" + "commit" + " amp;amp;"
+ "session[username_or_email]" + "=" + encodedUser + "amp;amp;"
+ "session[password]" + "=" + encodedPass;
HttpsURLConnection urlConnect = (HttpsURLConnection) (new URL(site).openConnection());
urlConnect.setDoInput(true);
urlConnect.setDoOutput(true);
urlConnect.setRequestProperty("Content-Type", "text/html; charset=utf-8");
urlConnect.setRequestMethod("POST");
DataOutputStream dataOutputStream = new DataOutputStream(urlConnect.getOutputStream());
dataOutputStream.writeBytes(content);
dataOutputStream.flush();
dataOutputStream.close();
BufferedReader buf = new BufferedReader(new InputStreamReader(urlConnect.getInputStream()));
String responseLine = "";
while ((responseLine = buf.readLine()) != null) {
response.append(responseLine);
}
System.out.println(response);
} catch (Exception e) {
e.printStackTrace();
}
return response.toString();
}
}
So basically what I am going to do is attempt login and then scan page to see if title says "Twitter \ Home" and if it does then I know I logged in correctly. I have not gotten that far, but when I browse it myself it does not work.
Btw I don't want to use Twitter4j because it refuses to return a Boolean.
It also may be that I do not have the right page to attempt to log into. How would I find it? What would it be for twitter?
Have you had a look at using the official Twitter API (http://dev.twitter.com/doc) to do this?
Looking at your code suggests that you're mimicking the browser's authentication requests, but this probably misses out some information such as cookies, request tokens and whatever else they might use in their login page.

Categories