I have created 2 web services and I was able to send some data.
Using this three lines of code
HttpClient client = HttpClientBuilder.create().build();
HttpGet request = new HttpGet("http://localhost/<appln-folder-name>/method/domethod?data1=abc&data2=xyz");
HttpResponse response = client.execute(request);
In this situation, the method that I posted send to a Web Server the 2 data.
#Path("/domethod")
// Produces JSON as response
#Produces(MediaType.APPLICATION_JSON)
// Query parameters are parameters: http://localhost/<appln-folder-name>/method/domethod?data1=abc&data2=xyz
public String doLogin(#QueryParam("data1") String d1, #QueryParam("data2") String d2){
String response = "";
System.out.println("Data: d1="+d1+"; d2="+d2);
if(checkData(d1, d1)){
response = Utitlity.constructJSON("tag",true);
}else{
response = Utitlity.constructJSON("tag", false, "Error");
}
return response;
}
System.out works correctely and print: d1=abc; d2=xyz
But now the application isn't able to return response to the first method.
How I can get the response?
You're already getting the response here:
HttpResponse response = client.execute(request);
And since you're already using org.apache.httpcomponents you can do something like:
String result = EntityUtils.toString(response.getEntity());
After that you have your data as a string, simply do what you wish with it.
EDIT:
A little bit more information, your data is in the entity of the response, which is an HttpEntity object. You can get the content from there as an InputStream and read it as you wish, my example was for a simple string.
First of all, I would annotate with get the method. Then I would use a Java Class and let the library convert the class to json for me.
Try to do this:
#GET
#Path("/domethod")
// Produces JSON as response
#Produces(MediaType.APPLICATION_JSON)
// Query parameters are parameters: http://localhost/<appln-folder-name>/method/domethod?data1=abc&data2=xyz
public String doLogin(#QueryParam("data1") String d1, #QueryParam("data2") String d2){
Response response = new Response();
System.out.println("Data: d1="+d1+"; d2="+d2);
if(checkData(d1, d1)){
//set in response the tag property to true and maybe another property to OK
response.setTag(true);
response.setStatus("OK");
}else{
//set in response the tag property to false and maybe another property to ERROR
response.setTag(false);
response.setStatus("ERROR");
}
return response;
}
Related
I am using Micronaut #Client to call external service which returns me response
of type FullNettyClientHttpResponse and it has body in the form of CompositeByteBuf(freed, components=1); I want to convert CompositeByteBuf to a human readable toString message but it has failing with IllegalReferenceCountException. Please provide suggestion how I can get the text message here.
#Client(value = "url")
public interface MyClient {
#Post(consumes = MediaType.APPLICATION_XML, produces = MediaType.APPLICATION_XML)
HttpResponse call(String body);
}
class service{
void method(){
HttpResponse httpResponse = client.call(request);// returns FullNettyClientHttpResponse with body "Optional[CompositeByteBuf(freed, components=1)]"
Optional<CompositeByteBuf> reBody = httpResponse.getBody(CompositeByteBuf.class);
if(reBody.isPresent()){
CompositeByteBuf b=reBody.get();
byte[] req = new byte[b.readableBytes()];
b.readBytes(req);
String body = new String(req, CharsetUtil.UTF_8).substring(0, req.length -
System.getProperty("line.separator").length());
System.out.println("server receive order : " + body);
}
}
I tried to get the message using toString but failed with IllegalReferenceCountException.
b.toString(Charset.defaultCharset()); // Method threw 'io.netty.util.IllegalReferenceCountException' exception.
toString returns CompositeByteBuf.
b.toString(); //CompositeByteBuf(freed, components=1);
You must specify the body type in the client if you want micronaut to keep the body of the response.
For example:
HttpResponse<String> call(String body);
I'm trying to send a post request to github to create a repository. I've got oauth 2.0 working and the request is correctly signed but github is just returning "Problems parsing JSON"
I'm using Scribe for the oauth side of things and as far as I can tell I've added JSON to the URL but I'm not 100% certain I'm doing it correctly, or am I just missing headers or something?
#POST
#Path("create_repo/{userid}")
#Produces(MediaType.APPLICATION_JSON)
public Response createRepo(#PathParam("userid") String userid) {
OAuthService service = createService().build();
User user = collection.findOneById(userid);
final OAuthRequest request = new OAuthRequest(Verb.POST, "https://api.github.com/user/repos", service);
Token token = new Token(user.getGithubToken(), "SECRET");
service.signRequest(token, request);
request.addHeader("Content-type", "application/vnd.github.v3+json");
request.addHeader("X-OAuth-Scopes", "repo");
request.addQuerystringParameter("name", "Test_v1");
LOGGER.info("Built request: " + request.getCompleteUrl());
final com.github.scribejava.core.model.Response response = request.send();
return Response.ok(response.getBody()).build();
}
The built URL looks like: https://api.github.com/user/repos?access_token=XXX_SECRET_XXX&name=Test_v1
I've also tried swapping the access_token after the params but same result.
Appreciate the any help.
Well I solved this by creating a object, serializing it, and adding it as a payload.
#POST
#Path("create_repo/{userId}/{projectId}")
#Produces(MediaType.APPLICATION_JSON)
public Response createRepo(#PathParam("userId") String userId, #PathParam("projectId") String projectId) {
// Setup collections
User user = userCollection.findOneById(userId);
ProjectDescription projectDescription = projectCollection.findOneById(projectId);
// Build repository object from project description
GithubRepository repository = new GithubRepository();
repository.setName(projectDescription.getTitle());
repository.setDescription(projectDescription.getDescription());
// Serialize object
ObjectMapper mapper = new ObjectMapper();
String jsonInString = null;
try {
jsonInString = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(repository);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
// Build request
OAuthService service = createService().build();
final OAuthRequest request = new OAuthRequest(Verb.POST, PROTECTED_RESOURCE_URL + "/user/repos", service);
request.addHeader("content-type", "application/json");
request.addPayload(jsonInString);
// Sign and send request
Token token = new Token(user.getGithubToken(), "secret");
service.signRequest(token, request);
request.send();
return Response.status(201).build();
}
However, I'd still like to know where I went wrong with my first attempt.
Query string parameters are ignored in POST requests. That's why it worked when passing them in the request body.
From GitHub's API Overview docs:
Parameters
Many API methods take optional parameters. For GET requests, any parameters not specified as a segment in the path can be passed as an HTTP query string parameter:
curl -i "https://api.github.com/repos/vmg/redcarpet/issues?state=closed"
In this example, the ‘vmg’ and ‘redcarpet’ values are provided for the :owner and :repo parameters in the path while :state is passed in the query string.
For POST, PATCH, PUT, and DELETE requests, parameters not included in the URL should be encoded as JSON with a Content-Type of ‘application/json’:
$ curl -i -u username -d '{"scopes":["public_repo"]}' https://api.github.com/authorizations
I need to implement robospice for doing the networking part in my Translator app. I previously used async task class and it was working fine, but now i want to improve my application with implementing robospice. I'am trying to execute the following code but it doesn't't throw any exception it just never executes....
#Override
public TranslatedText loadDataFromNetwork() throws Exception {
String jsonString = getJsonString();
String headerValue = getHeaderValue(jsonString);
String text = pair.getWordPairs().getWordFrom();
String languageFrom = pair.getLanguagePairs().getLanguageFrom().getCode();
String languageTo = pair.getLanguagePairs().getLangougateTo().getCode();
String uri = String
.format("http://api.microsofttranslator.com/v2/Http.svc/Translate?text=%s&from=%s&to=%s&contentType=text/html",
URLEncoder.encode(text, "UTF-8"),
URLEncoder.encode(languageFrom, "UTF-8"),
URLEncoder.encode(languageTo, "UTF-8"));
HttpHeaders headers = new HttpHeaders();
headers.set("Authorization", headerValue);
// Create a new RestTemplate instance
RestTemplate restTemplate = new RestTemplate();
// Add the Simple XML message converter
getRestTemplate().getMessageConverters().add(new SimpleXmlHttpMessageConverter());
//set the headerValue in the Entity
org.springframework.http.HttpEntity<?> request = new org.springframework.http.HttpEntity<Object>(headerValue);
// Make the HTTP GET request, marshaling the response from XML to an
// EventList
Log.v("request","Making request!");
//This line never finish execuitng, doesen't throw exception or anything in logCat
ResponseEntity<Object> responseEntity = getRestTemplate().exchange(uri, HttpMethod.GET, request, null);
Log.v("request", responseEntity.getBody().toString());
Log.d("Load Data From Network", request.getBody().toString());
return null;
}
The last thing it shows in log cat is Request First!! And nothing after that. It never even gets to The Request Listener onRequestFailure.
Can any 1 tell me what i do wrong ?
This is what look weird to me in your code:
ResponseEntity<Object> and null as 4th parameter of the exchange method are not correct. You need to provide a type which represents the response you get from the server.
The object returned by loadDataFromNetwork() is what you will get in the onRequestSuccess() method. Returning null is not a good idea, in my opinion.
I fixed the problem. So if you need to handle stream you will have to provide the following code
ResponseEntity<byte[]> responseEntity = getRestTemplate().exchange(uri, HttpMethod.GET, request, byte[]);
I am writing a client for one of my REST API using jersey(org.glassfish.jersey.client.*).
api url is : http://localhost:5676/searchws/search/getresults (POST)
this api returns a json response. i need to provide a payload using jersey client and thats where i am stuck. FOllowing is a sample extract of payload which i need to provide (preferably as string)
Question is how can i provide a payload (XML/JSON) as string or entity to my webtarget.
I saw the answer to providing payload mentioned by calden How to send Request payload to REST API in java? but i am looking for a way to do it in jersey client.
Here is my code till now which does not work fully for post requests.
public class RequestGenerator
{
private WebTarget target;
private ClientConfig config;
private Client client;
private Response response;
public RequestGenerator(Method RequestSendingMethod) throws Exception
{
switch (RequestSendingMethod)
{
case POST :
config = new ClientConfig();
client = ClientBuilder.newClient(config);
target = client.target("http://localhost:5676/searchws").path("search").path("getresults");
String payload = "{\"query\":\"(filter:(\\\"google\\\")) AND (count_options_availbale:[1 TO *])\"}"; //This is just a sample json payload actual one is pretty large
response = target.request(MediaType.APPLICATION_JSON_TYPE).post(Entity.json("")); // What to do here
String jsonLine = response.readEntity(String.class);
System.out.println(jsonLine);
}
}
You specify payload as the argument to Entity.json
String payload = "{\"query\":\"(filter:(\\\"google\\\")) AND (count_options_availbale:[1 TO *])\"}";
response = target.request(MediaType.APPLICATION_JSON_TYPE).post(Entity.json(payload));
I got this working using following code, Salil's code works fine as well(+1 with thanks to him), thanks everyone who contributed to this problem, loving stackoverflow:
public class RequestGenerator
{
private WebTarget target;
private ClientConfig config;
private Client client;
private Response response;
public RequestGenerator(Method RequestSendingMethod) throws Exception
{
switch (RequestSendingMethod)
{
case POST :
String payload = "\r\n{\r\n\"query\": \"google \",\r\n\"rows\": 50,\r\n\"return_docs\": true,\r\n\"is_facet\": true\r\n}"; //this is escapped json string in single line
config = new ClientConfig();
client = ClientBuilder.newClient(config);
target = client.target("http://localhost:7400/searchws/search/getresults");
response = target.request().accept(MediaType.APPLICATION_JSON).post(Entity.entity(payload, MediaType.APPLICATION_JSON), Response.class);
processresponse(response); //This could be any method which processes your json response and gets you your desired data.
System.out.println(response.readEntity(String.class));
break;
case GET :
config = new ClientConfig();
client = ClientBuilder.newClient(config);
target = client.target("http://localhost:7400/search-service/searchservice").path("search").path("results").path("tiger");
response = target.request().accept(MediaType.APPLICATION_JSON).get();
processresponse(response); //This could be any method which processes your json response and gets you your desired data.
System.out.println(response.readEntity(String.class));
}
}
I am using RestFul Webservice with JBoss Server to deploy the app to receive the JSONObject to my web service ,to test that i have created the web service and written test cases for it .Now i got hung up in passing the JSONobject from test case to web services , when i pass the json object to #post service calls it responses that Null Pointer Exception , even i have tried with passing string to it it responds null values.
I have used Annotations as follows in webservice
#consumes({Mediatype.APPLICATION_JSON})
#Consumes("application/json")
Test case As:
#Test
public void testgetmsg() {
String msg = "{\"patient\":[{\"id\":\"6\",\"title\":\"Test\"}]}";
try {
JSONObject obj = new JSONObject(new JSONTokener(msg));
WebResource resource = client.resource( "https://localhost:8443/../../resources/create");
ClientResponse response = resource.type(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON).
entity(obj).post(ClientResponse.class,JSONObject.class);
}
}
can any body guide me to proceed further ?
Thanks in Advance
You don't need to create the json object, you can just pass the string.
you should
ClientResponse response = resource.type(MediaType.APPLICATION_JSON)
.accept(MediaType.APPLICATION_JSON)
.post(ClientResponse.class, msg);
//CLIENT
public static void createStudent() {
String input = "{\"id\":12,\"firstName\":\"Fade To Black\",\"lastName\":\"Joy\"}";
ClientResponse response = service.path("class/post")
.type("application/json").post(ClientResponse.class, input);
System.out.println("Output from Server .... \n");
String output = response.getEntity(String.class);
System.out.println(output);
System.out.println(response.getStatus()+ "OK");
}
Instead of using code client you can use add on firefox (POSTER) to passing value as json or formparam...
// create new student SERVER
//class
#POST
#Path("post")
#Consumes(MediaType.APPLICATION_JSON)
#Produces(MediaType.APPLICATION_JSON)
public Response createStudent(Student st) {
// add new student
StudentDAO.instance.getModelStudent().put("8", st);
// response status code
return Response.status(200).entity(st).build();
}