how to get json object from HttpEntity? - java

I have an HttpEntity object created as below:
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpGet get = new HttpGet(new URI(currentUrl));
HttpResponse resp = httpclient.execute(get);
HttpEntity entity = resp.getEntity();
String respbody = EntityUtils.toString(entity);
JSONObject jsonobj = new JSONObject(respbody);
Result:
org.json.JSONException: A JSONObject text must begin with '{' at character 2
Observation:
respbody string when printed is not the same text returned from currentUrl, it includes some non ascii characters.
I tried adding charset to tostring method but no luck!
It will be very helpful if anyone can suggest why this string is not normal text?

Related

How to encode Post Data JSON in CloseableHttpClient APi

I have used the CloseableHttpClient APi for a Post call and Basic Auth for authorisation
private CloseableHttpClient httpclient = HttpClients.createDefault();
HttpPost httppost = new HttpPost("https://example.com");
MyJson myJson = new MyJson(); //custom java object to be posted as Request Body
Gson gson = new Gson();
String param = gson.toJson(myJson);
StringEntity urlparam = new StringEntity(param);
String credentials = username + ":" + passwprd;
String base64Credentials = new String(Base64.getencoder().encode(credentials.getBytes()));
String authorizartionHeader = "Basic" + base64Credentials;
httppost.setHeader("Content-Type", "application/Json");
httppost.setHeader("Authorization", authorizartionHeader);
urlparam.setContentEncoding("UTF-8");
httppost.setEntity(urlparam);
httpclient.execute(httppost);
I am getting error
"Invalid UTF-8 middle byte"
I have encoded the JSON still the encoding is not working for other locales except English. How to encode the Post data.
I tried using the method
httppost.setEntity(new URLEncodedFormEntity(namevaluePair, "UTF-8")) but I don't have any Namevaluepair and if the add the Username-pswd in that then getting Null pointer response.
You should try to set everything as UTF-8
StringEntity urlparam = new StringEntity(param, StandardCharsets.UTF_8);
And add proper header
httppost.setHeader("Content-Type", "application/json;charset=UTF-8");

Parsing a HttpResponse JSON in Java

I am trying to do a HTTP post request to a web API and then parse the received HttpResponse and access the key value pairs in the body. My code is like this:
public class access {
// http://localhost:8080/RESTfulExample/json/product/post
public static void main(String[] args) {
HttpClient httpclient = HttpClients.createDefault();
HttpPost httppost = new HttpPost("https://XXXXXXX/RSAM_API/api/Logon");
// Request parameters and other properties.
List<NameValuePair> urlParameters = new ArrayList<NameValuePair>(2);
urlParameters.add(new BasicNameValuePair("UserId", "XXXXX"));
urlParameters.add(new BasicNameValuePair("Password", "XXXXXX"));
try {
httppost.setEntity(new UrlEncodedFormEntity(urlParameters));
//Execute and get the response.
HttpResponse response = httpclient.execute(httppost);
BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
String line;
while(null !=(line=rd.readLine())){
System.out.println(line);
}
System.out.println(response);
String resp = EntityUtils.toString(response.getEntity());
JSONObject obj = new JSONObject(resp);
}
catch (Exception e){
e.printStackTrace();
}
}
}
I am trying to access the body by converting it to a JSONObject with these 2 lines of code:
String resp = EntityUtils.toString(response.getEntity());
JSONObject obj = new JSONObject(resp);
But I get an error in the second line saying:
JSONObject
(java.util.Map)
in JSONObject cannot be applied
to
(java.lang.String)
Not sure if this is the correct approach. Is there a way to do what I am trying to do?
Any help would be appreciated, Thank you.
EDIT:
So when I try to print the response body using the following lines,
String resp = EntityUtils.toString(response.getEntity());
System.out.println(resp);
I get the result: {"APIKey":"xxxxxxxxxxxxxx","StatusCode":0,"StatusMessage":"Y‌​ou have been successfully logged in."}
I am looking for a way to parse this result and then access each element. Is there a way to do this?
According to JsonSimple's JsonObject documentation it takes map in the constructor but not a String. So the error you are getting what it says.
You should use JSONParser to parse the string first.
Its also better to provide the encoding as part of EntityUtils.toString say UTF-8 or 16 based off your scenario.
IOUtils.toString() from Apache Commons IO would be a better choice to use too.
Try the below line to parse the JSON:
JSONParser parser = new JSONParser();
JSONObject obj = (JSONObject) parser.parse(resp);
The above lines will vaildate the JSON and through exception if the JSON is invalid.
You don't need to read the response in the extra while loop. EntityUtils.toString(response.getEntity()); will do this for you. As you read the response stream before, the stream is already closed when comming to response.getEntity().

Apache html response returns gibberish

I'm trying to get an HTML response from a remote website, and I get something like this :
ס×?×? ×?×? ×?×? ×?×?
instead of Hebrew letters or symbols.
Here is my code:
CloseableHttpClient httpclient = HttpClients.custom()
.setDefaultCookieStore(cookieStore)
.build();
HttpGet httpget = new HttpGet(URL);
CloseableHttpResponse response = httpclient.execute(httpget);
HttpEntity entity = response.getEntity();
String s=null;
if (entity != null) {
s= EntityUtils.toString(entity);
}
Does anyone know what the problem is?
As per the docs,
The content is converted using the character set from the entity (if any), failing that, "ISO-8859-1" is used.
The default charset is being used because you don't provide one, which doesn't map those characters correctly - you should probably use UTF-8 instead. Try this.
s= EntityUtils.toString(entity, "UTF-8");

Extract string from http response in java client

I want to extract the string returned from java web service in java client. The string returned from java web service is as follows:
{"Name":"Raj Johri","Email":"mailraj#server.com","status":true}
Which is a Json string format. I have written client code to extract this string as follows:
public static void main(String[] args) throws Exception{
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost post = new HttpPost("http://localhost:8080/JsonWebService/services/JsonWebService/getData");
post.setHeader("Content-Type", "application/xml");
HttpResponse httpres = httpClient.execute(post);
HttpEntity entity = httpres.getEntity();
String json = EntityUtils.toString(entity).toString();
System.out.println("json:" + json);
}
I am getting following print on the console for json as:
json:<ns:getDataResponse xmlns:ns="http://ws.jsonweb.com"><ns:return>{"Name":"Raj Johri","Email":"mailraj#server.com","status":true}</ns:return></ns:getDataResponse>
Please tell me how to extract the string
{"Name":"Raj Johri","Email":"mailraj#server.com","status":true}
which is the actual message. Thanks in advance...
Well, The respons is as type of xml, and your json is in the <ns:return> node , so i suggest you to enter in depth of the xml result and simply get your json from the <ns:return> node.
Note:
I suggest you to try to specifying that you need the response as JSON type:
post.setHeader("Content-type", "application/json");
post.setHeader("Accept", "application/json");
There is a dirty way to do this (beside the xml parsing way)
if you are getting the same XML every time,
you can use split()
String parts[] = json.split("<ns:return>");
parts = parts[1].split("</ns:return>");
String jsonPart = parts[0];
now jsonPart should contain only {"Name":"Raj Johri","Email":"mailraj#server.com","status":true}

Android: HttpPost not work

Hi guy's (sorry for my english error :P ) i have a problem, I'm trying to post a variable (id_art) to a php page, the problem is that I can't understand if the variable is not sent properly, or if I read it wrong php side.
JAVA CODE:
HttpClient httpclient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(myurl);
StringBuilder builder = new StringBuilder();
String json, result = "";
//Build jsonObject
JSONObject jsonObject = new JSONObject();
jsonObject.accumulate("id_articolo", id_art);
//Convert JSONObject to JSON to String
json = jsonObject.toString();
//Set json to StringEntity
StringEntity se = new StringEntity(json);
//Set httpPost Entity
httpPost.setEntity(se);
//Set some headers to inform server about the type of the content
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Content-type", "application/json");
//Execute POST request to the given URL
HttpResponse httpResponse = httpclient.execute(httpPost);
//Receive response as inputStream
StatusLine statusLine = httpResponse.getStatusLine();
int statusCode = statusLine.getStatusCode();
//Convert input stream to string
if (statusCode == 200){
HttpEntity entity = httpResponse.getEntity();
InputStream content = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(content));
String line="";
while ((line = reader.readLine()) != null) {
builder.append(line);
result = builder.toString();
}
System.out.println("DEBUG"+" "+result);
PHP CODE
<?php
include_once('configurazione.php');
header("Content-Type: application/json");
mysql_set_charset('utf8');
$value = json_decode(stripslashes($_POST),true);
var_dump($value);
?>
result is NULL... Why ????
Tnks 4 help
EDIT 1
I try to edit my php code replacing
this : json_decode(stripslashes($_POST),true);
with: $value = json_decode($_POST);
But the result is the same.. NULL
EDIT 2
I try to replace
in .JAVA
httpPost.setEntity(new StringEntity(yourJson.toString(),"UTF-8"));
in .PHP
$value = json_decode(file_get_contents('php://input'));
echo $value ;
but result is NULL
in .JAVA
httpPost.setEntity(new StringEntity(yourJson.toString(),"UTF-8"));
in .PHP
$value = file_get_contents('php://input');
var_dump(json_decode($value , true));
try with this
in .JAVA
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
nameValuePairs.add(new BasicNameValuePair("json", yourJson.toString()));
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
in .PHP
$value = $_POST['json'];
var_dump(json_decode($value , true));
I believe you cannot simply send StringEntity, because POST parameters are expected to be key=>value pairs. That means you need to give a name to your parameter, let's say json.
Then you can do this:
JSONObject jsonObject = new JSONObject();
// here you can set up the data
HttpPost httppost = new HttpPost(URL);
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("json", jsonObject.toString()));
// here you can add more POST data using nameValuePairs.add()
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
On the PHP side, you'll just do
$value = json_decode($_POST['json'], true);
var_dump($value);

Categories