Google Cloud Print integration without webview - java

I use this tutorial to integrate my android application with Google Cloud Printer. It works fine, but I want do this without WebView.
I want to print with two steps:
Generate pdf file
Click button "Print" and submit print job
I shared my printer to anyone with link and want to print all pdf files from my application to my shared printer.
Can you share some code or tutorial?
Sorry for my english

I found this link and it helps me
ADD:
#Override
protected Void doInBackground(Void... params) {
try {
DefaultHttpClient httpclient = new DefaultHttpClient();
String user = "user#gmail.com";
String pass = "password";
String source = "Cloud%20Printing%20Test";
HttpGet authGet = new HttpGet(
"https://www.google.com/accounts/ClientLogin?accountType=HOSTED_OR_GOOGLE&Email="
+ user
+ "&Passwd="
+ pass
+ "&service=cloudprint&source=" + source);
HttpResponse httpResponse;
httpResponse = httpclient.execute(authGet);
String authResponse = EntityUtils
.toString(httpResponse.getEntity());
String authKey = authResponse.substring(authResponse
.indexOf("Auth=") + 5);
authKey = authKey.replace("\n", "");
MyLog.d(TAG, "Auth key: " + authKey);
HttpPost printPost = new HttpPost(
"https://www.google.com/cloudprint/submit?output=json");
printPost.setHeader("Authorization", "GoogleLogin auth=" + authKey);
printPost.setHeader("X-CloudPrint-Proxy", source);
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("printerid", "ID"));
nameValuePairs.add(new BasicNameValuePair("title", "TEST"));
nameValuePairs.add(new BasicNameValuePair("capabilities", "{capabilities=[]}"));
nameValuePairs.add(new BasicNameValuePair("content", "123"));
nameValuePairs.add(new BasicNameValuePair("contentType", "text/plain"));
printPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse printResponse = httpclient.execute(printPost);
String lol = EntityUtils.toString(printResponse.getEntity());
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
But now I can print only text. If i found solution how to print pdf - I'll post code here
ADD2:
This code send pdf files to print
File file = new File("file.pdf");
FileBody fb = new FileBody(file);
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
builder.addTextBody("printerid", "ID");
builder.addTextBody("title", "TEST2");
builder.addTextBody("capabilities", "{capabilities=[]}");
builder.addTextBody("contentType", "application/pdf");
builder.addPart("content", fb);
printPost.setEntity(builder.build());

Related

How to generate Access Token for Google Cloud API?

I tried the following way
public class GoogleOAuth2 {
String authURL = "https://accounts.google.com/o/oauth2/auth";
String tokenURL = "https://oauth2.googleapis.com/token";
public void execute() {
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost post = new HttpPost(tokenURL);
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("client_id",
"*********"));
params.add(new BasicNameValuePair("client_secret", "*****"));
params.add(new BasicNameValuePair("grant_type", "Authorization Code"));
params.add(new BasicNameValuePair("redirect_url", "https://localhost:8080"));
params.add(new BasicNameValuePair("scope", "https://www.googleapis.com/auth/cloud-platform"));
post.setEntity(new UrlEncodedFormEntity(params));
HttpResponse response = httpclient.execute(post);
String body = EntityUtils.toString(response.getEntity());
System.out.println(body);
} catch (Exception ex) {
System.out.println("Catched an error in Authenticating user : " + ex.getMessage());
}
}}
Now, this shows this error ,
(I have tried grant-type as Code,password,offline also)
{
"error": "unsupported_grant_type",
"error_description": "Invalid grant_type: Authorization Code"
}
What m i missing?
Can you please guide me to the right direction? I have Tried using Postman and i was able to get an access Token from here.

Writing from android program to localhost phpmyadmin

I have been solving this problem for 2 days now, but still nothing.
This is my code I use in my main activity:
public void InsertData(final String name, final String email){
class SendPostReqAsyncTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
String postReceiverUrl = "http://192.168.1.71/insert_data.php";
Log.d("Hello", "postURL: " + postReceiverUrl);
String NameHolder = name ;
String EmailHolder = email ;
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("name", NameHolder));
nameValuePairs.add(new BasicNameValuePair("email", EmailHolder));
try {
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(postReceiverUrl);
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
Log.d("come on man", "it works");
} catch (ClientProtocolException e) {
} catch (IOException e) {
}
return "Data Inserted Successfully";
}
When I run this code in my Emulator it works, but when I upload it to my Samsung S3 phone, it doesnt work. The data doesn't get pushed.
This is my insert_data.php
<?php
$hostname = "localhost";
$username = "-";
$password = "-";
$dbname = "test";
$con = mysqli_connect($hostname,$username,$password,$dbname);
$name = $_POST['name'];
$email = $_POST['email'];
$Sql_Query = "insert into GetDataTable (name,email) values ('$name','$email')";
if(mysqli_query($con,$Sql_Query)){
echo 'Data Submit Successfully';
}
else{
echo 'Try Again';
}
mysqli_close($con);
?>
I am wondering why this code doesn't work on my phone. I also tried using my localhost IP address instead of localhost in my PHP file, but still it wasn't working.
I have fixed the problem.
I had to go to my config file of Apache httpd.conf.
You have to search for the lines that look like this:
I have added line 192 and 193 myself, they weren't there in the beginning, thats what solved the problem.
Special thanks to #SISYN for hinting me about the "My first guess is your db doesn't allow external connections by default".

Call PHP function from android?

I want to call specific php function on server from Android application and also to send some parameters. Till now I achieved that I can open php file using HttpClient and executed data transfer to Json and show that in my app. So, now I want to be able to call specific function and send parameter to it, how can I do that??
Thanks.
Here is a piece of code I wrote for registering a new username using JSON:
public static boolean register(Context myContext, String name, String pwd) {
byte[] data;
HttpPost httppost;
StringBuffer buffer;
HttpResponse response;
HttpClient httpclient;
InputStream inputStream;
List<NameValuePair> nameValuePairs;
try {
httpclient = new DefaultHttpClient();
httppost = new HttpPost(
"http://X.X.X.X/register.php");
// Add your data
nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("User", name.trim()));
nameValuePairs.add(new BasicNameValuePair("Password", pwd.trim()));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
response = httpclient.execute(httppost);
inputStream = response.getEntity().getContent();
data = new byte[256];
buffer = new StringBuffer();
int len = 0;
while (-1 != (len = inputStream.read(data))) {
buffer.append(new String(data, 0, len));
}
inputStream.close();
}
catch (Exception e) {
Toast.makeText(myContext, "error" + e.toString(), Toast.LENGTH_LONG)
.show();
return false;
}
if (buffer.charAt(0) == 'Y') {
return true;
} else {
return false;
}
}
If you notice:
nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("User", name.trim()));
nameValuePairs.add(new BasicNameValuePair("Password", pwd.trim()));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
in that piece you can send parameters.
The method simply sends User and Password to the register.php.
If the User is already taken, 'N' is returned; otherwise creates the User and returns 'Y'.
On the server side, you treat them as POST information, so:
$user = $_POST['User'];
It should do for your case :)
Cheers!
Present or wrap-up those specific php functions with in a web-service together with your required parameters and call that web-service including the input parameters from your android to get things done.
You need to use WebServices for this work.
http://www.php.net/manual/en/book.soap.php

Android, Java: HTTP POST Request

I have to do a http post request to a web-service for authenticating the user with username and password. The Web-service guy gave me following information to construct HTTP Post request.
POST /login/dologin HTTP/1.1
Host: webservice.companyname.com
Content-Type: application/x-www-form-urlencoded
Content-Length: 48
id=username&num=password&remember=on&output=xml
The XML Response that i will be getting is
<?xml version="1.0" encoding="ISO-8859-1"?>
<login>
<message><![CDATA[]]></message>
<status><![CDATA[true]]></status>
<Rlo><![CDATA[Username]]></Rlo>
<Rsc><![CDATA[9L99PK1KGKSkfMbcsxvkF0S0UoldJ0SU]]></Rsc>
<Rm><![CDATA[b59031b85bb127661105765722cd3531==AO1YjN5QDM5ITM]]></Rm>
<Rl><![CDATA[username#company.com]]></Rl>
<uid><![CDATA[3539145]]></uid>
<Rmu><![CDATA[f8e8917f7964d4cc7c4c4226f060e3ea]]></Rmu>
</login>
This is what i am doing HttpPost postRequest = new HttpPost(urlString); How do i construct the rest of the parameters?
Here's an example previously found at androidsnippets.com (the site is currently not maintained anymore).
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.yoursite.com/script.php");
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("id", "12345"));
nameValuePairs.add(new BasicNameValuePair("stringdata", "AndDev is Cool!"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
So, you can add your parameters as BasicNameValuePair.
An alternative is to use (Http)URLConnection. See also Using java.net.URLConnection to fire and handle HTTP requests. This is actually the preferred method in newer Android versions (Gingerbread+). See also this blog, this developer doc and Android's HttpURLConnection javadoc.
to #BalusC answer I would add how to convert the response in a String:
HttpResponse response = client.execute(request);
HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream instream = entity.getContent();
String result = RestClient.convertStreamToString(instream);
Log.i("Read from server", result);
}
Here is an example of convertStramToString.
Please consider using HttpPost. Adopt from this: http://www.javaworld.com/javatips/jw-javatip34.html
URLConnection connection = new URL("http://webservice.companyname.com/login/dologin").openConnection();
// Http Method becomes POST
connection.setDoOutput(true);
// Encode according to application/x-www-form-urlencoded specification
String content =
"id=" + URLEncoder.encode ("username") +
"&num=" + URLEncoder.encode ("password") +
"&remember=" + URLEncoder.encode ("on") +
"&output=" + URLEncoder.encode ("xml");
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
// Try this should be the length of you content.
// it is not neccessary equal to 48.
// content.getBytes().length is not neccessarily equal to content.length() if the String contains non ASCII characters.
connection.setRequestProperty("Content-Length", content.getBytes().length);
// Write body
OutputStream output = connection.getOutputStream();
output.write(content.getBytes());
output.close();
You will need to catch the exception yourself.
I'd rather recommend you to use Volley to make GET, PUT, POST... requests.
First, add dependency in your gradle file.
compile 'com.he5ed.lib:volley:android-cts-5.1_r4'
Now, use this code snippet to make requests.
RequestQueue queue = Volley.newRequestQueue(getApplicationContext());
StringRequest postRequest = new StringRequest( com.android.volley.Request.Method.POST, mURL,
new Response.Listener<String>()
{
#Override
public void onResponse(String response) {
// response
Log.d("Response", response);
}
},
new Response.ErrorListener()
{
#Override
public void onErrorResponse(VolleyError error) {
// error
Log.d("Error.Response", error.toString());
}
}
) {
#Override
protected Map<String, String> getParams()
{
Map<String, String> params = new HashMap<String, String>();
//add your parameters here as key-value pairs
params.put("username", username);
params.put("password", password);
return params;
}
};
queue.add(postRequest);
Try HttpClient for Java:
http://hc.apache.org/httpclient-3.x/
You can reuse the implementation I added to ACRA:
http://code.google.com/p/acra/source/browse/tags/REL-3_1_0/CrashReport/src/org/acra/HttpUtils.java?r=236
(See the doPost(Map, Url) method, working over http and https even with self signed certs)
I used the following code to send HTTP POST from my android client app to C# desktop app on my server:
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.yoursite.com/script.php");
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("id", "12345"));
nameValuePairs.add(new BasicNameValuePair("stringdata", "AndDev is Cool!"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
I worked on reading the request from a C# app on my server (something like a web server little application).
I managed to read request posted data using the following code:
server = new HttpListener();
server.Prefixes.Add("http://*:50000/");
server.Start();
HttpListenerContext context = server.GetContext();
HttpListenerContext context = obj as HttpListenerContext;
HttpListenerRequest request = context.Request;
StreamReader sr = new StreamReader(request.InputStream);
string str = sr.ReadToEnd();
HTTP request POST in java does not dump the answer?
public class HttpClientExample
{
private final String USER_AGENT = "Mozilla/5.0";
public static void main(String[] args) throws Exception
{
HttpClientExample http = new HttpClientExample();
System.out.println("\nTesting 1 - Send Http POST request");
http.sendPost();
}
// HTTP POST request
private void sendPost() throws Exception {
String url = "http://www.wmtechnology.org/Consultar-RUC/index.jsp";
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(url);
// add header
post.setHeader("User-Agent", USER_AGENT);
List<NameValuePair> urlParameters = new ArrayList<>();
urlParameters.add(new BasicNameValuePair("accion", "busqueda"));
urlParameters.add(new BasicNameValuePair("modo", "1"));
urlParameters.add(new BasicNameValuePair("nruc", "10469415177"));
post.setEntity(new UrlEncodedFormEntity(urlParameters));
HttpResponse response = client.execute(post);
System.out.println("\nSending 'POST' request to URL : " + url);
System.out.println("Post parameters : " + post.getEntity());
System.out.println("Response Code : " +response.getStatusLine().getStatusCode());
BufferedReader rd = new BufferedReader(new
InputStreamReader(response.getEntity().getContent()));
StringBuilder result = new StringBuilder();
String line = "";
while ((line = rd.readLine()) != null)
{
result.append(line);
System.out.println(line);
}
}
}
This is the web: http://www.wmtechnology.org/Consultar-RUC/index.jsp,from you can consult Ruc without captcha. Your opinions are welcome!

Android: sending xml as document object, POST method

i am new at programming and i need some help with that please =/
web service is already written but not by me. so all i have to do is send xml as document object by post method through web service.
my code:
public class send extends application {
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://app.local/test/");
try {
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
Document document = documentBuilder.newDocument();
Element rootElement = document.createElement("packet");
rootElement.setAttribute("version", "1.2");
document.appendChild(rootElement);
Element em = document.createElement("imei");
em.appendChild(document.createTextNode("000000000000000"));
rootElement.appendChild(em);
em = document.createElement("username");
em.appendChild(document.createTextNode("5555"));
rootElement.appendChild(em);
HttpResponse response = httpclient.execute(httppost);
} catch (Exception e) {
System.out.println("XML Pasing Excpetion = " + e);
}
}
}
I am also very new in android programming. However, I solved those issued by using following way.
public void send(){
DefaultHttpClient httpClient = new DefaultHttpClient();
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("Servername", "abc"));
nameValuePairs.add(new BasicNameValuePair("UserName", "123));
nameValuePairs.add(new BasicNameValuePair("PassWord", "123"));
nameValuePairs.add(new BasicNameValuePair("XML", getRequestTypeStringBuilder()));
// Your every parameter name must be match with passing parameter, otherwise it throw
// an exception if it in case sensitive
HttpPost httpPost = new HttpPost("http://app.local/DeviceLogin/");
httpPost.addHeader("Accept", "text/xml");
httpPost.setHeader("Content-Type","application/xml;charset=UTF-8");
httpPost.setEntity(nameValuePairs);
HttpResponse response = httpClient.execute(httpPost);
// Be aware, if your return data type is also xml, then using replace empty string,
// otherwise, it my not retrieve or seen all data.
}
private static String getRequestTypeStringBuilder(){
StringBuilder body = new StringBuilder("<?xml version=\"1.0 \"encoding=\"UTF-8\"?>");
body.append("<!DOCTYPE My System\"Abc.dtd\">");
// Please append detail your xml body in here;
return body.toString();
}
Hope this may solve your issue
"May all being be happy"
Regards and Metta,
Ichirohang Limbu

Categories