Decoding HttpEntity into android string - encoding issue - java

I know that should be basics but i had no formation :( and I don't understand it, everywhere it seems obvious to people. I get that one side encode data with his set and android is probably expecting another one, but what can I do to translate?
My app perform a get request on google maps api to retrieve an address from a Lat/lng. But I failed to decode properly the result as a French è is displayed as è
I have not enough xp in Java to understand what to do. It is linked with UTF-8, right?
What should I do?
response = client.execute(httpGet);
HttpEntity entity = response.getEntity();
InputStream stream = entity.getContent();
int b;
while ((b = stream.read()) != -1) {
stringBuilder.append((char) b);
}
JSONObject jsonObject = new JSONObject();
jsonObject = new JSONObject(stringBuilder.toString());
retList = new ArrayList<Address>();
if("OK".equalsIgnoreCase(jsonObject.getString("status"))){
JSONArray results = jsonObject.getJSONArray("results");
for (int i=0;i<results.length();i++ ) {
JSONObject result = results.getJSONObject(i);
String indiStr = result.getString("formatted_address");
Address addr = new Address(Locale.ITALY);
addr.setAddressLine(0, indiStr);
Dbg.d(TAG, "adresse :"+addr.toString());
retList.add(addr);
}
}
Thanks for help !

Try using UTF-8,
instead of using InputStream try something like,
String responseBody = EntityUtils.toString(response.getEntity(), HTTP.UTF_8);

you can use BufferReader
your code will be like this:
InputStream stream = entity.getContent();
BufferedReader br = new BufferedReader(new InputStreamReader(stream, "UTF-8"));
int b;
while ((b = br.read()) != -1) {
stringBuilder.append(b);
}

Related

JSON data not able to capture

I write a program to capture the JSON response from the server which contain some needed information I needed. I discovered that sometime my program will not able to capture the correct JSON string and sometime it's works well with no problem. I try to check my code for capturing the response and have no idea on it. When I check the JSON string from server, it's contain the field I want but my program not able to capture the correct data.
This is my JSON String
"info":{
      "reason":"Fine",
      "boolean":false,
      "post":{
         "actions":"",
         "actions_In_process":"Checked",
         "destination":"C%3ApdfFdoc%20edipdfFdestinationpdfFexample.pdf",
         "file_type":"pdf",
       
      },
This is my program for capture the JSON string and the field I need is action_In_process
String Url1 = "http://IP:port/etc/";
HttpURLConnection con = (HttpURLConnection) Url1.openConnection();
con.setRequestMethod("GET");
con.connect();
int responseCode = con.getResponseCode();
if(responseCode == 200)
{
try
{
InputStream is = con.getInputStream();
BufferedReader read = new BufferedReader (new InputStreamReader(is));
StringBuffer buffer = new StringBuffer();
String data = "" ;
while((data = read.readLine() ) != null )
{
buffer.append(data);
}
String JsonData = buffer.toString();
JSONObject jobj = new JSONObject(JsonData);
JSONObject process_info = jobj.getJSONObject("info");
JSONObject pi = process_info.getJSONObject("post");
String action_run = pi.getString("actions_In_process");
System.out.println("Process:" +action_run);
What I had found out is sometime the Process showing is blank but when I get back the JSON data and I found out the field I need is inside the JSON response. Please share your opinion on this issues
This is the message showing my compiler if I not able to capture the correct JSON string
Process :
If in normal condition
Process : check
BufferedReader's readline() is blocking.

Incorrect Json String was received on client while it was generated correctly on server side

I am working on a Server-Client application. For part of the requests, I need to generate a piece of Json String on Server side and send it to Client. The Json String was generated correctly on the server side according to the Server log. But on the Android client side, the String was changed and cannot be parsed as correct Json String.
Here are some related code.
Generate Json String on Server side:
#RequestMapping(value="/resourceList/{actType}/{type}/{id}")
#ResponseBody public Object personList(#PathVariable int actType, #PathVariable int type, #PathVariable int id){
ArrayList<ItemBase> list = new ArrayList();
......
return new ArrayList();
}
This generates following Json code:
[{"countryID":1,"locationID":5,"siteID":5,"brief":"shark point","userID":0,"status":"normal","rank":0.0,"id":2,"timestamp":1471494991000,"displayName":"shark point","pic":"2.jpg","actType":1,"type":64},{"countryID":1,"locationID":5,"siteID":5,"brief":"halik","userID":0,"status":"normal","rank":0.0,"id":3,"timestamp":1471495034000,"displayName":"halik","pic":"3.jpg","actType":1,"type":64}]
And receive it on Android client:
......
HttpURLConnection urlConnection = null;
try {
URL url = new URL(request);
urlConnection = (HttpURLConnection) url.openConnection();
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
byte[] buffer = new byte[256];
int len = 0;
StringBuilder responseBuilder = new StringBuilder();
while ((len = in.read(buffer)) != -1) {
String str = new String(buffer, "utf-8");
responseBuilder.append(str);
}
String response = responseBuilder.toString().trim();
The response variable was written with value:
[{"countryID":1,"locationID":5,"siteID":5,"brief":"halik","userID":0,"status":"normal","rank":0.0,"id":3,"timestamp":1471495034000,"displayName":"halik","pic":"3.jpg","actType":1,471494991000,"displayName":"shark point","pic":"2.jpg","actType":1,"type":64},{"countryID":1,"locationID":5,"siteID":5,"brief":"halik","userID":0,"status":"normal","rank":0.0,"id":3,"timestamp":1471495034000,""type":64}]":"halik","pic":"3.jpg","actType":1,471494991000,"displayName":"shark point","pic":"2.jpg","actType":1,"type":64},{"countryID":1,"locationID":5,"siteID":5,"brief":"halik","userID":0,"status":"normal","rank":0.0,"id":3,"timestamp":1471495034000,"
Which cannot be parsed as Json String correctly with obvious errors.
Most methods which return a Json String to client request work fine as I expected except this one. But this method was implemented almost exactly the same as those ones work correctly. Thus I have no idea how this happened at all. Any one got any clew please help.
You're building String the wrong way.
Try this instead:
// …
HttpURLConnection urlConnection = null;
try {
URL url = new URL(request);
urlConnection = (HttpURLConnection) url.openConnection();
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
BufferedInputStream bis = new BufferedInputStream(in);
ByteArrayOutputStream buf = new ByteArrayOutputStream();
int result = bis.read();
while(result != -1) {
buf.write((byte) result);
result = bis.read();
}
String response = buf.toString();
// …

How to get JSON Key/Value pairs with JSP [duplicate]

I'm very new to RESTFull WCF Services and even newer to calling them from an Android app. Here's my WCF service:
[ServiceContract]
public interface IPeople
{
[OperationContract]
void DoWork();
[WebGet(UriTemplate = "/GetPeople",
BodyStyle = WebMessageBodyStyle.WrappedRequest,
ResponseFormat = WebMessageFormat.Json,
RequestFormat = WebMessageFormat.Json)]
[OperationContract]
string GetPeople();
}
The implementation of the interface:
public string GetPeople()
{
PeoplesEntities qe = new PeoplesEntities();
var result = from q in qe.tPeople
select q;
int count = result.Count();
int index = new Random().Next(count);
tPeople people = result.OrderBy(a=>a.ID).Skip(index).FirstOrDefault();
// result.First().ToString();
return people.FirstName + " - " + people.LastName;
}
and this is how i'm consuming it through an android service:
try {
HttpGet request = new HttpGet(SERVICE_URI + "/GetPeople");
request.setHeader("Accept", "application/json");
request.setHeader("Content-type", "application/json");
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpResponse response = httpClient.execute(request);
HttpEntity responseEntity = response.getEntity();
// Read response data into buffer
char[] buffer = new char[(int)responseEntity.getContentLength()];
InputStream stream = responseEntity.getContent();
InputStreamReader reader = new InputStreamReader(stream);
reader.read(buffer);
stream.close();
JSONArray plates = new JSONArray(new String(buffer));
return new String(buffer);
} catch (Exception e) {
e.printStackTrace();
return e.toString();
}
}
The exception I get is what is mentioned in the subject. What's strange is the value tha ti'm expecting is returned in the exception. I have no clue why it's expecting the square bracket.
FYI, most of the code i used is taken directly from online examples. Any help would be greatly appreciated. Thanks.
You're trying to create a JSONArray from a string that doesn't contain valid JSON array syntax. A JSONArray can be created from a string of the form [item1, item2, item3....] but you're just returning a single item in your string: FirstName LastName.
The line after it just returns the buffer, so the JSONArray call is pointless, anyway. You don't need the JSONArray call at all, since you're not dealing with JSON data. Just remove that line.

HttpURLConection - JSON Response isn't Complete

I am trying to send a request to the Grooveshark API using POST Payload and their requested methods, and I have found a problem. Allow me to show you my code first.
public void getResponse() throws Exception
{
if(service.equals("Grooveshark")) link += getHmacMD5(privateGroovesharkKey, jsonInfo.toString());
if(requestedMethod.equals("GET")) infoURL = new URL(link+arguments);
else infoURL = new URL(link);
HttpURLConnection connection = (HttpURLConnection) infoURL.openConnection();
connection.setRequestMethod(requestedMethod);
connection.setRequestProperty("Accept-Charset", "UTF-8");
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setUseCaches(false);
if(service.equals("Grooveshark"))
{
connection.setRequestProperty("Content-Type","application/json");
OutputStream output = connection.getOutputStream();
output.write(jsonInfo.toString().getBytes());
}
else if(requestedMethod.equals("POST") || requestedMethod.equals("PUT"))
{
OutputStream output = connection.getOutputStream();
output.write(arguments.getBytes());
}
connection.connect();
BufferedReader rd = new BufferedReader(new InputStreamReader(connection.getInputStream()));
StringBuilder sb = new StringBuilder();
String line;
while ((line = rd.readLine()) != null)
sb.append(line).append('\n');
setJsonResult(sb.toString());
System.out.println(jsonResult);
jsonFinal = new JSONObject(jsonResult);
connection.disconnect();
}
I have got that code up here in my project, and I can successfully send requested to any API Webservice that uses JSON in their responses. Now there's only a problem: In Android, it does not give me the WHOLE answer. I've tried running the code on a separate Java (no Android) project, and I get the following output. Although, if I run it on Android, the Log shows me the following:
{"header":{"hostname":"RHL073"},"result":{"songs":[{"SongID":5443351,"SongName":"??????\u00b7???? (FINAL FANTASY XII????)","ArtistID":713,"ArtistName":"Final Fantasy","AlbumID":898007,"AlbumName":"Final Fantasy XII Original Soundtrack","CoverArtFilename":"","Popularity":1214500005,"IsLowBitrateAvailable":tr
And it stops on that tr. Has it anything to do with the parsing of the file that I actually apply afterwards? I don't think it is, but just in case, here it is [This is how I call the search, JSONHandler being the object that contains the code provided above]:
public void performSearch() throws Exception
{
JSONObject search = new JSONObject();
search.put("method", method);
JSONObject header = new JSONObject();
header.put("wsKey", key);
JSONObject parameters = new JSONObject();
parameters.put("query", getSearchQuery());
parameters.put("country", "Portugal");
parameters.put("limit", limit);
parameters.put("offset", "");
search.put("header", header);
search.put("parameters", parameters);
JSONHandler jsonHandler = new JSONHandler(link, search, "Grooveshark", "POST", "");
JSONObject finalResult = jsonHandler.getJsonFinal();
JSONArray songs = finalResult.getJSONObject("result").getJSONArray("songs");
ArrayList<Result> allResults = new ArrayList<Result>();
for(int i = 0; i < songs.length(); i++)
{
JSONObject inner = (JSONObject) songs.get(i);
String name = inner.getString("SongName");
int ID = inner.getInt("SongID");
String artist = inner.getString("ArtistName");
Result res = new Result(name, artist, ID);
res.setAlbumName(inner.getString("AlbumName"));
boolean low = inner.getBoolean("IsLowBitrateAvailable");
int bit = 0;
if(low) bit = 1;
else bit = 0;
res.setIsLowBitRateAvailable(bit);
}
setResults(allResults);
}
As you can clearly see, I am using the json.org library. I really don't understand what's the problem here. Has anyone got any idea as to why?

Android HTTP Post Request doesn't work, but stock Java does?

So I have 2 codes which supposedly do the same. The one I'm using on Android however, returns the wrong HTML data. The stock Java one returns the correct data after sending the request. I have both codes here. Can you tell me (EVEN THOUGH I GAVE INTERNET PERMISSION TO ANDROID) why the Android one isn't working, while the stock Java one is working? This is the Android code:
EDIT: I FOUND THE FIX. If you're going to use a StringEntity to send such a String to the Server, you have to set the content to application/x-www-form-urlencoded. I've edited my code to show this:
public static String sendNamePostRequest(String urlString) {
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(urlString);
StringBuffer sb = new StringBuffer();
try {
StringEntity se = new StringEntity(
"__EVENTTARGET=&__EVENTARGUMENT=&__VIEWSTATE=%2FwEPDwULLTE3NDM5MzMwMzRkZA%3D%3D&__EVENTVALIDATION=%2FwEWBAL%2B%2B4CfBgK52%2BLYCQK1gpH7BAL0w%2FPHAQ%3D%3D&_nameTextBox=John&_zoekButton=Zoek&numberOfLettersField=3");
se.setContent("application/x-www-form-urlencoded");
post.setEntity();
HttpResponse response = client.execute(post);
HttpEntity entity = response.getEntity();
BufferedReader br = new BufferedReader(new InputStreamReader(
entity.getContent()));
String in = "";
while ((in = br.readLine()) != null) {
sb.append(in + "\n");
}
br.close();
} catch (Exception e) {
e.printStackTrace();
}
return sb.toString();
}
This is the stock Java code:
public String sendNamePostRequest(String urlString) {
StringBuffer sb = null;
try {
String data = "__EVENTTARGET=&__EVENTARGUMENT=&__VIEWSTATE=%2FwEPDwULLTE3NDM5MzMwMzRkZA%3D%3D&__EVENTVALIDATION=%2FwEWBAL%2B%2B4CfBgK52%2BLYCQK1gpH7BAL0w%2FPHAQ%3D%3D&_nameTextBox=John&_zoekButton=Zoek&numberOfLettersField=3";
// String data = "";
URL requestUrl = new URL(urlString);
HttpURLConnection conn = (HttpURLConnection) requestUrl
.openConnection();
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setRequestMethod("POST");
DataOutputStream dos = new DataOutputStream(conn.getOutputStream());
dos.writeBytes(data);
dos.flush();
BufferedReader br = new BufferedReader(new InputStreamReader(
conn.getInputStream()));
String in = "";
sb = new StringBuffer();
while ((in = br.readLine()) != null) {
sb.append(in + "\n");
}
dos.close();
br.close();
} catch (Exception e) {
e.printStackTrace();
}
return sb.toString();
}
If the data is getting to the server, you might want to see what is happening there (logs, errors, exceptions, etc.) Other than that:
use can use HttpURLConnection, so you can have the exact same code
For HttpClient, not sure whey you are encoding the entity yourself. Use NameValuePair to set parameters, and HttpClient will encode them for you (correctly).
You can use NameValuePair and UrlEncodedFormEntity:
List<BasicNameValuePair> nvps = new ArrayList<BasicNameValuePair>();
nvps.add(new BasicNameValuePair(KEY1, VALUE1));
nvps.add(new BasicNameValuePair(KEY2, VALUE2));
UrlEncodedFormEntity p_entity = new UrlEncodedFormEntity(nvps,HTTP.UTF_8);
post.setEntity(p_entity);

Categories