I'm posting Hindi / English / Marathi data to server. The server side is able to detect the data if it is in English but they're not able to detect it if the data is in Hindi / Marathi. I'm using below mentioned code for this -
public static String sendDataToServer(String urlString, String parameter) {
try {
if (TextUtils.isEmpty(urlString) || TextUtils.isEmpty(parameter))
return null;
URL url = new URL(urlString);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("POST");
urlConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
urlConnection.setDoInput(true);
urlConnection.setDoOutput(true);
urlConnection.setFixedLengthStreamingMode(parameter.length());
urlConnection.setReadTimeout(10000);
urlConnection.setConnectTimeout(45000);
urlConnection.connect();
DataOutputStream dataOutputStream = new DataOutputStream(urlConnection.getOutputStream());
dataOutputStream.writeBytes(parameter);
dataOutputStream.flush();
dataOutputStream.close();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
String input;
StringBuilder stringBuilder = new StringBuilder();
while ((input = bufferedReader.readLine()) != null) {
stringBuilder.append(input);
}
bufferedReader.close();
return stringBuilder.toString();
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
I've also tried by setting the encoding but it's still not working. Mentioned below is the code in which I'm encoding the data -
public static String submitDataToServer(String urlString, String parameter1, String parameter2) {
try {
Uri.Builder builder = new Uri.Builder()
.appendQueryParameter(Constants.USER_NAME, parameter1)
.appendQueryParameter(Constants.USER_REVIEW, parameter2);
String query = builder.build().getEncodedQuery();
URL url = new URL(urlString);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(10000);
conn.setConnectTimeout(15000);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setDoInput(true);
conn.setRequestProperty("Content-Length", "" + query.getBytes().length);
conn.setDoOutput(true);
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os, "UTF-8"));
writer.write(query);
writer.flush();
writer.close();
os.close();
conn.connect();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String input;
StringBuilder stringBuilder = new StringBuilder();
while ((input = bufferedReader.readLine()) != null) {
stringBuilder.append(input);
}
bufferedReader.close();
return stringBuilder.toString();
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
Please let me know if I'm doing anything wrong in this code. Also let me know which method is suitable as per the my requirements.
Thanks in advance.