Reputation: 487
I have got the following string as HTTPResponse. It is in JSON format.
[
{
"From":"en",
"OriginalTextSentenceLengths":[
5
],
"TranslatedText":"Hallo",
"TranslatedTextSentenceLengths":[
5
]
},
{
"From":"en",
"OriginalTextSentenceLengths":[
8
],
"TranslatedText":"Frage",
"TranslatedTextSentenceLengths":[
5
]
},
{
"From":"en",
"OriginalTextSentenceLengths":[
6
],
"TranslatedText":"Antwort",
"TranslatedTextSentenceLengths":[
7
]
}
]
So this string I am parsing as follows to get the "Translated Texts array"
String resp = "[{\"From\":\"en\",\"OriginalTextSentenceLengths\":[5],\"TranslatedText\":\"Hallo\",\"TranslatedTextSentenceLengths\":[5]},{\"From\":\"en\",\"OriginalTextSentenceLengths\":[8],\"TranslatedText\":\"Frage\",\"TranslatedTextSentenceLengths\":[5]},{\"From\":\"en\",\"OriginalTextSentenceLengths\":[6],\"TranslatedText\":\"Antwort\",\"TranslatedTextSentenceLengths\":[7]}]";
String[] stringArray = null;
try {
JSONArray finalResult=null;
JSONTokener tokener = new JSONTokener(resp);
finalResult = new JSONArray(tokener);
stringArray = new String[finalResult.length()];
for(int i=0;i<finalResult.length();i++){
JSONObject e = finalResult.getJSONObject(i);
Log.v("TAG",e.getString("TranslatedText"));
stringArray[i]=e.getString("TranslatedText");
}
}catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
I am getting the extracted "translated text" array ( Hallo, Frage, Antwort) out of the JSON Object...
But when I am doing the same procedure by giving the same string as input to JSONTokener directly i.e after getting HttpResponse as below, I am getting JSON Exception at finalResult = new JSONArray(tokener) line....
org.json.JSONException: End of input at character 0 of
String resp = getHttpResponse(uri);
String[] stringArray = null;
try {
JSONArray finalResult=null;
JSONTokener tokener = new JSONTokener(resp);
finalResult = new JSONArray(tokener);
stringArray = new String[finalResult.length()];
for(int i=0;i<finalResult.length();i++){
JSONObject e = finalResult.getJSONObject(i);
Log.v("TAG",e.getString("TranslatedText"));
stringArray[i]=e.getString("TranslatedText");
}
}catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
I have tried hard for 2 days to resolve this error but couldn't do it.. So I am posting it here... Please help
EDIT:
I am adding the implementation of getHttpResponse
public static String getHttpResponse(URI uri) {
Log.d("APP_TAG", "Going to make a get request");
StringBuilder response = new StringBuilder();
try {
HttpGet get = new HttpGet();
get.setURI(uri);
//DefaultHttpClient httpClient = new DefaultHttpClient();
HttpParams httpParameters = new BasicHttpParams();
int timeoutConnection = 30000;
HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
int timeoutSocket = 30000;
HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters);
Log.v("TAG","1");
HttpResponse httpResponse = httpClient.execute(get);
Log.v("TAG","2");
if (httpResponse.getStatusLine().getStatusCode() == 200) {
Log.d("demo", "HTTP Get succeeded");
HttpEntity messageEntity = httpResponse.getEntity();
InputStream is = messageEntity.getContent();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String line;
while ((line = br.readLine()) != null) {
response.append(line);
}
}
} catch (Exception e) {
Log.e("demo", e.getMessage());
}
Log.d("demo", "Done with HTTP getting");
return response.toString();
}
And the uri which I am giving to getHttpResponse is as follows
String[] texts = {"hello","question","answer"};
final String params = "appId=" + URLEncoder.encode("78280AF4DFA1CE1676AFE86340C690023A5AC139","UTF-8")
+ "&from=" + URLEncoder.encode("en","UTF-8")
+ "&to=" + URLEncoder.encode("de","UTF-8")
+ "&texts=" + URLEncoder.encode(buildStringArrayParam(texts),"UTF-8");
final URL url = new URL("http://api.microsofttranslator.com/V2/Ajax.svc/TranslateArray?" + params);
URI myURI = java.net.URI.create(url.toString());
String resp = getHttpResponse(myURI);
This response string is what I am trying to parse...
This is for buildStringArrayParam(texts)
StringBuilder targetString = new StringBuilder("[\"");
String value;
for(Object obj : values) {
if(obj!=null) {
value = obj.toString();
if(value.length()!=0) {
if(targetString.length()>2)
targetString.append(",\"");
targetString.append(value);
targetString.append("\"");
}
}
}
targetString.append("]");
return targetString.toString();
Upvotes: 1
Views: 1932
Reputation: 20961
Ahaha... Microsoft.
At least in this case, they serve their API responses with an (incorrect?) FEFF FEFF
UTF-16 byte order mark at the beginning which breaks most clients.
Like the PHP guys over here already found out, you just have to strip the first two bytes from the response. For exmaple in your code:
JSONTokener tokener = new JSONTokener(resp.substring(2));
I'm afraid the more harmless trim()
doesn't work.
It's really hard to find, because FEFF
's official name is "zero width no-break space" so it's completely invisible unless you look at your string as char array or notice how your text cursor stops when you move through a string using left/right arrow keys...
Note that you should not do this with any other HTTP response you receive, this is just for this Microsoft API (maybe others, too).
Upvotes: 3
Reputation: 140
After getting the HTTP Response you have to do this thing, you cant use Httpresponse directly.
HttpResponse response= null;
response = http.execute(get);
HttpEntity entity = response.getEntity();
String xmlstring = EntityUtils.toString(entity);
message = xmlstring;
Upvotes: 0
Reputation: 1280
And try to change your code design, hope it will help you.
And retrieve content from url -
public static String getContent(String url) throws Exception {
return(new Scanner(new URL(url).openConnection().getInputStream()).useDelimiter("/z").next());
}
Have fun...
Upvotes: 2
Reputation: 3174
Try using this:
HttpPost request = new HttpPost(URL);
HttpResponse response = httpClient.execute(request);
HttpEntity httpEntity = response.getEntity();
InputStream content = httpEntity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(content,"iso-8859-1"),8);
String resp = reader.readLine();
Now "resp" will hold the string which can be parsed...
Upvotes: 0