Use arabic text in android - java

How to get the arabic string in json format and how to display in android application
inputStreamReader. I get the json from server side And using the Windows-1256 encodingString to convert the arabic string but sometext not be shown correctly.
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
System.out.println(url + ":::url");
try {
HttpResponse httpResponse = httpClient.execute(httpGet);
InputStream inputStream = httpResponse.getEntity()
.getContent();
InputStreamReader inputStreamReader = new InputStreamReader(
inputStream,"windows-1256");
//new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(
inputStreamReader,8);
StringBuilder stringBuilder = new StringBuilder();
String bufferedStrChunk = null;
while ((bufferedStrChunk = bufferedReader.readLine()) != null) {
stringBuilder.append(bufferedStrChunk);
}
return stringBuilder.toString();
} catch (ClientProtocolException cpe) {
System.out
.println("Exception generates caz of httpResponse :"
+ cpe);
cpe.printStackTrace();
} catch (IOException ioe) {
System.out
.println("Second exception generates caz of httpResponse :"
+ ioe);
ioe.printStackTrace();
}

I have been r & d around a day and finally success to parse my arabic json response getting from server using following code.So, may be helpful to you.
HttpParams params = new BasicHttpParams();
HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
HttpProtocolParams.setContentCharset(params, "UTF-8");
params.setBooleanParameter("http.protocol.expect-continue", false);
HttpClient httpclient = new DefaultHttpClient(params);
HttpPost httppost = new HttpPost(Your_URL);
HttpResponse http_response= httpclient.execute(httppost);
HttpEntity entity = http_response.getEntity();
String jsonText = EntityUtils.toString(entity, HTTP.UTF_8);
Log.i("Response", jsonText);
Now, use jsonText for your further requirement.
Thank You

Related

Use HttpURLConnection instead of HttpPost

I have a code written in java for android app. by using HttpPost and DefaultHttpClient library. Currently, i am recoding it to replace the HttpPost and DefaultHttpClient library with HttpURLConnection, as DefaultHttpClient has been depricated.
I have done it for one my project, and it worked.
But in the current project I am not getting same response from the webservice upon using HttpURLConnection instead of DefaultHttpClient. Would any one help me please where I'm doing mistake?
Here is the old code:
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
String postParameter = "Param1=" + Value1 + "&Param2="+ Value2+ "&Param3="+Value3;
try {
httpPost.setEntity(new StringEntity(postParameter));
} catch (Exception e) {
e.printStackTrace();
}
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
xml = EntityUtils.toString(httpEntity);
And here is my new code
_Url = new URL(Url);
HttpURLConnection urlconnection = (HttpURLConnection) _Url.openConnection();
urlconnection.setRequestMethod(Type);
urlconnection.setConnectTimeout(Timeout);
urlconnection.setUseCaches(false);
urlconnection.setDoInput(true);
urlconnection.setDoOutput(true);
String postParameter = "Param1=" + Value1 + "&Param2="+ Value2+ "&Param3="+Value3;
BufferedWriter writer = new BufferedWriter( new OutputStreamWriter(os));
writer.write(postParameter);
writer.flush();
writer.close();
os.close();
urlconnection.connect();
The code is running without any error, but the webservice is not giving same response as it is giving for the old code.
You are not getting the input stream, try the below code
try {
String postParameter = "Param1=" + Value1 + "&Param2="+ Value2+ "&Param3="+Value3;
URL url = new URL(UrlStr);
HttpURLConnection urlConnection = (HttpURLConnection) url
.openConnection();
urlConnection.setRequestMethod("POST");
urlConnection.setRequestProperty("Accept",
"application/json");
urlConnection.setRequestProperty("Content-Type",
"application/json");// setting your headers its a json in my case set your appropriate header
urlConnection.setDoOutput(true);
urlConnection.connect();// setting your connection
OutputStream os = null;
os = new BufferedOutputStream(
urlConnection.getOutputStream());
os.write(postParameter.toString().getBytes());
os.flush();// writing your data which you post
StringBuffer buffer = new StringBuffer();
InputStream is = urlConnection.getInputStream();
BufferedReader br = new BufferedReader(
new InputStreamReader(is));
String line = null;
while ((line = br.readLine()) != null)
buffer.append(line + "\r\n");
// reading your response
is.close();
urlConnection.disconnect();// close your connection
return buffer.toString();
} catch (Exception e) {
}
try this
List nameValuePairs = new ArrayList(3);
nameValuePairs.add(new BasicNameValuePair("Param1", value1));
nameValuePairs.add(new BasicNameValuePair("Param2", value2));
nameValuePairs.add(new BasicNameValuePair("Param3", value3));
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(nameValuePairs);
OutputStream post = request.getOutputStream();
entity.writeTo(post);
post.flush();

How to send Json String using REST to java webservice in Parameter in android?

Fiends, i sending JSON String with three parameters to java web service method. but on java side method cant print in console. Please guide me what i have to change from below code?
String json = "";
HttpParams httpParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParams, 10000);
HttpConnectionParams.setSoTimeout(httpParams, 10000);
HttpClient httpclient = new DefaultHttpClient();
// Prepare a request object
HttpPost httpPost = new HttpPost(url);
HttpGet httpGet = new HttpGet(url);
JSONObject jsonObject = new JSONObject();
try {
jsonObject.put("name", "ghanshyam");
jsonObject.put("country", "India");
jsonObject.put("twitter", "ghahhd");
json = jsonObject.toString();
StringEntity se = new StringEntity(json);
se.setContentEncoding("UTF-8");
se.setContentType("application/json");
// 6. set httpPost Entity
System.out.println(json);
httpPost.setEntity(se);
httpGet.se
// 7. Set some headers to inform server about the type of the content
//httpPost.addHeader( "SOAPAction", "application/json" );
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Content-type", "application/json");
//String s = doGet(url).toString();
Toast.makeText(getApplicationContext(), "Data Sent", Toast.LENGTH_SHORT).show();
Use the following code to post the json to Java web-service: and get the resopnse as a string.
JSONObject json = new JSONObject();
json.put("name", "ghanshyam");
json.put("country", "India");
json.put("twitter", "ghahhd");
HttpPost post = new HttpPost(url);
post.setHeader("Content-type", "application/json");
post.setEntity(new StringEntity(json.toString(), "UTF-8"));
DefaultHttpClient client = new DefaultHttpClient();
HttpResponse httpresponse = client.execute(post);
HttpEntity entity = httpresponse.getEntity();
InputStream stream = entity.getContent();
String result = convertStreamToString(stream);
and Your convertStremToString() method will be as follows:
public static String convertStreamToString(InputStream is)
{
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try
{
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
}
catch (IOException e)
{
e.printStackTrace();
}
finally
{
try
{
is.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
return sb.toString();
}

Sending POST data to website and getting answer

I have a problem with getting direct link to video. I want to play it in my WebView/VideoView. How to send POST request and recieve answer with direct link from website which decode such things:
videotools.12pings.net
Is there any way to do that?
Example: put link in the website form - than click a button - direct link is ready under the button
final HttpParams httpParameters = new BasicHttpParams();
// Set the timeout in milliseconds until a connection is
// established.
HttpConnectionParams.setConnectionTimeout(httpParameters, 7000);
// Set the default socket timeout (SO_TIMEOUT)
// in milliseconds which is the timeout for waiting for data.
HttpConnectionParams.setSoTimeout(httpParameters, 10000);
HttpClient client = new DefaultHttpClient(httpParameters);
HttpResponse response = client.execute(new HttpGet(path));
HttpEntity entity = response.getEntity();
InputStream imageContentInputStream = entity.getContent();
path is the variable that contains your URL
I hope this will help you..
*You need to get
httpcomponents-client-4.1.zip and apache-mime4j-0.6.1-bin.zip
Add
apache-mime4j-0.6.1-bin.zip
and
httpclient-4.1.jar
httpcore-4.1.jar
httpmime-4.1.jar
from the lib folder in httpcomponents-client-4.1.zip
- See more at: http://blog.tacticalnuclearstrike.com/2010/01/using-multipartentity-in-android-applications/#sthash.N7qT8apH.dpuf*
try {
MultipartEntity multipart = new MultipartEntity(
HttpMultipartMode.BROWSER_COMPATIBLE);
FormBodyPart office = new FormBodyPart("office",
new StringBody(getOffice));
multipart.addPart(office);
String imageCount = Integer.toString(drawableList.size());
System.out.println("ImageCount : " + imageCount);
FormBodyPart imgNo = new FormBodyPart("imgNo", new StringBody(
imageCount));
multipart.addPart(imgNo);
} catch (Exception e) {
// TODO: handle exception
}
try {
System.out.println("result : " + multipart.getContentLength());
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(CommunicatorUrl.ADD_INCIDENT);
httppost.setEntity(multipart);
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
// print responce
outPut = EntityUtils.toString(entity);
} catch (Exception e) {
Log.e("log_tag ******",
"Error in http connection " + e.toString());
}
basically this MultipartEntity is useful for sending multiple images and datas to server using post method
String paramUsername = "username";
String paramPassword = "password";
System.out.println("*** doInBackground ** paramUsername " + paramUsername + "
paramPassword :" + paramPassword);
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("http://www.xxxxxxxxxxxxxx.php");
BasicNameValuePair usernameBasicNameValuePair = new BasicNameValuePair("ParamUsername", paramUsername);
BasicNameValuePair passwordBasicNameValuePAir = new BasicNameValuePair("paramPassword", paramPassword);
List<NameValuePair> nameValuePairList = new ArrayList<NameValuePair>();
nameValuePairList.add(usernameBasicNameValuePair);
nameValuePairList.add(passwordBasicNameValuePAir);
try {
UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(nameValuePairList);
httpPost.setEntity(urlEncodedFormEntity);
try {
HttpResponse httpResponse = httpClient.execute(httpPost);
InputStream inputStream = httpResponse.getEntity().getContent();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
StringBuilder stringBuilder = new StringBuilder();
String bufferedStrChunk = null;
while((bufferedStrChunk = bufferedReader.readLine()) != null){
stringBuilder.append(bufferedStrChunk);
}
return stringBuilder.toString();
} catch (ClientProtocolException cpe) {
System.out.println("First Exception caz of HttpResponese :" + cpe);
cpe.printStackTrace();
} catch (IOException ioe) {
System.out.println("Second Exception caz of HttpResponse :" + ioe);
ioe.printStackTrace();
}
} catch (UnsupportedEncodingException uee) {
System.out.println("An Exception given because of UrlEncodedFormEntity argument :" + uee);
uee.printStackTrace();
}

Parse Json Arabic text

I can't parse Arabic/Persian text from SQL database. Everything is set to UTF-8. My SQL database text is set to utf8_general_ci. JSON parser is set to UTF-8 too.
Text is shown good in English. But when I use Arabic/Persian text in database, android shows text as ???????.
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
// function get json from url
// by making HTTP POST or GET method
public JSONObject makeHttpRequest(String url, String method,
List<NameValuePair> params) {
// Making HTTP request
try {
// check for request method
if(method == "POST"){
// request method is POST
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}else if(method == "GET"){
// request method is GET
DefaultHttpClient httpClient = new DefaultHttpClient();
String paramString = URLEncodedUtils.format(params, "utf-8");
url += "?" + paramString;
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
I have been r & d around a day and finally success to parse my arabic json response getting from server using following code.So, may be helpful to you.
HttpParams params = new BasicHttpParams();
HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
HttpProtocolParams.setContentCharset(params, "UTF-8");
params.setBooleanParameter("http.protocol.expect-continue", false);
HttpClient httpclient = new DefaultHttpClient(params);
HttpPost httppost = new HttpPost(Your_URL);
HttpResponse http_response= httpclient.execute(httppost);
HttpEntity entity = http_response.getEntity();
String jsonText = EntityUtils.toString(entity, HTTP.UTF_8);
Log.i("Response", jsonText);
Now, use jsonText for your further requirement.
Thank You
Maybe the problem is on server side. Check the raw String you got from the Server to see if it is correctly formatted.
I think it can help you by storing it as clob/blob, since once you have the bytes which were convereted from UTF-8 at server side, any client side code can also then using various String encoding formats to display the test.
Or my other advice, use a webview to display it, its more mature to handle these nuances.

Android - Http Get Request

I'm trying to Get Request with code below but the stringbuilder is always null. The url is correct...
http://pastebin.com/mASvGmkq
EDIT
public static StringBuilder sendHttpGet(String url) {
HttpClient http = new DefaultHttpClient();
StringBuilder buffer = null;
try {
HttpGet get = new HttpGet(url);
HttpResponse resp = http.execute(get);
buffer = inputStreamToString(resp.getEntity().getContent());
}
catch(Exception e) {
debug("ERRO EM GET HTTP URL:\n" + url + "\n" + e);
return null;
}
debug("GET HTTP URL OK:\n" + buffer);
return buffer;
}
I usually do it like this:
try {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
output = EntityUtils.toString(httpEntity);
}
where output is a String-object.

Categories