Android Java UTF-8 JSON - android

One part of my app performs a query (via php) on a mysql database. I use in the database UTF-8 because I have letters like é à ê that need to appear.
I read through this problem because this seemed almost the same.
Android Java UTF-8 HttpClient Problem
However when I am implementing the code he replaces every return value with an é as null.
This is my code
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("http://www.example.com/example.php");
httppost.setEntity(new UrlEncodedFormEntity(query));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
String jsonText = EntityUtils.toString(entity, HTTP.UTF_8);
Toast.makeText(StoresInfo.this, jsonText, Toast.LENGTH_LONG).show();
is = entity.getContent();
So in the jsonText string he replaces return values with a "è" in it by null.
The last line is = entity.getConent(); I added this because I normally use the input stream to read it but this does not work as well.
Somebody has an idea?
This is my php code
<?php
mysql_select_db("database");
$q=mysql_query($_REQUEST['query']);
while($e=mysql_fetch_assoc($q))
$output[]=$e;
print(json_encode($output));
mysql_close();
?>

After trying your code on another page, I think your problem come from your server web interface.
You can for example try a GET request on a google page containing "é" characters:
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);
HttpGet httpget = new HttpGet("http://www.google.ch/search?sourceid=chrome&ie=UTF-8&q=www.google.frb%C3%A9b%C3%A9&qscrl=1#sclient=psy&hl=fr&qscrl=1&source=hp&q=b%C3%A9b%C3%A9&aq=&aqi=&aql=f&oq=&pbx=1&fp=b4d89b2783e136eb&pf=p&pdl=300");
try
{
HttpResponse response = httpclient.execute(httpget);
HttpEntity entity = response.getEntity();
String jsonText = EntityUtils.toString(entity, HTTP.UTF_8);
Log.d("TEST", jsonText);
Toast.makeText(this, jsonText, Toast.LENGTH_LONG).show();
}
catch (Exception e)
{
}

Related

Get the XML entity passed in body - HTTP Put method in Android

I wanted to retrieve the XML entity passed in body of HTTP Put method. I used the below code,
DefaultHttpServerConnection conn = new DefaultHttpServerConnection();
conn.bind(serverSocket.accept(), new BasicHttpParams());
HttpRequest request = conn.receiveRequestHeader();
conn.receiveRequestEntity((HttpEntityEnclosingRequest)request);
HttpEntity entity = ((HttpEntityEnclosingRequest)request).getEntity();
System.out.println(EntityUtils.toString(entity));
I could get the norma strings, but when trying to pass the XML entity, I could not even see the print statement.
I hope this code help you.
HttpPost httppost = new HttpPost(SERVICE_EPR);
StringEntity se = new StringEntity(SOAPRequestXML,HTTP.UTF_8);
se.setContentType("text/xml");
httppost.setHeader("Content-Type","application/soap+xml;charset=UTF-8");
httppost.setEntity(se);
HttpClient httpclient = new DefaultHttpClient();
BasicHttpResponse httpResponse =
(BasicHttpResponse) httpclient.execute(httppost);
response.put("HTTPStatus",httpResponse.getStatusLine().toString());
PFB the solution,
DefaultHttpServerConnection conn = new DefaultHttpServerConnection();
params = new BasicHttpParams();
conn.bind(socket, params);
//Extracting the information from the requested URI
HttpRequest request = conn.receiveRequestHeader();
conn.receiveRequestEntity((HttpEntityEnclosingRequest)request);
HttpEntity httpEntity = ((HttpEntityEnclosingRequest)request).getEntity();
if(httpEntity != null){
InputStream instream = httpEntity.getContent();
try {
// do something useful
String myString = IOUtils.toString(instream, "UTF-8");
Log.e(TAG,">>>> http body > "+myString);
} finally {
instream.close();
}
}
Don't put any log or print statements using the data you received, I was getting 'Content already consumed' exception. I had used several logs using the httpEntity i received and that was causing the problem for me. I commented those(marked yellow) and started working.
PF the Apache doc for reference,
http://hc.apache.org/httpcomponents-core-ga/tutorial/pdf/httpcore-tutorial.pdf

Android CouchDB {"error":"bad_request","reason":"invalid_json"}

While trying to Create a new Document in my IrisCouch Database, i am always getting following error:
{"error":"bad_request","reason":"invalid_json"}
This is the relevant part of my function:
try {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("https://username.iriscouch.com:6984/mydb");
StringEntity entity = new StringEntity(body);
httpPost.setEntity(entity);
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Content-type", "application/json");
HttpResponse httpResponse = httpClient.execute(httpPost);
System.out.println(httpResponse.toString()) ;
HttpEntity httpEntity = httpResponse.getEntity();
// Get the response
BufferedReader rd = new BufferedReader(new InputStreamReader(httpEntity.getContent()));
String line = "";
while ((line = rd.readLine()) != null) {
System.out.println(line);
}
System.out.println("body: " + body);
} catch (Exception e) {
e.printStackTrace();
}
Here is my System.out of "body":
{"bild1":"","bild2":"","bild3":"","bild4":"","bild5":"","bild6":"","bild7":"","bild8":"","bild9":"","bild10":"","name":"","plz":0,"ort":"","strasse":"","n_koordinate":0,"e_koordinate":0,"beschreibung":"","groesse":"< 50m²","sitzplaetze":"< 50","grillstellen":"1","reservierung":false,"res_name":"","res_tele":"","res_weiteres":"","wc":true,"behindi":false,"dach":true,"kinderfreundl":false,"auto":false,"kinderwagen":false,"einkauf":false,"datum":"2015-07-01-14:12:01:856","bewertung":0,"anz_bewertung":0}
The JSON is valid. Tested it with jsonlint.com JSON Validator.
What could i do? Thanks in advance!
Perhaps the unicode superscript 2 (²) is bothering it?
Not sure which library this HttpPost is, but seems a lot like the HttpWebRequest, so try setting your header this way:
httpPost.setHeader("Content-type", "application/json charset=utf-8");
It could also be that the HttpPost class doesn't properly encode strings.
(I haven't pasted this in my Visual studio, so just a shot in the dark)

How to pass header to WebView in Android [duplicate]

This question already has answers here:
Send Post request along with HttpHeaders on Android
(2 answers)
Closed 2 years ago.
I am passing post data as Json using postUrl() to WebView in Android. Now I want to pass a header "Content-Type: application/json" also along with that. How to achieve it?
may this will help u :)
HttpPost httpPost = new HttpPost(url_src);
HttpParams httpParameters = new BasicHttpParams();
httpclient.setParams(httpParameters);
StringEntity se = new StringEntity(str,"UTF-8");
se.setContentType("application/json");
httpPost.setEntity(se);
httpPost.setHeader("userId", ""+userId);//userID
httpPost.setHeader("machineId", machineId);//deviceUserMachineID
response = httpclient.execute(httpPost);
I believe this will help: link
Doesn't look like you can actually send headers with postUrl(), only with loadUrl() method.
it possible to post data with header i have done it in my project
I am posting you my code ...
HttpParams par = new BasicHttpParams();
//par.setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
int timeoutConnection = 30000;
HttpConnectionParams.setConnectionTimeout(par, timeoutConnection);
int timeoutSocket = 10000;
HttpConnectionParams.setSoTimeout(par, timeoutSocket);
DefaultHttpClient httpClient = new DefaultHttpClient(par);
// httpClient.setParams(par);
HttpPost httpPost = new HttpPost(url);
httpPost = new HttpPost(url);
if(postMessage==null)
throw new IllegalArgumentException("please send post data as well");
byte[] data =postMessage.toString().getBytes("UTF-8");
String base64 = Base64.encodeToString(data, Base64.DEFAULT);
System.out.println("Base64: "+base64);
// httpPost.setEntity(new UrlEncodedFormEntity(params));
httpPost.setEntity(new StringEntity(base64));
httpPost.setHeader("token", app.getToken());
httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
System.out.println("httpEntity.getContent():"+ is );
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
data = sb.toString();
//remember httpconnection should be in background thread
// if you use asynchtask then upper code should be in doinbackground method
//and in onpostexecution do data load in webview
webview.loadData(data, "text/html","UTF-8");

Android:Trying to make an httpPost Request but keep getting connection timeout

I am really in pain right now please help me solve this issue.
I've previously also tried to make the http request to my localhost and it all works fine but right now it is not working and I don't know why.
I am trying to make the request from the following code.
HttpClient httpclient = new DefaultHttpClient();
String result="";
try
{
HttpPost httppost = new HttpPost("http://[ip]/php/untitled.php");
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(3);
nameValuePairs.add(new BasicNameValuePair("email",this.userEmail));
nameValuePairs.add(new BasicNameValuePair("pwd",this.userpassword));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity=response.getEntity();
if(entity!=null)
{
InputStream inputStream=entity.getContent();
result= convertStreamToString(inputStream);
}
}
catch (ClientProtocolException e)
{
Log.e("errorhai",e.getMessage());
}
catch (IOException e)
{
Log.e("errorhai",e.getMessage());
}
return result;
I've also added the internet permission but still it keeps saying
Connect to [ip] timed out.
When I enter the url in my browser it works fine but it is not working here.Please tell me what can be the causes of this problem ?
you can set the time out parameter to handle such type of exception :
HttpParams httpParameters = new BasicHttpParams();
/* Set the timeout in milliseconds until a connection is established.
The default value is zero, that means the timeout is not used.*/
int timeoutConnection = 60*1000*1;
HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
/* Set the default socket timeout (SO_TIMEOUT)
in milliseconds which is the timeout for waiting for data. */
int timeoutSocket = 60*1000*1;
HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
HttpClient client = new DefaultHttpClient(httpParameters);
//HttpClient client = new DefaultHttpClient();
HttpResponse httpResponse;
try {
/** Finally, we send our request using HTTP. This is the synchronous
long operation that we need to run on this thread. */
httpResponse = client.execute(request);
/*int responseCode = httpResponse.getStatusLine().getStatusCode();
String message = httpResponse.getStatusLine().getReasonPhrase();*/
HttpEntity entity = httpResponse.getEntity();
if (entity != null) {
InputStream instream = entity.getContent();
String res = convertStreamToString(instream);
MLog.v("HTTP RESPONSE : ", "Res :-"+res);
if(!res.trim().equalsIgnoreCase("[]")){
response.setResult(res);
response.setSuccess(true);
}else{
response.setSuccess(false);
response.setErrorMessage(AppConstant.RECORD_NOT_FOUND);
}
/** Closing the input stream will trigger connection release */
instream.close();
}else{
response.setSuccess(false);
response.setErrorMessage(AppConstant.NETWORK_ERROR);
}
}
catch (Exception e) {
//client.getConnectionManager().shutdown();
e.printStackTrace();
response.setSuccess(false);
response.setErrorMessage(AppConstant.NETWORK_ERROR);
}
//you can again try to send request , if your response is not sucess.
//retryHttpRequestIfNotSucess();
your problem might be related to the login. Is your script expecting a preemptive authetification? Do you have a error page for a failed login?
For requesting a page with preemptive http basic authentication i'm using the following code that is working. Have a try, if its working for you too.
DefaultHttpClient httpclient = null;
HttpParams params = new BasicHttpParams();
HttpResponse response = null;
HttpEntity entity = null;
// Set connection parameter
params.setParameter(HttpProtocolParams.USE_EXPECT_CONTINUE, false);
HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);
httpclient = new DefaultHttpClient(params);
// Create a post statement
HttpPost httppost = new HttpPost(Constants.urlLogin);
httppost.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.RFC_2965);
httppost.getParams().setParameter("http.protocol.single-cookie-header", true);
httppost.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BROWSER_COMPATIBILITY);
List<NameValuePair> nvps = new ArrayList<NameValuePair>();
nvps.add(new BasicNameValuePair("login_name", this.username));
nvps.add(new BasicNameValuePair("login_passwd", this.userpassword));
httppost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
response = httpclient.execute(httppost);
entity = response.getEntity();
int statusCode = response.getStatusLine().getStatusCode();
String loadedContent = null;
if (entity != null)
{
loadedContent = EntityUtils.toString(entity, HTTP.UTF_8);
// loadedContent =
// Helper.convertStreamToString(entity.getContent());
entity.consumeContent();
}
if (statusCode != (HttpStatus.SC_OK))
{
throw new ServerCommunicationErrorException();
} else if (!loadedContent.contains("Logout"))
{
// Login failed
throw new LoginFailedException();
}
As you can see, i get a "not logged in" page as result, if the login fails to determine the login process. Further more i set some parameters, that might be also interesting for you. You can look here for more information on parameters.

What is wrong with this POST request with json on android?

I'm trying to perform a POST request to a server that wants the Content-Type set to application/json with name and email as some keys. Currently, I'm getting a 406 error, which I'm assuming is working on the server side, but android can't handle the response. How can I tweak the code to get a 200 response?
HttpClient client = new DefaultHttpClient();
HttpEntity entity;
try{
JSONObject j = new JSONObject();
j.put("name" , myName);
j.put("email", myEmail);
HttpPost post = new HttpPost(targetURL);
post.setHeader("Content-Type", "application/json");
StringEntity se = new StringEntity(j.toString(), HTTP.UTF_8);
se.setContentType("application/json");
post.setEntity(se);
HttpResponse response = client.execute(post);
entity = response.getEntity();
Log.d("response", response.getStatusLine().toString());
} catch(Exception e){Log.e("exception", e.toString());}
Does that look about right? Do I need one of those response handlers when creating the HttpClient?
This works for me with json-2.0.jar
HttpClient client = new DefaultHttpClient();
HttpConnectionParams.setConnectionTimeout(client.getParams(), MyApplication.HTTP_TIMEOUT); //Timeout Limit
HttpResponse response;
ArrayList<appResults> arrayList = new ArrayList<appResults>();
String resul;
try{
HttpGet get = new HttpGet(urls[0]);
response = client.execute(get);
/*Checking response */
if(response!=null){
InputStream in = response.getEntity().getContent(); //Get the data in the entity
resul = convertStreamToString(in);
Gson gson = new Gson();
Type listType = new TypeToken<ArrayList<appResults>>() {}.getType();
arrayList = gson.fromJson(resul, listType);
in.close();
of course in asynctask or thread.
But 406... it seems that your format on your webserver and your app are not consistent...

Categories

Resources