Crossdomain all from GAE - java

How to make a cross-domain call from GWT?
I found JSONPRequestBuilder as a solution, but it can only create GET request not POST. I am trying to call URL shortner service ("http://goo.gl/api/shorten") of google.

From servlet on GAE you can call external http services via URLFetch.
From client side GWT you can directly call Google Shortener API via gwt-google-apis. See the shortener example at the end of page.

Got it through URLFetch. Below is my code:
//Classes to import
import com.google.appengine.api.urlfetch.HTTPMethod;
import com.google.appengine.api.urlfetch.HTTPRequest;
import com.google.appengine.api.urlfetch.HTTPResponse;
import com.google.appengine.api.urlfetch.URLFetchService;
import com.google.appengine.api.urlfetch.URLFetchServiceFactory;
//Shortening download URL
URL url=new URL("http://goo.gl/api/shorten");
HTTPRequest req=new HTTPRequest(url,HTTPMethod.POST);
req.setPayload(("url=www.google.com").getBytes());
URLFetchService service = URLFetchServiceFactory.getURLFetchService();
HTTPResponse response = service.fetch(req);
byte[] content = response.getContent();
String urlshort=new String(content); //here is the JSON data from goo.gl

Related

How to capture response of a Bean shell sampler

Above is my code i have written to hit a web service whose endpoint is expecting a Byte Stream object.
I am able to do that but i am not getting any response.
I have to test the response.
Though i am getting 200 ok but a string is sent in response that i am not getting.
And the response is blank
How can I get the response ?
In order to read server's response you need to use URLConnection.getInputStream() method, not OutputStream
In order to convert stream to string you can use IOUtils.toString() method
In order to return data you can use return keyword
Minimal working code is below, adjust as per your needs:
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import org.apache.commons.io.IOUtils;
URL url = new URL("http://example.com");
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("GET");
String response = IOUtils.toString(con.getInputStream(), StandardCharsets.UTF_8);
return response;
Be aware of fact that JMeter is built on top of Apache HttpComponents so you can use the power of these libraries in order to create HTTP requests, see QuickStart wiki page to get ramped up in minutes
Be aware that starting from JMeter 3.1 it is recommended to use JSR223 Test Elements and Groovy language for scripting, check out Apache Groovy - Why and How You Should Use It for comprehensive explanation, benchmarks, code samples, etc.
You can add your output by using the SampleResult object:
String output = "...";
SampleResult.setResponseData( output );
SampleResult.setDataType( org.apache.jmeter.samplers.SampleResult.TEXT );

How do I send payload with GET call using JAX-RS client? [duplicate]

This question already has answers here:
HTTP GET with request body
(23 answers)
Closed 5 years ago.
I know that GET call should not have body but the call is developed by other people and I can't change it now. I want to consume an API which is GET method and takes payload (json body). I can consume a GET method passing path param but not payload. I don't see an option to send payload for GET call.
Here is the GET call I am doing.
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
Client client = ClientBuilder.newClient();
String targetUri = "http://" + service.getHost() + ":" + service.getPort() + PROFILES_URI;
Response response = client
.target(target)
.path(profileIds.get(0))
.request(MediaType.APPLICATION_JSON)
.get();
If the method is PUT or POST I can send the payload as shown below.
Client client = ClientBuilder.newClient();
String target = "http://" + service.getHost() + ":" + service.getPort() + PROFILES_URI;
Response response = client
.target(target)
.request(MediaType.APPLICATION_JSON)
.post(Entity.entity(profileIds, MediaType.APPLICATION_JSON));
How do I send payload with GET call?
Reference: http://www.baeldung.com/jersey-jax-rs-client
I am not developing a rest call here
Actually you are, because javax.ws.rs is the base package of RESTful web services in Java and javax.ws.rs.client.Client is the base interface for RESTfull web service clients: Overview of the Client API.
That being said you'll probably need to either build your own client that allows you to send a payload in a GET request or find an existent web service client with such capability.
The correctness of sending a body in a GET request is actually a different topic already discussed in this Q&A: HTTP GET with request body

Apache Http Client in Android

I'm trying to get the whole html from a web page in Android.
In java console aplication I used to do like this:
DefaultHttpClient httpclient = new DefaultHttpClient();
String busca = "kindle";
HttpGet httpGet = new HttpGet("http://www.amazon.com/s/ref=nb_sb_noss?url=search-alias%3Daps&field-keywords="+busca);
try {
ResponseHandler<String> manipulador = new BasicResponseHandler();
String resposta = httpclient.execute(httpGet,manipulador);
}
} finally {
httpGet.releaseConnection();
}
I tried to do the same in my Android aplication but I didn't work!
This library works in Android?
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
Is there in better way to get a page html code in a string on Android?
Thks for the help!
I did it with another URl and it worked :)
Maybe the HTML code of that page I was using as to big to save in a String or to show in a Text
You can have a loot at this :
HttpClient 4.0.1 - how to release connection?
HttpRequestBase.releaseConnection() is introduced in Version 4.2

How to send data from one webApplication to another

I have two web applications in two different server.I want send some data in header or request to other web application.How can I do that, please help me.
You can pass data by many means:
by making http request from your app:
URLConnection conn = new URL("your other web app servlet url").openConnection();
// pass data using conn. Then on other side you can have a servlet that will receive these calls.
By using JMS for asynchronous communication.
By using webservice (SOAP or REST)
By using RMI
By sharing database between the apps. So one writes to a table and the other reads from that table
By sharing file system file(s)...one writes to a file the other reads from a file.
You can use socket connection.
HttpClient can help
http://hc.apache.org/index.html
Apache HttpComponents
The Apache HttpComponents™ project is responsible for creating and
maintaining a toolset of low level Java components focused on HTTP and
associated protocols.
One web application is functioning as the client of the other. You can use the org.apache.http library to create your HTTP client code in Java. How you will do this depends on a couple of things:
Are you using http or https?
Does the application you are sending data to have a REST API?
Do you have a SOAP based web service?
If you have a SOAP based web service, then creating a Java client for it is very easy. If not, you could do something like this and test the code in a regular Java client before trying to run it in the web application.
import org.apache.http.client.utils.*;
import org.apache.http.*;
import org.apache.http.impl.client.*;
HttpClient httpclient = new DefaultHttpClient();
try {
URIBuilder builder = new URIBuilder();
builder.setHost("yoursite.com").setPath(/appath/rsc/);
builder.addParameter("user", username);
builder.addParameter("param1", "SomeData-sentAsParameter");
URI uri = builder.build();
HttpGet httpget = new HttpGet(uri);
HttpResponse response = httpclient.execute(httpget);
System.out.println(response.getStatusLine().toString());
if (response.getStatusLine().getStatusCode() == 200) {
String responseText = EntityUtils.toString(response.getEntity());
httpclient.getConnectionManager().shutdown();
} else {
log(Level.SEVERE, "Server returned HTTP code "
+ response.getStatusLine().getStatusCode());
}
} catch (java.net.URISyntaxException bad) {
System.out.println("URI construction error: " + bad.toString());
}

HTTP authentication with Apache HTTP Components: force sending of challenge

I need to talk to an obscure webserver which requires authentication. If I don't supply credentials, a login form is displayed. However, if I do supply unsolicited Basic Authentication credentials, I get directly to the desired content.
wget supports this directly:
# this fails and downloads a form:
wget https://weird.egg/data.txt --http-user=me --http-password=shhh
# this works and downloads the document:
wget https://weird.egg/data.txt --http-user=me --http-password=shhh --auth-no-challenge
Now my question: How can I make the download in Java using Apache's HTTP Components?
Here's what I got so far. (There's also a proxy in place, and I use -Y on in wget, and I have a matching https_proxy environment variable.)
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.conn.params.ConnRoutePNames;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import java.net.URI;
// ...
DefaultHttpClient hc = new DefaultHttpClient();
hc.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, new HttpHost(proxy_name, proxy_port));
URI uri = new URI("https://weird.egg/data.txt");
hc..getCredentialsProvider().setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT, AuthScope.ANY_REALM, AuthScope.ANY_SCHEME), new UsernamePasswordCredentials("me", "shh"));
hc.execute(new HttpGet(uri)); // etc
However, I only end up with the login form page, not the actual document. I'm suspecting that the DefaultHttpClient isn't sending the credentials unsolicited, in the way that wget does. Is there a way to make the Java program send the credentials?
Never mind. I solved the problem by not trying to use any library authentication methods, but just brute-forcing the Basic Authentication header into the request:
HttpGet get = new HttpGet(uri);
String basic_auth = new String(Base64.encodeBase64((username + ":" + password).getBytes()));
get.addHeader("Authorization", "Basic " + basic_auth);
hc.execute(get); // etc
(This needs the additional import org.apache.commons.codec.binary.Base64;, but in turn we can remove the credential-related imports.)

Categories