I have created a Google custom search engine and initiated the query using the HTTP GET. Now Google is returning the result as JSON format. I was just wondering how to format this JSON output into a Human readable way.
For example:
Title: The matrix
htmlTitle: "The matrix.."
I have seen XStream is recommended in many forums. But not sure how can I get this to work.
Can someone please help me with this.
Just for reference, I am giving the HTTP GET code in here:
public static void main(String[] args) throws IOException {
HttpGet httpget = new HttpGet("https://www.googleapis.com/customsearch/v1?key=AIzaSyBp_5Upf6h0QSXR8UveLs4_c6lAmGW_7B8&cx=014783642332862910131:opc1zgsvfhi&q=matrix&alt=json");
System.out.println(httpget.getURI());
ResponseHandler<String> responseHandler = new BasicResponseHandler();
HttpClient httpClient = new DefaultHttpClient();
String responseBody = httpClient.execute(httpget, responseHandler);
System.out.println(responseBody);
First you need to create a Class that maps the Goolge response, then use a code like this (from the XStream tutorial):
String json = "{\"product\":{\"name\":\"Banana\",\"id\":\"123\""
+ ",\"price\":\"23.0\"}}";
XStream xstream = new XStream(new JettisonMappedXmlDriver());
xstream.alias("product", Product.class);
Product product = (Product)xstream.fromXML(json);
System.out.println(product.getName());
Related
Can someone guide me how to test iOS(auto-renewable IAP) Receipt Validation API by using Sandbox URL?
I have tried this below snippet.
public void validateReceiptData(VerifyReceiptRequestView requestview) {
System.out.println("validateReceiptData ....................");
String VERIFICATION_URL=" https://sandbox.itunes.apple.com/verifyReceipt";
HttpClient httpClient = new DefaultHttpClient();
try {
HttpPost request = new HttpPost(VERIFICATION_URL);
JSONObject requestData = new JSONObject();
requestData.put("receipt-data", requestview.getReceiptdata());
requestData.put("password", requestview.getPassword());
StringEntity requestEntity = new StringEntity(requestData.toString());
request.addHeader("content-type", "application/x-www-form-urlencoded");
request.setEntity(requestEntity);
HttpResponse response =httpClient.execute(request);
String responseBody = EntityUtils.toString(response.getEntity());
JSONObject responseJSON = new JSONObject(responseBody);
System.out.println("responseJSON -------------->"+responseJSON);
}catch(Exception e) {
e.printStackTrace();
}
}
But I need sample request data for the below mentioned fields
requestData.put("receipt-data", requestview.getReceiptdata());
requestData.put("password", requestview.getPassword());
Does the field requestview.getReceiptdata() requires any Valid Purchased receipt or does Apple provides any sample receipt data to test this API in SandBox environment.
I am a newbie to Solr. I want to use Java to connect to my solr core and get the results back in XML format. By referring the official document, I am able to get the results in binary form. Below is my code:
public static void main(String[] args) throws SolrServerException, IOException {
String urlString = "http://localhost:8983/solr/index1/";
SolrClient solr = new HttpSolrClient.Builder(urlString).build();
SolrQuery query = new SolrQuery();
query.setQuery("*:*");
QueryResponse response = solr.query(query);
System.out.println(response.toString());
}
I also tried to research on how to get response. I found this link which says "If you want to get the raw xml response, just pick up any java HTTP Client, build the request and send it to Solr. You'll get a nice XML String.." solr response in xml format
I coded the below code, but it is not giving me response
public static void main(String[] args) throws ClientProtocolException, IOException
{
CloseableHttpClient httpclient = HttpClients.createDefault();
HttpGet httpGet = new HttpGet("http://localhost:8983/solr/index1/select?q=*:*&wt=xml");
CloseableHttpResponse response1 = httpclient.execute(httpGet);
System.out.println(response1);
}
}
Output:
HttpResponseProxy{HTTP/1.1 200 OK [Content-Type: application/xml; charset=UTF-8, Transfer-Encoding: chunked] ResponseEntityProxy{[Content-Type: application/xml; charset=UTF-8,Chunked: true]}}
On the official site https://lucene.apache.org/solr/guide/6_6/using-solrj.html, it is mentioned to use
solr.setParser(new XMLResponseParser());
to get XML response, but I am not sure how to use it since any example is not given. Any help is appreciated.
Edit:
As mentioned in John's comment, I have modified my code as:
System.out.println(EntityUtils.toString(response1.getEntity()));
But in the output, I can see some javascript which is followed by the XML output:
In Solr, the output in XML looks like this:
Not tried but it should work,
You need to initialize org.apache.solr.client.solrj.SolrClient which represents the Solr instance you want to use as follows.
import org.apache.solr.client.solrj.impl.XMLResponseParser;
String serverURL = "http://localhost:8983/solr/<core_name>";
SolrClient solr = new HttpSolrClient.Builder(serverURL).build();
solr.setParser(new XMLResponseParser());
i'm trying to send json object from java client to C# WebApi, but the input parameter is null.
the java code:
ObjectMapper mapper = new ObjectMapper();
Gson gson = new Gson();
String json = gson.toJson(per);
HttpClient httpclient = new DefaultHttpClient();
List<NameValuePair> qparams = new ArrayList<NameValuePair>();
qparams.add(new BasicNameValuePair("person", json.toString()));
HttpGet httpPost = new HttpGet("http://naviserver.azurewebsites.net/api/Person/Get?" + URLEncodedUtils.format(qparams, "UTF-8"));
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Content-type", "application/json");
httpPost.setHeader(
"Authorization",
"Bearer TokenRemovedBecauseUseless");
org.apache.http.HttpResponse httpResponse = httpclient.execute(httpPost);
the WebApi method:
public List<String> Get([FromUri]Person person)
{}
can someone tell me how to send json object?
The problem is that the WebApi is not expecting the person object in JSON format. By using FromUri with a complex object, it is expecting that the url with have a query parameter for each field in Person.
There is a nice example here about how it works.
Basically you will want your query parameters to look like this:
http://naviserver.azurewebsites.net/api/Person/Get?name=dave&age=30
and in Java:
qparams.add(new BasicNameValuePair("name", person.getName()));
qparams.add(new BasicNameValuePair("age", String.valueOf(person.getAge())));
If you want to send the person in JSON format, a better way would be to use a HTTP POST and set the JSON in the body. Then in the WebApi, your method would look like this:
public HttpResponseMessage Post([FromBody]Person person)
You will then also have to change your Java client to send a POST request.
HttpClient httpClient = HttpClientBuilder.create().build();
HttpPost httpPost = new HttpPost("http://naviserver.azurewebsites.net/api/Person");
Person person = new Person("dave", 30);
Gson gson = new Gson();
String json = gson.toJson(person);
StringEntity body = new StringEntity(json);
httpPost.setEntity(body);
HttpResponse response = httpClient.execute(httpPost);
I can do this with android functions:
I have post parametrs like JsonString:
String parametrs = "{\"object\": \"parametr\"};
And then im setting connection, creating String entity and makingRequest:
String url = "http://lalala.com/json/";
HttpPost request = new HttpPost(url);
StringEntity se = null;
...
se = new StringEntity(parametrs, "UTF-8");
...
request.setEntity(se);
String jsonString = null;
HttpParams httpParameters = new BasicHttpParams();
...
HttpClient httpClient = new DefaultHttpClient(httpParameters);
try
{
HttpResponse response = httpClient.execute(request);
......
How can i do this thing with spring?
you could use:
String parametrs = "{\"object\": \"parametr\"}";
RestTemplate restTemplate = new RestTemplate();
template.getMessageConverters().add(new MappingJackson2HttpMessageConverter());
restTemplate.put(new URI("http://lalala.com/json/"), parametrs);
It is the same result on server (I test it with Google App Engine + Spring MVC).
But maybe you should think about a Jackson libery, so you would be able to send Objects =)
I use:
jackson-annotations-2.4.1.jar
jackson-core-2.4.1.jar
jackson-databind-2.4.1.1.jar
spring-android-core-1.0.0.RELEASE.jar
spring-android-rest-template-1.0.1.RELEASE.jar
Jackson downloadable here
So you would be able to send it like:
restTemplate.put(new URI(http://lalala.com/json/), new Example(1L, "test");
By the way: the above code doesn't use the params, it uses the body to send the information.
Hope I was able to help you.
Let's try again and again and ...
I have something like the following:
final String url = "http://example.com";
final HttpClient httpClient = new HttpClient();
final PostMethod postMethod = new PostMethod(url);
postMethod.addRequestHeader("Content-Type", "application/json");
postMethod.addParameters(new NameValuePair[]{
new NameValuePair("name", "value)
});
httpClient.executeMethod(httpMethod);
postMethod.getResponseBodyAsStream();
postMethod.releaseConnection();
It keeps coming back with a 500. The service provider says I need to send JSON. How is that done with Apache HttpClient 3.1+?
Apache HttpClient doesn't know anything about JSON, so you'll need to construct your JSON separately. To do so, I recommend checking out the simple JSON-java library from json.org. (If "JSON-java" doesn't suit you, json.org has a big list of libraries available in different languages.)
Once you've generated your JSON, you can use something like the code below to POST it
StringRequestEntity requestEntity = new StringRequestEntity(
JSON_STRING,
"application/json",
"UTF-8");
PostMethod postMethod = new PostMethod("http://example.com/action");
postMethod.setRequestEntity(requestEntity);
int statusCode = httpClient.executeMethod(postMethod);
Edit
Note - The above answer, as asked for in the question, applies to Apache HttpClient 3.1. However, to help anyone looking for an implementation against the latest Apache client:
StringEntity requestEntity = new StringEntity(
JSON_STRING,
ContentType.APPLICATION_JSON);
HttpPost postMethod = new HttpPost("http://example.com/action");
postMethod.setEntity(requestEntity);
HttpResponse rawResponse = httpclient.execute(postMethod);
For Apache HttpClient 4.5 or newer version:
CloseableHttpClient httpclient = HttpClients.createDefault();
HttpPost httpPost = new HttpPost("http://targethost/login");
String JSON_STRING="";
HttpEntity stringEntity = new StringEntity(JSON_STRING,ContentType.APPLICATION_JSON);
httpPost.setEntity(stringEntity);
CloseableHttpResponse response2 = httpclient.execute(httpPost);
Note:
1 in order to make the code compile, both httpclient package and httpcore package should be imported.
2 try-catch block has been ommitted.
Reference:
appache official guide
the Commons HttpClient project is now end of life, and is no longer
being developed. It has been replaced by the Apache HttpComponents
project in its HttpClient and HttpCore modules
As mentioned in the excellent answer by janoside, you need to construct the JSON string and set it as a StringEntity.
To construct the JSON string, you can use any library or method you are comfortable with. Jackson library is one easy example:
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
ObjectMapper mapper = new ObjectMapper();
ObjectNode node = mapper.createObjectNode();
node.put("name", "value"); // repeat as needed
String JSON_STRING = node.toString();
postMethod.setEntity(new StringEntity(JSON_STRING, ContentType.APPLICATION_JSON));
I use JACKSON library to convert object to JSON and set the request body like below. Here is full example.
try (CloseableHttpClient httpclient = HttpClients.createDefault()) {
HttpPost httpPost = new HttpPost("https://jsonplaceholder.typicode.com/posts");
Post post = new Post("foo", "bar", 1);
ObjectWriter ow = new ObjectMapper().writer();
String strJson = ow.writeValueAsString(post);
System.out.println(strJson);
StringEntity strEntity = new StringEntity(strJson, ContentType.APPLICATION_JSON);
httpPost.setEntity(strEntity);
httpPost.setHeader("Content-type", "application/json");
try (CloseableHttpResponse response = httpclient.execute(httpPost)) {
System.out.println(response.getCode() + " " + response.getReasonPhrase());
HttpEntity entity = response.getEntity();
String result = EntityUtils.toString(entity);
System.out.println(result);
EntityUtils.consume(entity);
} catch (ParseException e) {
e.printStackTrace();
}
} catch (IOException e) {
System.out.println(e.getMessage());
}