I am getting a string in JSON response. It contains a dash (-), however instead of it, I get some special characters in the string.
I tried to decode it using UTF-8, but without success.
Here is that string:
String subject =
It contains – in the subject.
How to correctly decode it?
I am using the following Java code from which I get the JSON response:
try{
HttpGet httpGet = new HttpGet(WEB_SERVICE_URL);
String AUTHORIZATION_VALUE = "BEARER "+ "KEY"
httpGet.setHeader(AUTHORIZATION_KEY,AUTHORIZATION_VALUE);
String responseBody = "";
try(CloseableHttpResponse responseN = HttpClients.createDefault().execute(httpGet)){
responseBody = EntityUtils.toString(responseN.getEntity());
}catch (IOException e) {
e.printStackTrace();
}
JSONObject jsonObj = JSONFactoryUtil.createJSONObject(responseBody.toString());
jsonArray = jsonObj.getJSONArray("messages");
} catch (Exception e) {
e.printStackTrace();
}
In json object, for one of the attribute I get encoded string as given below.
Thank you in advance!
UPDATE :-
I modified my code with following line,
responseBody = EntityUtils.toString(responseN.getEntity(), "utf-8");
But luck did not work. However string is replaced from – to –.
I referred few links to decode further this special character but I did not get success. Any help would be really appreciable. Thank you in advance !
Related
I have made a webservice that send multiple pdfs as response to client using mutlipart/formdata but as it happens one of the client is salesforce which does not support mutlipart/ formdata.
They want a json in response like -
{ "filename": xyzname,
"fileContent": fileContent
}
I tried encoding data in Base64 using apache codec library but pdf on client side seems to get corrupted and I am unable to open it using acrobat.
Please find code below -
import org.apache.commons.io.FileUtils;
//------Server side ----------------
#POST
#Consumes(MULTIPART_FORM_DATA)
#Produces(MediaType.APPLICATION_JSON)
#Path("somepath")
public Response someMethod(someparam) throws Exception
{
....
JSONArray filesJson = new JSONArray();
String base64EncodedData = Base64.encodeBase64URLSafeString(loadFileAsBytesArray(tempfile));
JSONObject fileJSON = new JSONObject();
fileJSON.put("fileName",somename);
fileJSON.put("fileContent", base64EncodedData);
filesJson.put(fileJSON);
.. so on ppopulate jsonArray...
//sending reponse
responseBuilder = Response.ok().entity(filesJson.toString()).type(MediaType.APPLICATION_JSON_TYPE) ;
response = responseBuilder.build();
}
//------------Client side--------------
Response clientResponse = webTarget.request()
.post(Entity.entity(entity,MediaType.MULTIPART_FORM_DATA));
String response = clientResponse.readEntity((String.class));
JSONArray fileList = new JSONArray(response);
for(int count= 0 ;count< fileList.length();count++)
{
JSONObject fileJson = fileList.getJSONObject(count);
byte[] decodedBytes = Base64.decodeBase64(fileJson.get("fileContent").toString());
outputFile = new File("somelocation/" + fileJson.get("fileName").toString() + ".pdf");
FileUtils.writeByteArraysToFile(outputFile, fileJson.get("fileContent").toString().getBytes());
}
-------------------------------
Kindly advise.
Yes so the problem was with the client.
while decoding we should use
byte[] decodedBytes = Base64.decodeBase64(fileJson.getString("fileContent"));
rather than
byte[] decodedBytes = Base64.decodeBase64(fileJson.get("fileContent").toString());
Since encoded data.toString() yields some think else
Also replaced encodeBase64URLSafeString with encodeBase64String
Well quite a simple solution :)
We are doing the same, basically sending PDF as JSON to Android/iOS and Web-Client (so Java and Swift).
The JSON Object:
public class Attachment implements Serializable {
private String name;
private String content;
private Type contentType; // enum: PDF, RTF, CSV, ...
// Getters and Setters
}
And then from byte[] content it is set the following way:
public Attachment createAttachment(byte[] content, String name, Type contentType) {
Attachment attachment = new Attachment();
attachment.setContentType(contentType);
attachment.setName(name);
attachment.setContent(new String(Base64.getMimeEncoder().encode(content), StandardCharsets.UTF_8));
}
Client Side Java we create our own file type object first before mapping to java.io.File:
public OurFile getAsFile(String content, String name, Type contentType) {
OurFile file = new OurFile();
file.setContentType(contentType);
file.setName(name);
file.setContent(Base64.getMimeDecoder().decode(content.getBytes(StandardCharsets.UTF_8)));
return file;
}
And finally:
public class OurFile {
//...
public File getFile() {
if (content == null) {
return null;
}
try {
File tempDir = Files.createTempDir();
File tmpFile = new File(tempDir, name + contentType.getFileEnding());
tempDir.deleteOnExit();
FileUtils.copyInputStreamToFile(new ByteArrayInputStream(content), tmpFile);
return tmpFile;
} catch (IOException e) {
throw new RuntimeException(e);
}
}
In my REST application with PHP:
1. Send the data encoded in base64 $data = base64_encode($data) to REST.
2. Before writing the file, I decode $data = base64_decode($data).
3. Therefore, when the file is downloaded, it is already in the correct format.
I would change from using "Safe" to just using "string". So change:
encodeBase64URLSafeString(...)
to:
encodeBase64String(...)
The reason is that the "safe" versions actually change the content to preserve URLs before encrypting - I'm totally uncertain what that would do to a PDF, but suspect it is the source of your problem.
If that doesn't do it for you, I suggest encrypting/decrypting right on the server (or a separate test app) and comparing the results while you try to work it out. That way you can see if what you are doing is working, but don't have to go through the whole "start the server, start the client, connect..." process each time, and it will speed your debugging.
i want to parse some json downloaded from the web in a JSONArray.
Simple thing i think, but can't get it to work.
It seams that the JSON Format is the Problem. I tried different ways
to fix it, but nothing helps.
I download the String with this method:
private String DownloadContent(String URL) {
String result = null;
try {
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(URL);
HttpResponse response = httpClient.execute(httpGet);
result = EntityUtils.toString(response.getEntity());
} catch(Exception e) {
Log.e("log_tag", e.toString());
}
return result;
}
After that i try to parse the string to the JSONArray like this:
String resultString = DownloadContent(stringUrl);
JSONArray jArray = new JSONArray(resultString);
but everytime i get this exception:
i test the following to get the JSON right:
result = EntityUtils.toString(response.getEntity(), "UTF-8");
result = StringEscapeUtils.unescapeJson(EntityUtils.toString(response.getEntity()));
this methods changed the string but no time the JSON is valid (tested with this).
In my JSON are things like this:
Meine gr\\u00f6\\u00dfte Leidenschaft ist es
http:\\/\\/bla.de\\/wp-content\\/uploads\\/2014\\/02\\/hello.jpg
What should i do to get it right? I hope someone can help me :)
Thanks!
Looking at the detailMessage, it looks like you are trying to create a JSONArray from JSON that looks like
{"posts": [...]}
That's a JSON object, not an array. You'll need to parse it as a JSONObject and get the array object from it.
JSONObject object = new JSONObject(resultString);
JSONArray array = object.getJSONArray("posts"); // or whatever the method is to get a JSONArray element from the JSONObject
This is assuming you are trying to get the JSON array named posts.
I have a problem with my app, when i try to send a text to my apache server which contains characters like má mé mí mó mú it sent the character as m?. How can i solve that?
This is my code:
public boolean loginstatus(String reporte, String user) {
File file = new File(fileUri.getPath());
try {
MultipartEntityBuilder entity = MultipartEntityBuilder.create();
Log.e("enviando", "archivo "+fileUri.getPath());
Log.e("enviando", "reporte "+reporte);
Log.e("enviando", "usuario "+user);
entity.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
entity.addTextBody("reporte", reporte);
entity.addTextBody("usuarioID",user);
if (file.length() <= 0){
}else{
entity.addPart("archivo", new FileBody(file));
}
final HttpEntity yourEntity = entity.build();
httppost.setEntity(yourEntity);
HttpResponse response = httpclient.execute(httppost);
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return true;
}
First of all, the problem here is your encoding.
Either the database's table is not encoded to use UTF-8 or the String you send isnt.
table issue:
you can use CHARACTER SET utf8 on your db table.
String issue:
The elegant way to solve it is using
StringEntity entity = new StringEntity(Yourtext, "UTF-8");
The other way is to use your String's getBytes("UTF-8") function and use DataOutputStream
I receive a post request from client. This request contains some json data which I want to part on the server side. I have created the server using httpcore. HttpRequestHandler is used for handling the request. Here is the code I thought would work
HttpEntity entity = ((HttpEntityEnclosingRequest)request).getEntity();
InputStream inputStream = entity.getContent();
String str = inputStream.toString();
System.out.println("Post contents: " + str);*/
But I cant seem to find a way to get the body of the request using the HttpRequest object. How can I extract the body from the request object ? Thanks
You should use EntityUtils and it's toString method:
String str = EntityUtils.toString(entity);
getContent returnes stream and you need to read all data from it manually using e.g. BufferedReader. But EntityUtils does it for you.
You can't use toString on stream, because it returns string representation of the object itself not it's data.
One more thing: AFAIK GET requests can't contain body so it seems you get POST request from client.
... and for MultipartEntity use this:
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try {
entity.writeTo(baos);
} catch (IOException e) {
e.printStackTrace();
}
String text = new String(baos.toByteArray());
I have a problem in getting Hebrew characters from a http get request.
I'm getting squares characters like this: "[]" instead of the Hebrew characters.
The English characters are Ok.
This is my function:
public String executeHttpGet(String urlString) throws Exception {
BufferedReader in = null;
try {
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet();
request.setURI(new URI(urlString));
HttpResponse response = client.execute(request);
in = new BufferedReader(new InputStreamReader(response.getEntity().getContent(),"UTF-8"));
StringBuffer sb = new StringBuffer("");
String line = "";
String NL = System.getProperty("line.separator");
while ((line = in.readLine()) != null) {
sb.append(line + NL);
}
in.close();
String page = sb.toString();
// System.out.println(page);
return page;
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
You can test is by this example url:
String str = executeHttpGet("http://kavim-t.co.il/include/getXMLStations.asp?parent=7_%20_1");
Thank you!
The file you linked to doesn't seem to be UTF-8. I tested that it opens correctly using WINDOWS-1255 (hebrew encoding), you should try that instead of UTF-8.
Try a different website, it looks like it doesn't use UTF-8. Alternatively, UTF-16 may work but I haven't tried. Your code looks fine.
As others have pointed out, the content is not actually encoded as UTF-8. You might want to look at httpEntity.getContentType() to extract the actual encoding of the content, and then pass this to your InputStreamReader. This means your code will then be able to cope correctly with any encoding.
hi as is posted in this other question Special characters in PHP / MySQL
you can set the characters on the php file on the example they set utf-8, but you can set a different type that supports the chararcters you need.