Post method in RestAssured throws java.net.ConnectException - java

I'm trying to Post a JSON to a Rest service using RestAssured and it throws java.net.ConnectException error.
Since my JSON message is complex, I've made it available within the txt file.
public class PPJson {
public static void main(String[] args) throws IOException, JSONException {
BufferedReader tempreader = new BufferedReader(new FileReader("/Users/RestService/Jsonfileinput.txt"));
StringBuilder sbuilder = new StringBuilder();
String line = tempreader.readLine();
while (line != null) {
sbuilder.append(line);
line = tempreader.readLine();
}
tempreader.close();
//Initializing Rest API's URL
String APIUrl = "http://api.sample.com/api/v3/parcel/collect?apiKey={Value}";
//Initializing payload or API body
String APIBody = sbuilder.toString();
// Building request using requestSpecBuilder
RequestSpecBuilder builder = new RequestSpecBuilder().setBody(APIBody).setContentType("application/json; charset=UTF-8");
RequestSpecification requestSpec = builder.build();
//Making post request with authentication
Response response = given().authentication().preemptive().basic("","").spec(requestSpec).when().post(APIUrl);
JSONObject JSONResponseBody = new JSONObject(response.body().asString());
//Fetching the desired value of a parameter
String result = JSONResponseBody.getString("status");
System.out.println(result);
}
}

#all, the issue has been fixed, removed the references to RequestSpecs and here's the code snippet
public class ParcelPointJson {
public static void main(String[] args) throws IOException, JSONException {
BufferedReader tempreader = new BufferedReader(new FileReader("/Users/srkrish/gitTrial/pim-automation/RestService/Jsonfileinput.txt"));
StringBuilder sbuilder = new StringBuilder();
String line = tempreader.readLine();
while (line != null) {
sbuilder.append(line);
line = tempreader.readLine();
}
tempreader.close();
//Initializing Rest API's URL
String APIUrl = "http://api.staging.wow.parcelpoint.com.au/api/v3/parcel/collect?apiKey=09BH1TXV";
//Initializing payload or API body
String APIBody = sbuilder.toString();
//Making post request with authentication
Response response = given().contentType("application/json; charset=UTF-8").body(APIBody).when().post(APIUrl);
JSONObject JSONResponseBody = new JSONObject(response.body().asString());
//Fetching the desired value of a parameter
String result = JSONResponseBody.getString("parcelId");
System.out.println(result);
//Assert.assertEquals(result, "200");
}
}

Related

Get value from JSON and put it in String

it's my first question here, i've try to be the more explicit :)
I want get value from a JSON page : https://api.dailymotion.com/video/x3p6d9r?fields=onair.
I have follow a tutorial about json object.
But i want get the value "onair" and put this in a String for use a IF STRING == "XX".
This is my code :
public class notification extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_notification);
detectonline();
}
public void detectonline(){
/*
if (xx == "false") {
Do something is live is off
}
else{
Do something is live is on
}
*/
}
public static boolean checkIfOnline(String channel) throws IOException {
String channerUrl = "https://api.dailymotion.com/video/x3p6d9r?fields=onair";
String jsonText = readFromUrl(channerUrl);// reads text from URL
JsonParser parser = new JsonParser();
JsonObject json = parser.parse(jsonText).getAsJsonObject();
return !json.get("onair").isJsonNull();
}
private static String readFromUrl(String url) throws IOException {
URL page = new URL(url);
StringBuilder sb = new StringBuilder();
Scanner scanner = null;
try{
//scanner = new Scanner(page.openStream(), StandardCharsets.UTF_8.name());
scanner = new Scanner(page.openStream());
while (scanner.hasNextLine()){
sb.append(scanner.nextLine());
}
}finally{
if (scanner!=null)
scanner.close();
}
return sb.toString();
}
}
I remake your method according what you are looking for it's one of several way to parse json data :
public static boolean checkIfOnline(String channel) throws JSONException, IOException {
String channerUrl = "https://api.dailymotion.com/video/x3p6d9r?fields=onair";
String jsonText = readFromUrl(channerUrl);// reads text from URL
JSONObject json = new JSONObject(jsonText); // You create a json object from your string jsonText
if(json.has("onair")) { // just a simple test to check the node that you need existe
boolean value = json.getBoolean("onair"); // In the url that you gave onair value is boolean type
return value;
}
return false;
}
I will create methode using your way !
public static boolean checkIfOnline(String channel) throws IOException {
String channerUrl = "https://api.dailymotion.com/video/x3p6d9r?fields=onair";
String jsonText = readFromUrl(channerUrl);// reads text from URL
JsonParser parser = new JsonParser();
String myString =json.get("onair");
return mystring;}

How to implement Facebook Realtime Update Subscription with callback URL [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
How to implement Facebook Realtime API
Configure Facebook app and then install the app on Facebook pages/users that you want updates for.
We need to maintain a callback URL for Facebook to be able to post updates. Jersey based implementation as an example:
#Path("/social/facebook/update")
public class FacebookRealtimeAPIResource
{
private static final String HUB_MODE = "hub.mode";
private static final String HUB_CHALLENGE = "hub.challenge";
private static final String HUB_VERIFY_TOKEN = "hub.verify_token";
public FacebookRealtimeAPIResource()
{
// any desired implementation here
}
#GET
#Produces(MediaType.TEXT_HTML)
public void validateFacebookRequest(
#DefaultValue("") #QueryParam(HUB_MODE) String hubMode,
#DefaultValue("") #QueryParam(HUB_CHALLENGE) String hubChallenge,
#DefaultValue("") #QueryParam(HUB_VERIFY_TOKEN) String hubVerifyToken,
#Context HttpServletRequest request,
#Context HttpServletResponse response)
{
try
{
// hubVerifyToken based validation if desired
response.setStatus(HttpServletResponse.SC_OK);
response.getWriter().write(hubChallenge);
response.getWriter().flush();
response.getWriter().close();
}
catch (IOException exc)
{
throw new WebApplicationException(Response.Status.BAD_REQUEST);
}
}
#POST
#Consumes(MediaType.APPLICATION_JSON)
public void processFacebookRealtimeUpdate(#Context HttpServletRequest request, InputStream inputStream)
{
StringBuilder sb = new StringBuilder();
String newLine = System.getProperty("line.separator");
String line;
String json = "";
try
{
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, request.getCharacterEncoding()));
while ((line = reader.readLine()) != null)
sb.append(line).append(newLine);
}
catch (Exception exc)
{
throw new WebApplicationException(Response.Status.BAD_REQUEST);
}
json = sb.toString(); // use this json string for desired purpose
}
}
Install app for page and then subscribe for page updates
public class FacebookRealtimeSubscriber
{
private AccessToken appAccessToken = null;
private String appSecret = // your app secret
private String userAccessToken = // access token for user that owns the page, generated using your app
private String applicationId = // your application id
private String callbackURL = "<your context root>/social/facebook/update";
private String pageName = // page name you want to install app for
private FacebookClient client = null;
private final String subscribedAppsEdge = "/subscribed_apps";
private final String appSubscriptions = "/subscriptions";
private final String verifyToken = "AnyRandomVerifyToken";
// below are all the fields that can be subscribed for page object
private final String pageFields = "feed,ratings,name,picture,category,description,founded,company_overview,conversations,mission,products,general_info,location,hours,parking,public_transit,phone,email,website,attire,payment_options,culinary_team,general_manager,price_range,restaurant_services,restaurant_specialties,videos,release_date,genre,starring,screenplay_by,directed_by,produced_by,studio,awards,plot_outline,network,season,schedule,written_by,band_members,hometown,current_location,record_label,booking_agent,press_contact,artists_we_like,influences,band_interests,bio,affiliation,birthday,personal_info,personal_interests,members,built,features,mpg,checkins,productlists";
public static void main(String[] args)
{
new FacebookRealtimeSubscriber().subscribe();
}
private void subscribe()
{
String pageAccessToken = "";
String pageId = "";
client = new DefaultFacebookClient(Version.VERSION_2_3);
appAccessToken = client.obtainAppAccessToken(applicationId, appSecret);
client = new DefaultFacebookClient(userAccessToken, Version.VERSION_2_3);
Connection<Account> pages = client.fetchConnection("me/accounts", Account.class);
List<Account> accounts = pages.getData();
for (Account account : accounts)
{
if (pageName.equals(account.getName()))
{
pageAccessToken = account.getAccessToken();
pageId = account.getId();
}
}
client = new DefaultFacebookClient(pageAccessToken, appSecret, Version.VERSION_2_3);
// subscribe app for page
Object obj = client.publish(pageId + subscribedAppsEdge, JsonObject.class, Parameter.with("id", Long.valueOf(pageId)));
System.out.println(obj.toString());
// list subscriptions for app
obj = client.fetchObject(pageId + subscribedAppsEdge, JsonObject.class);
System.out.println(obj.toString());
// subscribe for page updates for app
client = new DefaultFacebookClient(appAccessToken.getAccessToken(), appSecret, Version.VERSION_2_3);
obj = client.publish(applicationId + appSubscriptions,
JsonObject.class,
Parameter.with("object", "page"),
Parameter.with("callback_url", callbackURL),
Parameter.with("fields", pageFields),
Parameter.with("verify_token", verifyToken));
System.out.println(obj);
// get subscriptions for app
obj = client.fetchObject(applicationId + appSubscriptions, JsonObject.class);
System.out.println(obj);
}
}

How to get all post id's of a specific page in facebook

I am extracting the post details of a facebook page. I extracted the json of a particular page and now I have to get id of all the posts of that page. How can I do it using facebook4j.
private static String readpage(Reader rd) throws IOException
{
StringBuilder sb = new StringBuilder();
int cp;
while ((cp = rd.read()) != -1)
{
sb.append((char) cp);
}
return sb.toString();
}
public static JSONObject readurl(String url) throws IOException, JSONException
{
InputStream is = new URL(url).openStream();
try
{
BufferedReader rd = new BufferedReader(new InputStreamReader
(is, Charset.forName("UTF-8")));
String jsonText = readpage(rd);
JSONObject json = new JSONObject(jsonText);
return json;
}
finally
{
is.close();
}
}
public static void main(String[] args) throws
IOException, JSONException, FacebookException
{
JSONObject json = readurl("https://graph.facebook.com/"+s);
}
You can obtain all the post related information of a particular page by referring the following code :
ResponseList<Post> results = facebook.getPosts(searchPost);
String userId = "";
for (Post post : results) {
obj.put("Post Id", post.getId());
obj.put("Post message", post.getMessage());
obj.put("No of likes on Post", post.getLikes().size());
obj.put("Post owner name:", post.getFrom().getName());
objArray = new JSONArray();
where obj is a JSON object.
PS:I am using eclipse kepler and facebook4j-core-2.0.2

Test Design: How to test a method properly without rewriting it completely?

I have the following class which contains a hard coded URL that never changes:
public class HttpClient {
private final String DOWNLOAD_URL = "http://original.url.json";
public String readJsonDataFromUrl() throws IOException {
URLConnection urlConnection = getUrlConnection();
BufferedReader reader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
StringBuffer content = new StringBuffer();
String readLine = "";
while ((readLine = reader.readLine()) != null) {
content.append(readLine);
}
return content.toString();
}
private URLConnection getUrlConnection() throws IOException {
URL jsonLocator = new URL(DOWNLOAD_URL);
return jsonLocator.openConnection();
}
}
Now imagine that I'd like to expect the IOException in my test. In my opinion, the only way to do that is to rewrite the complete class in a mock object because of the final variable:
public class HttpClientMock extends HttpClient {
private final String DOWNLOAD_URL = "http://wrong.test.url.json";
#Override
public String readJsonDataFromUrl() throws IOException {
URLConnection urlConnection = getUrlConnection();
BufferedReader reader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
StringBuffer content = new StringBuffer();
String readLine = "";
while ((readLine = reader.readLine()) != null) {
content.append(readLine);
}
return content.toString();
}
private URLConnection getUrlConnection() throws IOException {
URL jsonLocator = new URL(DOWNLOAD_URL);
URLConnection urlConnection = jsonLocator.openConnection();
return urlConnection;
}
}
But this is somehow far-fetched. If the original methods would be changed, the test results could still be positive because with this attempt, I don't actually test the original class anymore.
How can this be done properly? (I don't want to use a framework just for this one test, so are there any design attempts to solve this in a common way?)
Another spin on Gilbert Le Blanc's suggestion, is to make the HttpClient totally ignorant of the URL by injecting it through the constructor.
public class HttpClient {
private final String url;
public HttpClient(String url) { this.url = url; }
}
You can hard code the URL (or read from a config) somewhere externally to HttpClient and inject it wherever you instantiate the client. Then in your test it will be trivial to inject a bad url.
Thanks to everybody, but I think that Gilbert Le Blanc's solution is the most preferable for that case which looks like this:
The original class:
public class HttpClient {
private final String DOWNLOAD_URL = "http://my.original.json.url";
public String readJsonDataFromUrl() throws IOException {
URLConnection urlConnection = getUrlConnection();
BufferedReader reader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
StringBuffer content = new StringBuffer();
String readLine = "";
while ((readLine = reader.readLine()) != null) {
content.append(readLine);
}
return content.toString();
}
private URLConnection getUrlConnection() throws IOException {
URL jsonLocator = new URL(getConnectionString());
return jsonLocator.openConnection();
}
protected String getConnectionString() {
return DOWNLOAD_URL;
}
}
The mock object:
public class HttpClientMock extends HttpClient {
private String downloadUrl = "http://my.original.json.url";
public HttpClientMock() {
super();
}
public HttpClientMock(String downloadUrl) {
this.downloadUrl = downloadUrl;
}
#Override
protected String getConnectionString() {
return downloadUrl;
}
}
And the working tests:
public class HttpClientTest {
private JSONParser jsonParser = new JSONParser();
#Test
public void readJsonDataFromUrlSucceeds() throws IOException, ParseException {
HttpClient httpClient = new HttpClientMock();
String jsonString = httpClient.readJsonDataFromUrl();
JSONObject jsonObject = (JSONObject)jsonParser.parse(jsonString);
assertTrue(jsonObject.size() > 0);
}
#Test(expected = IOException.class)
public void readJsonDataFromMalformedUrlFails() throws IOException, ParseException {
HttpClient httpClient = new HttpClientMock("http://malformed");
httpClient.readJsonDataFromUrl();
}
}

commons httpclient - Adding query string parameters to GET/POST request

I am using commons HttpClient to make an http call to a Spring servlet. I need to add a few parameters in the query string. So I do the following:
HttpRequestBase request = new HttpGet(url);
HttpParams params = new BasicHttpParams();
params.setParameter("key1", "value1");
params.setParameter("key2", "value2");
params.setParameter("key3", "value3");
request.setParams(params);
HttpClient httpClient = new DefaultHttpClient();
httpClient.execute(request);
However when i try to read the parameter in the servlet using
((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest().getParameter("key");
it returns null. In fact the parameterMap is completely empty. When I manually append the parameters to the url before creating the HttpGet request, the parameters are available in the servlet. Same when I hit the servlet from the browser using the URL with queryString appended.
What's the error here? In httpclient 3.x, GetMethod had a setQueryString() method to append the querystring. What's the equivalent in 4.x?
Here is how you would add query string parameters using HttpClient 4.2 and later:
URIBuilder builder = new URIBuilder("http://example.com/");
builder.setParameter("parts", "all").setParameter("action", "finish");
HttpPost post = new HttpPost(builder.build());
The resulting URI would look like:
http://example.com/?parts=all&action=finish
If you want to add a query parameter after you have created the request, try casting the HttpRequest to a HttpBaseRequest. Then you can change the URI of the casted request:
HttpGet someHttpGet = new HttpGet("http://google.de");
URI uri = new URIBuilder(someHttpGet.getURI()).addParameter("q",
"That was easy!").build();
((HttpRequestBase) someHttpGet).setURI(uri);
The HttpParams interface isn't there for specifying query string parameters, it's for specifying runtime behaviour of the HttpClient object.
If you want to pass query string parameters, you need to assemble them on the URL yourself, e.g.
new HttpGet(url + "key1=" + value1 + ...);
Remember to encode the values first (using URLEncoder).
I am using httpclient 4.4.
For solr query I used the following way and it worked.
NameValuePair nv2 = new BasicNameValuePair("fq","(active:true) AND (category:Fruit OR category1:Vegetable)");
nvPairList.add(nv2);
NameValuePair nv3 = new BasicNameValuePair("wt","json");
nvPairList.add(nv3);
NameValuePair nv4 = new BasicNameValuePair("start","0");
nvPairList.add(nv4);
NameValuePair nv5 = new BasicNameValuePair("rows","10");
nvPairList.add(nv5);
HttpClient client = HttpClientBuilder.create().build();
HttpGet request = new HttpGet(url);
URI uri = new URIBuilder(request.getURI()).addParameters(nvPairList).build();
request.setURI(uri);
HttpResponse response = client.execute(request);
if (response.getStatusLine().getStatusCode() != 200) {
}
BufferedReader br = new BufferedReader(
new InputStreamReader((response.getEntity().getContent())));
String output;
System.out.println("Output .... ");
String respStr = "";
while ((output = br.readLine()) != null) {
respStr = respStr + output;
System.out.println(output);
}
This approach is ok but will not work for when you get params dynamically , sometimes 1, 2, 3 or more, just like a SOLR search query (for example)
Here is a more flexible solution. Crude but can be refined.
public static void main(String[] args) {
String host = "localhost";
String port = "9093";
String param = "/10-2014.01?description=cars&verbose=true&hl=true&hl.simple.pre=<b>&hl.simple.post=</b>";
String[] wholeString = param.split("\\?");
String theQueryString = wholeString.length > 1 ? wholeString[1] : "";
String SolrUrl = "http://" + host + ":" + port + "/mypublish-services/carclassifications/" + "loc";
GetMethod method = new GetMethod(SolrUrl );
if (theQueryString.equalsIgnoreCase("")) {
method.setQueryString(new NameValuePair[]{
});
} else {
String[] paramKeyValuesArray = theQueryString.split("&");
List<String> list = Arrays.asList(paramKeyValuesArray);
List<NameValuePair> nvPairList = new ArrayList<NameValuePair>();
for (String s : list) {
String[] nvPair = s.split("=");
String theKey = nvPair[0];
String theValue = nvPair[1];
NameValuePair nameValuePair = new NameValuePair(theKey, theValue);
nvPairList.add(nameValuePair);
}
NameValuePair[] nvPairArray = new NameValuePair[nvPairList.size()];
nvPairList.toArray(nvPairArray);
method.setQueryString(nvPairArray); // Encoding is taken care of here by setQueryString
}
}
This is how I implemented my URL builder.
I have created one Service class to provide the params for the URL
public interface ParamsProvider {
String queryProvider(List<BasicNameValuePair> params);
String bodyProvider(List<BasicNameValuePair> params);
}
The Implementation of methods are below
#Component
public class ParamsProviderImp implements ParamsProvider {
#Override
public String queryProvider(List<BasicNameValuePair> params) {
StringBuilder query = new StringBuilder();
AtomicBoolean first = new AtomicBoolean(true);
params.forEach(basicNameValuePair -> {
if (first.get()) {
query.append("?");
query.append(basicNameValuePair.toString());
first.set(false);
} else {
query.append("&");
query.append(basicNameValuePair.toString());
}
});
return query.toString();
}
#Override
public String bodyProvider(List<BasicNameValuePair> params) {
StringBuilder body = new StringBuilder();
AtomicBoolean first = new AtomicBoolean(true);
params.forEach(basicNameValuePair -> {
if (first.get()) {
body.append(basicNameValuePair.toString());
first.set(false);
} else {
body.append("&");
body.append(basicNameValuePair.toString());
}
});
return body.toString();
}
}
When we need the query params for our URL, I simply call the service and build it.
Example for that is below.
Class Mock{
#Autowired
ParamsProvider paramsProvider;
String url ="http://www.google.lk";
// For the query params price,type
List<BasicNameValuePair> queryParameters = new ArrayList<>();
queryParameters.add(new BasicNameValuePair("price", 100));
queryParameters.add(new BasicNameValuePair("type", "L"));
url = url+paramsProvider.queryProvider(queryParameters);
// You can use it in similar way to send the body params using the bodyProvider
}
Im using Java 8 and apache httpclient 4.5.13
HashMap<String, String> customParams = new HashMap<>();
customParams.put("param1", "ABC");
customParams.put("param2", "123");
URIBuilder uriBuilder = new URIBuilder(baseURL);
for (String paramKey : customParams.keySet()) {
uriBuilder.addParameter(paramKey, customParams.get(paramKey));
}
System.out.println(uriBuilder.build().toASCIIString()); // ENCODED URL
System.out.println(uriBuilder.build().toString); // NORMAL URL
Full example with DTO
public class HttpResponseDTO {
private Integer statusCode;
private String body;
private String errorMessage;
public Integer getStatusCode() {
return statusCode;
}
public void setStatusCode(Integer statusCode) {
this.statusCode = statusCode;
}
public String getBody() {
return body;
}
public void setBody(String body) {
this.body = body;
}
public String getErrorMessage() {
return errorMessage;
}
public void setErrorMessage(String errorMessage) {
this.errorMessage = errorMessage;
}
}
/**
*
* #param destinationURL
* #param params
* #param headers
* #return HttpResponseDTO
*/
public static HttpResponseDTO get(String baseURL, Boolean encodeURL, HashMap<String, String> params, HashMap<String, String> headers) {
final HttpResponseDTO httpResponseDTO = new HttpResponseDTO();
// ADD PARAMS IF
if (params != null && Boolean.FALSE.equals(params.isEmpty())) {
URIBuilder uriBuilder;
try {
uriBuilder = new URIBuilder(baseURL);
for (String paramKey : params.keySet()) {
uriBuilder.addParameter(paramKey, params.get(paramKey));
}
// CODIFICAR URL ?
if (Boolean.TRUE.equals(encodeURL)) {
baseURL = uriBuilder.build().toASCIIString();
} else {
baseURL = uriBuilder.build().toString();
}
} catch (URISyntaxException e) {
httpResponseDTO.setStatusCode(500);
httpResponseDTO.setErrorMessage("ERROR AL CODIFICAR URL: " + e.getMessage());
return httpResponseDTO;
}
}
// HACER PETICION HTTP
try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
final HttpGet get = new HttpGet(baseURL);
// ADD HEADERS
if (headers != null && Boolean.FALSE.equals(headers.isEmpty())) {
for (String headerKey : headers.keySet()) {
get.setHeader(headerKey, headers.get(headerKey));
}
}
try (CloseableHttpResponse response = httpClient.execute(get);) {
HttpEntity httpEntity = response.getEntity();
if (httpEntity != null) {
httpResponseDTO.setBody(EntityUtils.toString(httpEntity));
httpResponseDTO.setStatusCode(response.getStatusLine().getStatusCode());
}
} catch(Exception e) {
httpResponseDTO.setStatusCode(500);
httpResponseDTO.setErrorMessage(e.getMessage());
return httpResponseDTO;
}
} catch(Exception e) {
httpResponseDTO.setStatusCode(500);
httpResponseDTO.setErrorMessage(e.getMessage());
return httpResponseDTO;
}
return httpResponseDTO;
}

Categories