C2DM java example of third-part app - java

I'm trying to do example form: http://www.vogella.de/articles/AndroidCloudToDeviceMessaging/article.html
I've got everything allright with android app (I think), but to simulate the
server i all the time got error 403.
The code is the same like in example:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
public class AuthenticationUtil
{
private AuthenticationUtil()
{
}
public static String getToken(String email, String password)
throws IOException {
// Create the post data
// Requires a field with the email and the password
StringBuilder builder = new StringBuilder();
builder.append("Email=").append(email);
builder.append("&Passwd=").append(password);
builder.append("&accountType=GOOGLE");
builder.append("&source=CloudTut");
builder.append("&service=ac2dm");
// Setup the Http Post
byte[] data = builder.toString().getBytes();
URL url = new URL("https://www.google.com/accounts/ClientLogin");
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setUseCaches(false);
con.setDoOutput(true);
con.setRequestMethod("POST");
con.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
con.setRequestProperty("Content-Length", Integer.toString(data.length));
// Issue the HTTP POST request
OutputStream output = con.getOutputStream();
output.write(data);
output.close();
// Read the response
BufferedReader reader = new BufferedReader(new InputStreamReader(
con.getInputStream()));
String line = null;
String auth_key = null;
while ((line = reader.readLine()) != null) {
if (line.startsWith("Auth=")) {
auth_key = line.substring(5);
}
}
// Finally get the authentication token
// To something useful with it
return auth_key;
}
}
and the error respond:
Exception in thread "main" java.io.IOException: Server returned HTTP response code: 403 for URL: https://www.google.com/accounts/ClientLogin
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1436)
at sun.net.www.protocol.https.HttpsURLConnectionImpl.getInputStream(HttpsURLConnectionImpl.java:234)
at AuthenticationUtil.getToken(AuthenticationUtil.java:48)
at GetAuthenticationToken.main(GetAuthenticationToken.java:8)

This code is from a functioning app and works well for me. It uses the C2DM account login details to request an auth-token, which can then be used to send C2DM messages to client devices. Note that this code is from an Android app, but would typically be executed on the server.
public static String getClientLoginAuthToken() {
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost("https://www.google.com/accounts/ClientLogin");
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
nameValuePairs.add(new BasicNameValuePair("Email", "C2DMEMAILADDRESS));
nameValuePairs.add(new BasicNameValuePair("Passwd", "C2DMPASSWORD));
nameValuePairs.add(new BasicNameValuePair("accountType", "GOOGLE"));
nameValuePairs.add(new BasicNameValuePair("source", "Google-cURL-Example"));
nameValuePairs.add(new BasicNameValuePair("service", "ac2dm"));
post.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = client.execute(post);
BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
String line = "";
while ((line = rd.readLine()) != null) {
Trace.e("HttpResponse", line);
if (line.startsWith("Auth=")) {
return line.substring(5);
}
}
} catch (IOException e) {
e.printStackTrace();
}
Trace.e(TAG, "Failed to get C2DM auth code");
return "";
}
If you continue to have problems, then best to assume the C2DM account wasn't set up right, and create another one.

Related

How to consume liferay web service written in liferay from java client?

I have web service written in Liferay. I want to get data in Java Client that is running on a separate machine.how can i do this?
I have tried this but i am getting following error
{"message":"Authenticated access required","exception":"java.lang.SecurityException"}
My Code is below
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
public class JavaClient {
// http://localhost:8080/RESTfulExample/json/product/get
public static void main(String[] args)
{
try
{
// URL url = new
// URL("http://localhost:8080/api/jsonws/us-pharmacy-ui-portlet.ph_fax/get-documents-to-fax
// \-u test#liferay.com:test");
HttpURLConnection conn = (HttpURLConnection) getURL().openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("Accept", "application/json");
if(conn.getResponseCode() != 200){ throw new RuntimeException("Failed : HTTP error code : " + conn.getResponseCode()); }
BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream())));
String output;
System.out.println("Output from Server .... \n");
while ((output = br.readLine()) != null)
{
System.out.println(output);
}
conn.disconnect();
}
catch (MalformedURLException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
}
private static URL getURL() throws MalformedURLException
{
String url = "http://localhost:8080";
String screenName = "shahid.rana";
String password = "123";
int pos = url.indexOf("://");
String protocol = url.substring(0, pos + 3);
String host = url.substring(pos + 3, url.length());
StringBuilder sb = new StringBuilder();
sb.append(protocol);
sb.append(screenName);
sb.append(":");
sb.append(password);
sb.append("#");
sb.append(host);
sb.append("/api/jsonws/us-pharmacy-ui-portlet.ph_fax/get-documents-to-fax/");
// sb.append(serviceName);
System.out.println("sb.toString()" + sb.toString());
return new URL(sb.toString());
}
}
Yes, you will get this error because Liferay Web services needs basic Auth.
you need to set test#liferay.com & whatever-password in base64 & pass it along.
Example code using HttpClient
HttpHost targetHost = new HttpHost("localhost", 8080, "http");
DefaultHttpClient httpclient = new DefaultHttpClient();
BasicHttpContext ctx = new BasicHttpContext();
// Plugin Context Use for Liferay 6.1
HttpPost post = new HttpPost("/api/jsonws/country/get-countries");
Base64 b = new Base64();
String encoding = b.encodeAsString(new String("test#liferay.com:test").getBytes());
post.setHeader("Authorization", "Basic " + encoding);
List<NameValuePair> params = new ArrayList<NameValuePair>();
//params.add(new BasicNameValuePair("emplyeeId", "30722"));
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(params, "UTF-8");
post.setEntity(entity);
HttpResponse resp = httpclient.execute(targetHost, post, ctx);
resp.getEntity().writeTo(System.out);
httpclient.getConnectionManager().shutdown();
}
Please note
String encoding = b.encodeAsString(new String("test#liferay.com:test").getBytes());
post.setHeader("Authorization", "Basic " + encoding);

no response from HttpGet client.execute(request) after initial login was successful

I'm trying to log into this site and collect some data.
I removed the username and password from the code i shared below, but when it takes the first url and password and runs i get a response showing me that the login was successful, however after saving the cookies and trying to run the second link with the query for the site it just hangs. no errors and no response. I played for hours but just cant get it. Its getting stuck at the client.execute(request) thats running with this link (http :// sef.imapp. com/ilinks/property?upin=US120860131120280120&report=comps&distance=0.5)
I copied the code from http://www.mkyong.com/java/apache-httpclient-examples/ (Part 3) and made changes until i got the response html page showing logged in, but I just cant run the query url.
I appreciate any help to be explained in detail.
Thank you.
package connectors;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.CookieHandler;
import java.net.CookieManager;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicNameValuePair;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
public class HttpCilentExampleToMls {
private String cookies;
private HttpClient client = HttpClientBuilder.create().build();
private final String USER_AGENT = "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.36 Safari/537.36";
public static void main(String[] args) throws Exception {
//Login page Changed from google address
String url = "http://sef.imapp.com/ilinks/search";
//Search page Changed from gmail address
String mlsUrl = "http://sef.imapp.com/ilinks/property?upin=US120860131120280120&report=comps&distance=0.5";
// make sure cookies is turn on
CookieHandler.setDefault(new CookieManager());
HttpCilentExampleToMls http = new HttpCilentExampleToMls();
String page = http.GetPageContent(url);
List<NameValuePair> postParams =
// Changed from "Username" and "Password"
http.getFormParams(page, "Username","Password");
http.sendPost(url, postParams);
String result = http.GetPageContent(mlsUrl);
}
private void sendPost(String url, List<NameValuePair> postParams)
throws Exception {
HttpPost post = new HttpPost(url);
// add header
post.setHeader("Host", "sef.imapp.com");
post.setHeader("User-Agent", USER_AGENT);
post.setHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
post.setHeader("Accept-Language", "en-US,en;q=0.8");
post.setHeader("Cookie", getCookies());
post.setHeader("Connection", "Keep-Alive");
post.setHeader("Referer", "http://sef.imapp.com/ilinks/login?logout=true");
post.setHeader("Content-Type", "application/x-www-form-urlencoded");
post.setEntity(new UrlEncodedFormEntity(postParams));
HttpResponse response = client.execute(post);
int responseCode = response.getStatusLine().getStatusCode();
System.out.println("\nSending 'POST' request to URL : " + url);
System.out.println("Post parameters : " + postParams);
System.out.println("Response Code : " + responseCode);
BufferedReader rd = new BufferedReader(
new InputStreamReader(response.getEntity().getContent()));
StringBuffer result = new StringBuffer();
String line = "";
while ((line = rd.readLine()) != null) {
result.append(line);
System.err.println(line);
}
// System.out.println(result.toString());
}
private String GetPageContent(String url) throws Exception {
HttpGet request = new HttpGet(url);
request.setHeader("User-Agent", USER_AGENT);
request.setHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
request.setHeader("Accept-Language", "en-US,en;q=0.8");
HttpResponse response = client.execute(request);
int responseCode = response.getStatusLine().getStatusCode();
System.out.println("\nSending 'GET' request to URL : " + url);
System.out.println("Response Code : " + responseCode);
BufferedReader rd = new BufferedReader(
new InputStreamReader(response.getEntity().getContent()));
StringBuffer result = new StringBuffer();
String line = "";
while ((line = rd.readLine()) != null) {
result.append(line);
}
// set cookies
setCookies(response.getFirstHeader("Set-Cookie") == null ? "" :
response.getFirstHeader("Set-Cookie").toString());
return result.toString();
}
public List<NameValuePair> getFormParams(
String html, String username, String password)
throws UnsupportedEncodingException {
System.out.println("Extracting form's data...");
Document doc = Jsoup.parse(html);
// Google form id
Element loginform = doc.getElementById("standardLogin");
Elements inputElements = loginform.getElementsByTag("input");
List<NameValuePair> paramList = new ArrayList<NameValuePair>();
for (Element inputElement : inputElements) {
String key = inputElement.attr("name");
String value = inputElement.attr("value");
if (key.equals("user"))
value = username;
else if (key.equals("passwd"))
value = password;
paramList.add(new BasicNameValuePair(key, value));
}
return paramList;
}
public String getCookies() {
return cookies;
}
public void setCookies(String cookies) {
this.cookies = cookies;
}
}
I had the same problem trying exactly the code at mkyong and a comment from the website solved it: after using HttpGet or HttpPost objects, use the method releaseConnection() in them.
Alex Loginov • 8 months ago Hi, might be helpful for someone: after
you receive the response, please close HttpPost (HttpGet) :
post.releaseConnection(); Else after 2 times you will have no free
connections and will have to wait infinitely for them to release - no
exception will be thrown.

How to build RESTful request over in java

I tried to understand how to send REST request to server. If I have to implement this as a request in java using httpconnections or any other connections, how would I do that?
POST /resource/1
Host: myownHost
DATE: date
Content-Type: some standard type
How should this be structured in a standard way?
URL url= new URL("http://myownHost/resource/1");
HttpsURLConnection connect= (HttpsURLConnection) url.openConnection();
connect.setRequestMethod("POST");
connect.setRequestProperty("Host", "myOwnHost");
connect.setRequestProperty("Date","03:14:15 03:14:15 GMT");
connect.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
There are many options, Apache HTTP client (http://hc.apache.org/httpcomponents-client-4.4.x/index.html) is one of them (and makes things very easy)
Creating REST requests can be as easy as this (using JSON in this case):
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet getRequest = new HttpGet(
"http://localhost:8080/RESTfulExample/json/product/get");
getRequest.addHeader("accept", "application/json");
HttpResponse response = httpClient.execute(getRequest);
if (response.getStatusLine().getStatusCode() != 200) {
throw new RuntimeException("Failed : HTTP error code : "
+ response.getStatusLine().getStatusCode());
}
BufferedReader br = new BufferedReader(
new InputStreamReader((response.getEntity().getContent())));
Update: Sorry the link to the documentation was updated.Posted the new one.
you should use json here
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
public class NetClientPost {
// http://localhost:8080/RESTfulExample/json/product/post
public static void main(String[] args) {
try {
URL url = new URL("http://myownHost/resource/1");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json");
String input = "{\"DATE\":\"03:14:15 03:14:15 GMT\",\"host\":\"myownhost\"}";
OutputStream os = conn.getOutputStream();
os.write(input.getBytes());
os.flush();
if (conn.getResponseCode() != HttpURLConnection.HTTP_CREATED) {
throw new RuntimeException("Failed : HTTP error code : "
+ conn.getResponseCode());
}
BufferedReader br = new BufferedReader(new InputStreamReader(
(conn.getInputStream())));
String output;
System.out.println("Output from Server .... \n");
while ((output = br.readLine()) != null) {
System.out.println(output);
}
conn.disconnect();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
more over it browse link
There are several ways to call a RESTful service with Java but it's not required to use raw level APIs ;-)
It exists some RESTful frameworks like Restlet or JAX-RS. They address both client and server side and aim to hide the technical plumbing of such calls. Here is a sample of code describing how to do your processing with Restlet and a JSON parser:
JSONObject jsonObj = new JSONObject();
jsonObj.put("host", "...");
ClientResource cr = new Client("http://myownHost/resource/1");
cr.post(new JsonRepresentation(jsonObject);
// In the case of form
// Form form = new Form ();
// form.set("host", "...");
// cr.post(form);
You can notice that in the previous snippet, headers Content-type, Date are automatically set for you based on what you sent (form, JSON, ...)
Otherwise a small remark, to add an element you should use a method POST on the element list resource (http://myownHost/resources/) or a method PUT if you have the unique identifier you want to use to identify it (http://myownHost/resources/1). This link could be useful to you: https://templth.wordpress.com/2014/12/15/designing-a-web-api/.
Hope it helps you,
Thierry

Posting data in raw format to PHP file and getting response

I am making an android application where I need to send some data collected from a data to server php file using post data and get the echoed text from the php file and display it. I have the post variables in this format -> "name=xyz&home=xyz" and so on. I am using the following class to post, but the php file on the server does not get the post vars. Can someone please tell me whats wrong or any other ways to do what I am trying to do?
package xxx.xxx.xxx;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class NetUtil {
public static String UrlToString(String targetURL, String urlParameters)
{
URL url;
HttpURLConnection connection = null;
try {
//Create connection
url = new URL(targetURL);
connection = (HttpURLConnection)url.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
connection.setRequestProperty("Content-Length", "" +
Integer.toString(urlParameters.getBytes().length));
connection.setRequestProperty("Content-Language", "en-US");
connection.setUseCaches (false);
connection.setDoInput(true);
connection.setDoOutput(true);
//Send request
DataOutputStream wr = new DataOutputStream (
connection.getOutputStream ());
wr.write(urlParameters.getBytes("UTF-8"));
wr.flush ();
//Get Response
InputStream is = connection.getInputStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
String line;
StringBuffer response = new StringBuffer();
while((line = rd.readLine()) != null) {
response.append(line);
response.append('\r');
}
rd.close();
return response.toString();
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
if(connection != null) {
connection.disconnect();
}
}
}
}
I get a response from php file, but the php file does not get the post data.
The example looks okay to me for a beginner. Only the following springs out:
connection.setRequestProperty("Content-Length", "" +
Integer.toString(urlParameters.getBytes().length));
and
wr.write(urlParameters.getBytes("UTF-8"));
In the first you're converting chars to bytes using platform default encoding. The resulting length is not necessarily the same as when using UTF-8 encoding to convert chars to bytes as you did when writing the request body. So the chance exist that the Content-Length header is off from the actual content length. To fix this, you should be using the same charset on the both calls.
But I believe that PHP isn't really that strict when parsing the request body so that you would get nothing in the PHP end. Probably the urlParameters is not in proper format. Are they really URL-encoded?
Anyway, did you try it with Android's builtin HttpClient API? It should be as simple as follows:
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(targetURL);
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("name", "xyz"));
params.add(new BasicNameValuePair("home", "xyz"));
post.setEntity(new UrlEncodedFormEntity(params));
HttpResponse response = client.execute(post);
InputStream input = response.getEntity().getContent();
// ...
If that doesn't work as well, then the mistake is likely in the PHP side.

Https request, authentication in Android

I am currently trying to authenticate with a server via a http Get call. The code provided below works when compiled in a java project. Returning the correct token to the program. However whenever I try to implement the same code in Android I do not get a token returned via the Get call.
In Android I am returning inputLine in a function, however inputLine is always an empty string.
The system.out.println() prints the returned token.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import javax.net.ssl.HttpsURLConnection;
public class JavaHttpsExample
{
public static void main(String[] args)
{ String inputLine = new String();
try
{
String httpsURL = "https://the url";
URL myurl = new URL(httpsURL);
HttpsURLConnection con = (HttpsURLConnection)myurl.openConnection();
InputStream ins = con.getInputStream();
InputStreamReader isr=new InputStreamReader(ins);
BufferedReader in =new BufferedReader(isr);
inputLine = in.readLine();
System.out.println(inputLine);
in.close();
}
catch(IOException e)
{
e.printStackTrace();
}
}
}
thanks for your help!!!
You probably did not add the Internet-Permission to your projects AndroidManifest.xml.
If so, add the following line as a child of the <manifest/> node:
<uses-permission android:name="android.permission.INTERNET" />
I'm using POST and FormEntity for retrieving data from the server (such as authentication), and i have never had any problems:
final String httpsURL = "https://the url";
final DefaultHttpClient client = new DefaultHttpClient();
final HttpPost httppost = new HttpPost(httpsURL);
//authentication block:
final List<BasicNameValuePair> nvps = new ArrayList<BasicNameValuePair>();
nvps.add(new BasicNameValuePair("userName", userName));
nvps.add(new BasicNameValuePair("password", password));
final UrlEncodedFormEntity p_entity = new UrlEncodedFormEntity(nvps, HTTP.UTF_8);
httppost.setEntity(p_entity);
//sending the request and retrieving the response:
HttpResponse response = client.execute(httppost);
HttpEntity responseEntity = response.getEntity();
//handling the response: responseEntity.getContent() is your InputStream
final InputSource inputSource = new InputSource(responseEntity.getContent());
[...]
maybe you'll find this usefull

Categories

Resources