I have a web application in C#, and I use JsonSerializer to create a json.
Now I'm wotrking on an android application and I'm trying to read the json.
On my Android application, my code is
try {
HttpClient client = new DefaultHttpClient();
client.getParams().setParameter(CoreProtocolPNames.USER_AGENT, "android");
HttpGet request = new HttpGet();
request.setHeader("Content-Type", "application/json; charset=utf-8");
request.setURI(new URI(uri));
HttpResponse response = client.execute(request);
in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
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();
JSONObject jsonObject = new JSONObject(page); // here it explodes
}
It get explodes when trying to create a json object, because the value of "page" is
"{\\"Key\\":\\"1\\",\\"RowVersion\\":[0,0,0,0,0,0,226,148].....
When I try to get the json on the browser manually (with direct GET url), I get
"{\"Key\":\"1\",\"RowVersion\":[0,0,0,0,0,0,226,148]......
When I copy this string manually it works fine.
How can I fix it?
You are returned a JSON object as a String whereas you expected a JSON object...
With Jackson, this is easily solved:
final ObjectMapper mapper = new ObjectMapper();
// JSON object as a string...
final JsonNode malformed = mapper.readTree(response.getEntity().getContent());
// To JSON object
final JsonNode OK = mapper.readTree(malformed.textValue());
Either this, or fix the server side so as to return the JSON object!
I think that your code it too complicated, try do it like this:
String page = EntityUtils.toString(response.getEntity());
Related
In my project , i separated back-end and front-end modules and run by providing REST api from back-end and call it by using Apache Http Client and GSON.
I want to provide multiple language like German,French... on UI(webpage).
On webpage , It shows like this "Schl��ssli Sch��negg, Wilhelmsh��he" , but in database and RestAPI json is "Schlössli Schönegg" .
How can I support multi language?
In back-end , i wrote Request methods like get,put,post and In Front-end, i used HttpClient and GSON to convert JSON to/from Java Object.
I tried inside the html but main problem is from GSON when it convert fromJSON() , the original JSON value ""Schlössli Schönegg" become "Schl��ssli Sch��negg, Wilhelmsh��he".
In RestAPI , JSON data is
{
"addressId": 3,
"buildingName": "Schlössli Schönegg",
"street": "Wilhelmshöhe",
"ward": "6003",
"district": "luzern",
"cityOrProvince": "luzern state",
"country": "Switzerland"
}
But in Front-end , Java Object String Data after GSON convert is
(..buildingName=Schlössli Schönegg, street=Wilhelmshöhe, ward=6003, district=luzern, cityOrProvince=luzern state, country=Switzerland)
Here , RestClient function code
public List<FakeEmployeeDTO> getAllEmployeeList() throws IOException {
HttpClient client = HttpClientBuilder.create().build();
HttpGet getRequest = new HttpGet(URL);
HttpResponse response = client.execute(getRequest);
Integer statusCode = response.getStatusLine().getStatusCode();
if (statusCode != 200) {
throw new SystemException(ERROR_MESSAGE + statusCode);
}
BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
String line = "";
StringBuilder jsonData = new StringBuilder();
while ((line = rd.readLine()) != null) {
jsonData.append(line);
}
response.getEntity().getContent().close();
rd.close();
logger.info(jsonData.toString());
Gson gson = new GsonBuilder().setDateFormat("dd-MMM-yyyy").create();
Type listType = new TypeToken<List<FakeEmployeeDTO>>() {
}.getType();
List<FakeEmployeeDTO> employeeList = gson.fromJson(jsonData.toString(), listType);
sortEmployeeListByFirstName(employeeList);
return employeeList;
}
Inside Employee, I have address atrribute , inside that address i have value like buildingNumber and Street, that value can be in any languages.
Try with this
(BufferedReader rd = new BufferedReader( new InputStreamReader(response.getEntity().getContent(),
"UTF-8"));)
Entire Code will end up with like this.
public List<FakeEmployeeDTO> getAllEmployeeList() throws IOException {
HttpClient client = HttpClientBuilder.create().build();
HttpGet getRequest = new HttpGet(url);
HttpResponse response = client.execute(getRequest);
Integer statusCode = response.getStatusLine().getStatusCode();
if (statusCode != 200) {
throw new SystemException(ERROR_MESSAGE + statusCode);
}
BufferedReader rd = new BufferedReader( new InputStreamReader(response.getEntity().getContent(),
"UTF-8")); // if it is not working please try with ("ISO-8859-1")
String line = "";
StringBuilder jsonData = new StringBuilder();
while ((line = rd.readLine()) != null) {
jsonData.append(line);
}
response.getEntity().getContent().close();
rd.close();
logger.info(jsonData.toString());
Gson gson = new GsonBuilder().setDateFormat("dd-MMM-yyyy").create();
Type listType = new TypeToken<List<FakeEmployeeDTO>>() {
}.getType();
List<FakeEmployeeDTO> employeeList = gson.fromJson(jsonData.toString(), listType);
sortEmployeeListByFirstName(employeeList);
return employeeList;}
Next time make sure to try with this, because you can use "try with resource"
try (BufferedReader reader = new BufferedReader(new InputStreamReader(
new URL("https://htt.your url.com" + URLEncoder.encode(query, "UTF-8") )
.openConnection().getInputStream()))) {
I have the following Java code to send a POST request to SharePoint REST API to create a list and it returns the following authentication errors:
CloseableHttpClient httpClient = null;
try {
String user = xxx;
String password = xxx;
String domain = xxx;
String workstation = "";
CredentialsProvider credsProvider = new BasicCredentialsProvider();
credsProvider.setCredentials(new AuthScope(AuthScope.ANY),
new NTCredentials(user, password, workstation, domain));
httpClient = HttpClients.custom().setDefaultCredentialsProvider(credsProvider).build();
String digestQueryURL = "http://my_sharepoint_site/_api/contextinfo";
HttpPost httpPost = new HttpPost(digestQueryURL);
httpPost.addHeader("Accept", "application/json;odata=verbose");
CloseableHttpResponse response = httpClient.execute(httpPost);
byte[] content = EntityUtils.toByteArray(response.getEntity());
String jsonString = new String(content, "UTF-8");
ObjectMapper mapper = new ObjectMapper();
JsonNode j = mapper.readTree(jsonString);
String formDigestValue = j.get("d").get("GetContextWebInformation").get("FormDigestValue").toString();
response.close();
// now try to create the list
String url = "http://my_sharepoint_site/_api/web/lists";
HttpPost httpPost2 = new HttpPost(url);
httpPost2.addHeader("X-RequestDigest", getFormDigest(httpClient));
httpPost2.addHeader("Accept", "application/json;odata=verbose");
httpPost2.addHeader("Content-Type", "application/json;odata=verbose");
String body = "{ '__metadata': { 'type': 'SP.List' }, 'AllowContentTypes': true, 'BaseTemplate': 100, 'ContentTypesEnabled': true, 'Description': 'My list description', 'Title': 'Test' }";
StringEntity se = new StringEntity(body);
httpPost2.setEntity(se);
CloseableHttpResponse response2 = httpClient.execute(httpPost2);
StringBuilder result = new StringBuilder();
System.out.println(response2.getStatusLine().toString());
BufferedReader br = new BufferedReader(new InputStreamReader(response2.getEntity().getContent()));
String output;
while ((output = br.readLine()) != null) {
result.append(output);
}
System.out.println(result.toString());
} catch (Exception e) {
}
Console output
HTTP/1.1 403 FORBIDDEN
{"error":{"code":"-2130575251, System.Runtime.InteropServices.COMException","message":{"lang":"en-US","value":"The security validation for this page is invalid. Click Back in your Web browser, refresh the page, and try your operation again."}}}
I can use very similar code to send GET requests to the REST API to retrieve all lists, retrieve list items, perform all these read operations. However this does not work for POST requests. Am I doing something wrong? The credentials provided are for an account that has full control over the entire site collection, so we can rule out permission errors.
Alright, the problem is really very simple. This line:
String formDigestValue = j.get("d").get("GetContextWebInformation").get("FormDigestValue").toString();
Returns the formDigestValue with quotation marks enclosing it. Using asText() instead of toString() helped.
I want to get just ID from httpResponse after I did HttpGet.
This is my code:
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet("http://localhost:80/api/");
HttpResponse httpResponse = httpClient.execute(httpGet);
System.out.println(httpResponse);
BufferedReader rd = new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent()));
String line = "";
while ((line = rd.readLine()) != null) {
System.out.println(line);
}
which returns this:
{"list":[{"timestamp":{"$date":"2014-08-01T08:37:54.058Z"},"nameGroup":false,"_id":{"$oid":"53db5045ccf2b2399e0e6128"},"created":{"$date":"2014-08-01T08:31:01.139Z"}],"name":"John"}]}
But I just want Oid not the whole thing. Any idea?
Thanks
Strint you've got is json encoded data, so you need to decode it and than you are able to access the field "oid". There are several libaries around to acomplish this job:
gson
JsonSimple
Jackson etc.
My favorite for small projects is gson
Using Jackson or Gson, you can parse the response JSON and get exactly the part you need.
If you don't need the whole result, then there is no point in creating a reference object, just manually traverse the json document, e.g.
mapper.readTree(responseText).get("foo").get("bar")
I think instead of using a library just to get value of one parameter is not appropriate if you have other options available. I would suggest you to parse the json on yor own using the APIs provided. You can try following:
try {
JSONObject obj = new JSONObject(your_json_string);
String value= null;
if (obj != null && obj.has(YOUR_KEY_FOR_PARAM)) {
value = obj.getString(YOUR_KEY_FOR_PARAM));
}
}
im having a strange problem when receiving json results from the server. I have no idea what the problem is. The thing is that my String json result is corrupted, with strange symbols.
The result is like this (taken from eclipse debug)
Image :
Another strange thing that happens is that when I change the URL of the service to an alternative one, it works and the data is not corrupted. The URLs are the same but once redirects everything to the other.
The URL is use always is (example) http://www.hello.com
The URL that works is http://www.hello.com.uy
(cant post the exact link for security reasons)
The second one redirects everything to the first one, its the only thing it does.
I have tried changing the encoding to UTF-8 and it is still not working, here is the code (with one of the URLs commented)
I have also tried using Dev HTTP Client extension from chrome to check the service and it works fine, no corrupted data. Also, it works perfectly on iOS so i think its just and android/java issue.
DevClient:
try {
JSONObject json = new JSONObject();
HttpParams httpParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParams, 10000);
HttpConnectionParams.setSoTimeout(httpParams, 10000);
HttpClient client = new DefaultHttpClient(httpParams);
//String url = TAG_BASEURL_REST +"Sucursal";
String url = "http://www.-------.com/rest/Sucursal";
//String url = "http://www.--------.com.uy/rest/Sucursal";
HttpGet request = new HttpGet(url);
request.setHeader("Accept", "application/json");
request.setHeader("Content-type", "application/json");
HttpResponse response = client.execute(request);
HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream is = entity.getContent();
BufferedReader reader = new BufferedReader(
new InputStreamReader(is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
String jsonRes = sb.toString();
JSONArray jObj = new JSONArray(jsonRes);
return jObj;
}
} catch (Throwable t) {
Log.i("Error", "Request failed: " + t.toString(), t);
}
return null;
InputStream is = entity.getContent();
// check if the response is gzipped
Header encoding = response.getFirstHeader("Content-Encoding");
if (encoding != null && encoding.getValue().equals("gzip")) {
is = new GZIPInputStream(is);
}
So I'm building an URL to be called to get a JSON response but facing a strange issue. Building the URL as shown below returns "Not found" but for testing purposes I just built the URL as such "http://api.themoviedb.org/3/search/person?api_key=XXX&query=brad" and didn't append anything and that returned the correct response. Also tried not encoding "text" and same thing...Not found. Any ideas?
StringBuilder url = new StringBuilder();
url.append("http://api.themoviedb.org/3/search/person?api_key=XXX&query=").append(URLEncoder.encode(text, ENCODING));
Log.v("URL", url.toString());
try {
HttpGet httpRequest = null;
httpRequest = new HttpGet(url.toString());
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = (HttpResponse) httpclient.execute(httpRequest);
HttpEntity entity = response.getEntity();
BufferedHttpEntity bufHttpEntity = new BufferedHttpEntity(entity);
InputStream input = bufHttpEntity.getContent();
String result = toString(input);
//JSONObject json = new JSONObject(result);
return result;
Try using the code I have below. I've copied and pasted it out of some code I use and I know it works. May not solve your problem but I think its worth a shot. I've edited it a little bit and it should just be copy and paste into your code now.
HttpGet request = new HttpGet(new URI(url.toString()));
HttpClient client = new DefaultHttpClient();
HttpResponse response = client.execute(request);
BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
StringBuilder builder = new StringBuilder();
for (String line = null; (line = reader.readLine()) != null;) {
builder.append(line).append("\n");
}
JSONObject jResponse = new JSONObject(builder.toString());