I have WebService Call using Java Http Client. Need to do Junit testing using Mockito for the Response of WebService (HttpResponse).
Gson gson = new Gson();
HttpResponse httpResponse= JavaHttpClient.callWebService("URL",object);
String json = EntityUtils.toString(httpResponse.getEntity());
response = gson.fromJson(json, ClassName.class);
log.info("Response: " + new Gson().toJson(response));
How to set the mock values for httpResponse.getEntity() ? and this should be convert to JSON as above
Thanks
Nithyanandan K
Here is some sample MockServer. Modify it for your requirement.
import static org.mockserver.integration.ClientAndServer.startClientAndServer;
import static org.mockserver.model.HttpRequest.request;
import static org.mockserver.model.HttpResponse.response;
import org.mockserver.client.server.MockServerClient;
import org.mockserver.initialize.ExpectationInitializer;
import org.mockserver.model.Header;
import org.mockserver.model.HttpStatusCode;
public class MockServerInitializer implements ExpectationInitializer {
/**
* Standalone mock server
*
* #param args
*/
public static void main(String[] args) {
MockServerClient mockServerClient = startClientAndServer(9999);
defineMockServerBehaviour(mockServerClient);
}
#Override
public void initializeExpectations(MockServerClient mockServerClient) {
defineMockServerBehaviour(mockServerClient);
}
public static void defineMockServerBehaviour(MockServerClient mockServer) {
mockServer.when(
request()
.withMethod("POST")
.withPath("/Sample")
).respond(
response()
.withStatusCode(HttpStatusCode.OK_200.code())
.withHeader(Header.header("Content-Type", "application/xml"))
.withBody("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n" +
"<Response>\n" +
" <responseStatus>OK</responseStatus>\n" +
"</Response>"));
}
}
Related
I'm very new to web-service dev and I'm trying to make a POST request to an API using Jersey. The issue is I think I'm mixing documentation and example I'm finding online between client & server. I'm pretty sure that it's simple but I can't figure out why my code is failing.
Here is my main Class :
import deliveryPayload.Payload;
import jakarta.ws.rs.*;
import jakarta.ws.rs.client.*;
import jakarta.ws.rs.core.HttpHeaders;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.Response;
import jakarta.ws.rs.core.UriBuilder;
import org.apache.commons.lang3.StringUtils;
import responsePayload.ResponsePayload;
import java.net.URI;
import java.util.*;
#Path("/hook")
public class Hook {
private static final String apiToken = "myToken";
private static final String domain = "url";
private static final String apiUrl = "https://" + domain + "/api/v1/";
#POST
#Consumes(MediaType.APPLICATION_JSON)
public Response eventHook(String body, #HeaderParam("Pass") String password) {
ObjectMapper objectMapper = new ObjectMapper();
Payload payload = new Payload();
try {
payload = objectMapper.readValue(body, Payload.class);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
EventsItem event = payload.getData().getEvents().get(0);
Actor actor = event.getActor();
Response response = ClientBuilder.newClient()
.target(getBaseURI())
.path("apps/" + "someID" + "/users")
.request(MediaType.APPLICATION_JSON)
.header(HttpHeaders.AUTHORIZATION, apiToken)
.post(Entity.entity(actor, MediaType.APPLICATION_JSON));
return response;
}
}
I'm getting this error Parse Error: The response headers can't include "Content-Length" with chunked encoding when using Postman.
Thanks for any help !
So, the problem:
i need to send some custom value in the header via Apache Camel/MQTT.
Code example:
import java.util.Map;
import org.apache.camel.CamelContext;
import org.apache.camel.Message;
import org.apache.camel.impl.DefaultCamelContext;
public class MQTTEntryPoint {
private static final String BASE = "mqtt:test?host=tcp://ip_address&";
private static final String SUBSCRIBER = BASE + "subscribeTopicName=test2";
private static final String PUBLISHER = BASE + "publishTopicName=test2";
public static void main(String[] args) {
CamelContext camelContext = new DefaultCamelContext();
Thread thread = new Thread(new Runnable() {
#Override
public void run() {
Message message = camelContext.createConsumerTemplate().receive(SUBSCRIBER).getIn();
String body = message.getBody(String.class);
System.out.println(body);
Map<String, Object> headers = message.getHeaders();
for (String key : headers.keySet()) {
System.out.println("Header key: " + key + ", Header value: " + headers.get(key));
}
}
});
thread.start();
camelContext.createProducerTemplate().sendBodyAndHeader(PUBLISHER, "some body value", "headerKey",
"some header value");
}
}
In system out i can see only:
some body value
Header key: CamelMQTTSubscribeTopic, Header value: test2
As you can see, sending of custom header value does not works. What is wrong?
The MQTT protocol AFAIR only supports a single payload without any additional headers.
I have my service defined as:
#Path("/fileservice")
public class FileService {
#POST
#Path("/path")
#Consumes("application/xml")
public Response getFilePath(FileRequest fileRequest) {
System.out.println("....." + fileRequest.client);
(...)
}
My activator:
#ApplicationPath("/services")
public class JaxRsActivator extends Application{
}
And the XML file mapping is defined as:
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
#XmlRootElement(name="fileDetails")
public class FileRequest {
#XmlElement public String path;
#XmlElement public String client;
And my client is:
public static void main(String args[]) throws Exception {
URI uri = new URI(SERVICE_URL);
Client client = ClientBuilder.newClient();
String xml = "<fileDetails> "
+ "<path>usr/test/a.pdf</path>"
+ "<client>abc</client>"
+"</fileDetails>" ;
Response response= client.target(uri).request().post(Entity.xml(xml));
System.out.println("Request posted :"+ response.getAllowedMethods());
System.out.println("Request posted, response status :"+ response.getStatus());
When I send request to the URL http://localhost:8080/xx/services/fileservice/path I'm getting response.getStatus() as 405.
What I'm doing wrong here?
Hi guys I am trying to use scribe-java library to access the REST api via http.code looks
package org.scribe.examples;
import java.util.*;
import org.scribe.builder.*;
import org.scribe.builder.api.*;
import org.scribe.model.*;
import org.scribe.oauth.*;
public class WooCommerceOauth1Example {
private static final String RESOURCE_URL = "http://WEBSITE.COM/wc-api/v1/orders";
public static void main(String[] args) {
OAuthService service = new ServiceBuilder().provider(OneLeggedApi10.class)
.apiKey("ck_SOME_NUMBER")
.apiSecret("cs_SOME_NUMBER")
.build();
// Now let's go and ask for a protected resource!
System.out.println("Now we're going to access a protected resource...");
OAuthRequest request = new OAuthRequest(Verb.GET, RESOURCE_URL);
//Since it is a one legged protocol, access token is empty.Right?
service.signRequest(new Token("", ""), request);
Response response = request.send();
System.out.println("Got it! Lets see what we found...");
System.out.println();
System.out.println(response.getCode());
System.out.println(response.getBody());
System.out.println();
System.out.println("Thats it man! Go and build something awesome with Scribe! :)");
}
}
Throws the following error
{"errors":[{"code":"woocommerce_api_authentication_error","message":"oauth_consumer_key parameter is missing"}]}
. Any Ideas why my code is throwing the above error? Note that I have checked the v1 endpoint with http and it returns sensible message back.so basically it is working.
Removing '&' + OAuthEncoder.encode(tokenSecret) from https://github.com/fernandezpablo85/scribe-java/blob/master/src/main/java/org/scribe/services/HMACSha1SignatureService.java#L32 and adding and changed signature type to QueryString and it works now.
I will propose a PR after cleaning.Thanks Pablo. Below is the full code
package org.scribe.builder.api;
import org.scribe.model.Token;
import org.scribe.model.Verb;
public class OneLeggedApi10 extends DefaultApi10a {
#Override
public String getAccessTokenEndpoint() {
return null;
}
#Override
public String getRequestTokenEndpoint() {
return null;
}
#Override
public String getAuthorizationUrl(Token requestToken) {
return null;
}
#Override
public Verb getAccessTokenVerb() {
return Verb.GET;
}
#Override
public Verb getRequestTokenVerb() {
return Verb.GET;
}
}
And the example class
package org.scribe.examples;
import org.scribe.builder.*;
import org.scribe.builder.api.*;
import org.scribe.model.*;
import org.scribe.oauth.*;
public class WooCommerceOauth1Example {
private static final String NETWORK_NAME = "Woocommerce";
private static final String RESOURCE_URL = "http://YOUR_DOMAIN/wc-api/v1/orders/count";
private static final String SCOPE = "*"; //all permissions
public static void main(String[] args) {
OAuthService service = new ServiceBuilder().provider(OneLeggedApi10.class)
.apiKey("API_KEY")
.apiSecret("SECRET_KEY")
.debugStream(System.out)
.signatureType(SignatureType.QueryString)
/*.scope(SCOPE).*/
.build();
System.out.println("=== " + NETWORK_NAME + "'s OAuth Workflow ===");
System.out.println();
// Now let's go and ask for a protected resource!
System.out.println("Now we're going to access a protected resource...");
OAuthRequest request = new OAuthRequest(Verb.GET, RESOURCE_URL);
service.signRequest(new Token("", ""), request);
Response response = request.send();
System.out.println("Got it! Lets see what we found...");
System.out.println();
System.out.println(response.getCode());
System.out.println(response.getBody());
System.out.println();
System.out.println("Thats it man! Go and build something awesome with Scribe! :)");
}
}
We're trying to get 2-legged OAuth to work with the Gmail atom feed. We're using the Java library contributed by John Kristian, Praveen Alavilli and Dirk Balfanz. [http://oauth.net/code/] instead of the GData library.
We know we have the correct CONSUMER_KEY and CONSUMER_SECRET, etc. becuase it works with the Contacts feed (http://www.google.com/m8/feeds/contacts/default/full) and have no problems. However with Gmail atom feed it always returns: HTTP/1.1 401 Unauthorized
Any ideas? Should we try a different OAuth framework or does the problem lie on the Google side?
We think we got it working with the OAuth libraries but not with the GData library.
Snippet of code is:
import static net.oauth.OAuth.HMAC_SHA1;
import static net.oauth.OAuth.OAUTH_SIGNATURE_METHOD;
import java.net.URL;
import java.util.List;
import java.util.Map;
import net.oauth.OAuthAccessor;
import net.oauth.OAuthConsumer;
import net.oauth.OAuthMessage;
import net.oauth.ParameterStyle;
import net.oauth.SimpleOAuthValidator;
import net.oauth.client.OAuthClient;
import net.oauth.client.httpclient4.HttpClient4;
/**
* Sample application demonstrating how to do 2-Legged OAuth in the Google Data
* Java Client. See the comments below to learn about the details.
*
*/
public class GmailAtomFeed2LeggedOauth {
public static String CONSUMER_KEY = "test-1001.com";
public static String CONSUMER_SECRET = "zN0ttehR3#lSecr3+";
public static String SCOPE = "https://mail.google.com/mail/feed/atom";
public static String RESOURCE_URL = "https://mail.google.com/mail/feed/atom";
public static String SERVICE_NAME = "mail";
public static String username = "username";
public static boolean debug = true;
public static void main(String[] args) throws Exception {
// This should be passed in as a parameter
String user = username + "#" + CONSUMER_KEY;
OAuthConsumer consumer = new OAuthConsumer(null, CONSUMER_KEY, CONSUMER_SECRET, null);
OAuthAccessor accessor = new OAuthAccessor(consumer);
// HMAC uses the access token secret as a factor,
// and it's a little less compute-intensive than RSA.
accessor.consumer.setProperty(OAUTH_SIGNATURE_METHOD, HMAC_SHA1);
// Gmail only supports an atom feed
URL atomFeedUrl = new URL(SCOPE +"?xoauth_requestor_id=" + user);
System.out.println("=====================================================");
System.out.println("Building new request message...");
OAuthMessage request = accessor.newRequestMessage(OAuthMessage.GET, atomFeedUrl.toString(),null);
if (debug) {
List<Map.Entry<String, String>> params = request.getParameters();
for (Map.Entry<String, String> p : params) {
System.out.println("'" + p.getKey() + "' = <" + p.getValue() + ">");
}
System.out.println("Validating message...");
SimpleOAuthValidator validator=new SimpleOAuthValidator();
validator.validateMessage(request,accessor);
}
OAuthClient client = new OAuthClient(new HttpClient4());
System.out.println("Client invoking request message...");
System.out.println(" request: " + request);
OAuthMessage message = client.invoke(request, ParameterStyle.AUTHORIZATION_HEADER);
System.out.println("=====================================================");
System.out.println(" message: " + message.readBodyAsString());
System.out.println("=====================================================");
}
}
Put the OAuth data in the Authorization header, not on the URI.