google safe browsing lookup api code for java - java

i had some difficulties in programming and the meaning of the Request Body is confused. It always returns 400 response codes.Please help me.
String baseURL="https://sb-ssl.google.com/safebrowsing/api/lookup";
String arguments = "";
arguments+=URLEncoder.encode("client", "UTF-8")+"="+URLEncoder.encode("demo-app", "UTF-8")+"&";
arguments+=URLEncoder.encode("apikey", "UTF-8")+"="+URLEncoder.encode("apikey", "UTF-8")+"&";
arguments+=URLEncoder.encode("appver", "UTF-8")+"="+URLEncoder.encode("1.5.2", "UTF-8")+"&";
arguments+=URLEncoder.encode("pver", "UTF-8")+"="+URLEncoder.encode("3.0", "UTF-8")+"&";
arguments+=URLEncoder.encode("post_req_body", "UTF-8")+"="+URLEncoder.encode("2\nhttp://www.google.com\nhttp://www.facebook.com", "UTF-8");
String query = arguments;
System.out.println("Sending POST request - " + query);
// Construct the url object representing cgi script
URL url = new URL( baseURL );
// Get a URLConnection object, to write to POST method
URLConnection connect = url.openConnection();
// Specify connection settings
connect.setDoInput(true);
connect.setDoOutput(true);
// Get an output stream for writing
OutputStream output = connect.getOutputStream();
PrintStream pout = new PrintStream (output);
pout.print ( query );
pout.close();

Your request is wrong. If you use a POST request, then the parameters client, apikey, apiver and pver should be part of the URL.
The request body should only consist of the URLs to check (plus the number of URLS on the first line).
So it could look like this:
String baseURL="https://sb-ssl.google.com/safebrowsing/api/lookup";
String arguments = "";
arguments + =URLEncoder.encode("client", "UTF-8") + "=" + URLEncoder.encode("myapp", "UTF-8") + "&";
arguments + =URLEncoder.encode("apikey", "UTF-8") + "=" + URLEncoder.encode("12341234", "UTF-8") + "&";
arguments + =URLEncoder.encode("appver", "UTF-8") + "=" + URLEncoder.encode("1.5.2", "UTF-8") + "&";
arguments + =URLEncoder.encode("pver", "UTF-8") + "=" + URLEncoder.encode("3.0", "UTF-8");
// Construct the url object representing cgi script
URL url = new URL(baseURL + "?" + arguments);
// Get a URLConnection object, to write to POST method
URLConnection connect = url.openConnection();
// Specify connection settings
connect.setDoInput(true);
connect.setDoOutput(true);
// Get an output stream for writing
OutputStream output = connect.getOutputStream();
PrintStream pout = new PrintStream (output);
pout.print("2");
pout.println();
pout.print("http://www.google.com");
pout.println();
pout.print("http://www.facebook.com");
pout.close();

Related

Why all my https request are consider in server log as POST?

Why all my request methods (post,get,delete) are considered as POST method? if something wrong in the code can you explain what is the problem and how to fix it?
the method has a string parameter where I change it to post/delete/get
for all request I got https error code 405 but for post I got 200.
Thank you
my code -
well, Http-Code 405 means: Method Not Allowed => your server only implemented a POST method. Until you implement another methods on the server you will not be able to call them from your client.
I have fixed this, since POST method required the body while GET and DELETE do not need the body, for Authentication I used basicauth.
if (user_name != "" || password != "")
{
if (method == "POST")
{
// write body to query
String body = "username=" + user_name + "&password=" + password;
OutputStream os = connection.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
writer.write(body);
writer.flush();
writer.close();
os.close();
}
else
{
String userpass = user_name + ":" + password;
String basicAuth = "Basic " + new String(Base64.getEncoder().encode(userpass.getBytes()));
connection.setRequestProperty ("Authorization", basicAuth);
InputStream in = connection.getInputStream();
}
}
// connect
connection.connect();
//results
String results = request_call_results(connection);
JSONObject json = String_toJson(results);
return json;

Sending and receiving HTTP post data - Java

I'm trying to send a request through Google's Safe Browsing API, but I'm not getting any output and I'm not sure why. I've searched this online but each solution either only refers to only how to send or receive a POST request (but not both), or the input of data is done differently.
According to the Google Safe Browsing documentation:
Specify the queried URLs in the POST request body using the following format:
POST_REQ_BODY = NUM LF URL (LF URL)*
NUM = (DIGIT)+
URL = URL string following the RFC 1738
-
Response body:
POST_RESP_BODY = VERDICT (LF VERDICT)*
VERDICT = “phishing” | “malware” | "unwanted" | “phishing,malware” >| "phishing,unwanted" | "malware,unwanted" | "phishing, malware, unwanted" >| “ok”
and sent to:
https://sb-ssl.google.com/safebrowsing/api/lookup?client=CLIENT&key=APIKEY
I found another topic that shows how you send this request, but I'm not sure how to get/print out the response. Here is what I tried:
String baseURL="https://sb-ssl.google.com/safebrowsing/api/lookup";
String arguments = "";
arguments +=URLEncoder.encode("client", "UTF-8") + "=" + URLEncoder.encode("myapp", "UTF-8") + "&";
arguments +=URLEncoder.encode("apikey", "UTF-8") + "=" + URLEncoder.encode("12345", "UTF-8") + "&";
arguments +=URLEncoder.encode("appver", "UTF-8") + "=" + URLEncoder.encode("1.5.2", "UTF-8") + "&";
arguments +=URLEncoder.encode("pver", "UTF-8") + "=" + URLEncoder.encode("3.0", "UTF-8");
// Construct the url object representing cgi script
URL url = new URL(baseURL + "?" + arguments);
// Get a URLConnection object, to write to POST method
URLConnection connect = url.openConnection();
// Specify connection settings
connect.setDoInput(true);
connect.setDoOutput(true);
InputStream input = connect.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(input));
StringBuilder result = new StringBuilder();
String line;
// Get an output stream for writing
OutputStream output = connect.getOutputStream();
PrintStream pout = new PrintStream (output);
pout.print("2");
pout.println();
pout.print("http://www.google.com");
pout.println();
pout.print("http://www.facebook.com");
pout.close();
while((line = reader.readLine()) != null) {
result.append(line);
}
System.out.println(result.toString());
Where is the error?
Move these lines:
InputStream input = connect.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(input));
After pout.close();, the getInputStream method actually send the HTTP request to the server, in that example you are sending the request before you fill the body.
It looks like there will be other things to fix after this.

Passing value from applet to PHP

I want to send values of two variables to a PHP file from a Java applet), and I tried the following code.
try {
URL url = new URL(getCodeBase(),"abc.php");
URLConnection con = url.openConnection();
con.setDoOutput(true);
PrintStream ps = new PrintStream(con.getOutputStream());
ps.print("score="+score);
ps.print("username="+username);
con.getInputStream();
ps.close();
} catch (Exception e) {
g.drawString(""+e, 200,100);
}
I got the following error:
java.net.UnknownServiceException:protocol doesn't support output
java.net.UnknownServiceException:protocol doesn't support output
Means that you are using a protocol that doesn't support output.
getCodeBase() refers to a file url, so something like
file:/path/to/the/applet
The protocol is file, which doesn't support outout. You are looking for a http protocol, which supports output.
Maybe you wanted getDocumentBase(), which actually returns the web page where the applet is, i.e.
http://www.path.to/the/applet
Here's some code I used with my own applet, to send values (via POST) to a PHP script on my server:
I would use it like this:
String content = "";
content = content + "a=update&gid=" + gid + "&map=" + getMapString();
content = content + "&left_to_deploy=" + leftToDeploy + "&playerColor=" + playerColor;
content = content + "&uid=" + uid + "&player_won=" + didWin;
content = content + "&last_action=" + lastActionCode + "&appletID=" + appletID;
String result = "";
try {
result = requestFromDB(content);
System.out.println("Sending - " + content);
} catch (Exception e) {
status = e.toString();
}
As you can see, I am adding up all my values to send into a "content" string, then calling my requestFromDB method (which posts my "request" values, and returns the server's response) :
public String requestFromDB(String request) throws Exception
{
// This will accept a formatted request string, send it to the
// PHP script, then collect the response and return it as a String.
URL url;
URLConnection urlConn;
DataOutputStream printout;
DataInputStream input;
// URL of CGI-Bin script.
url = new URL ("http://" + siteRoot + "/globalconquest/applet-update.php");
// URL connection channel.
urlConn = url.openConnection();
// Let the run-time system (RTS) know that we want input.
urlConn.setDoInput (true);
// Let the RTS know that we want to do output.
urlConn.setDoOutput (true);
// No caching, we want the real thing.
urlConn.setUseCaches (false);
// Specify the content type.
urlConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
// Send POST output.
printout = new DataOutputStream (urlConn.getOutputStream ());
printout.writeBytes (request);
printout.flush ();
printout.close ();
// Get response data.
input = new DataInputStream (urlConn.getInputStream ());
String str;
String a = "";
while (null != ((str = input.readLine())))
{
a = a + str;
}
input.close ();
System.out.println("Got " + a);
if (a.trim().equals("1")) {
// Error!
mode = "error";
}
return a;
} // requestFromDB
In my PHP script, I would only need to look at $_POST for my values. Then I would just print a response.
Note! Your PHP script MUST be on the same server as the applet for security reasons, or this will not work.

Android use a SMS Gateway

I need to put in my android applicazion a tool that uses the free service for sending free sms through internet...
I saw that many apps are able to integrate these sevices..
I tried a lot but I have not found anything useful..
So I ask you ... how can I use the gateway of uthsms.net (for example) for send SMS with my Android application?
Sorry for the generic question..but I not found any starting point for resolve this question.
Thanks in advance
Use a Tool like Firebug to see what gets sent when you click the button on the website. I see that a POST-Request is done to uthsms.net with some parameters. You should be able to do the same POST with your app.
These are the parameter:
button: Send SMS
country: (some integer)
gateway: 0
hyderabad: your message
remLen: remaining length??
sindh: number to send sms to (without the +)
x: some integer
y: some integer
To send this POST-request in Android use following code:
URL url = new URL("http://uthsms.net");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
String data = URLEncoder.encode("button", "UTF-8") + "="
+ URLEncoder.encode("Send SMS", "UTF-8");
data += "&" + URLEncoder.encode("country", "UTF-8") + "="
+ URLEncoder.encode(country, "UTF-8");
data += "&" + URLEncoder.encode("gateway", "UTF-8") + "="
+ URLEncoder.encode("0", "UTF-8");
data += "&" + URLEncoder.encode("hyderabad", "UTF-8") + "="
+ URLEncoder.encode(message, "UTF-8");
data += "&" + URLEncoder.encode("remLen", "UTF-8") + "="
+ URLEncoder.encode(remLen, "UTF-8");
data += "&" + URLEncoder.encode("sindh", "UTF-8") + "="
+ URLEncoder.encode(number, "UTF-8");
data += "&" + URLEncoder.encode("x", "UTF-8") + "="
+ URLEncoder.encode("0", "UTF-8");
data += "&" + URLEncoder.encode("y", "UTF-8") + "="
+ URLEncoder.encode("0", "UTF-8");
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(
conn.getOutputStream());
wr.write(data);
wr.flush();
BufferedReader inStream = new BufferedReader(new InputStreamReader((conn.getInputStream())));
result = inStream.readLine();
inStream.close();
The result seems to be a html-document. Somewhere inside you should find the success message, or possible errors.
Try GoogleVoice API. It has documentation, which might help you get started.
Here's a link : https://code.google.com/p/google-voice-java/

How to access servlet and download attachment?

I have the following code snippet that tries to make an HTTP call to my servlet:
try {
// Construct data
String data = URLEncoder.encode("rpt_type", "UTF-8") + "=" + URLEncoder.encode(reportType, "UTF-8");
data += "&" + URLEncoder.encode("rpt_project", "UTF-8") + "=" + URLEncoder.encode(reportProject, "UTF-8");
data += "&" + URLEncoder.encode("rpt_mrv_creator", "UTF-8") + "=" + URLEncoder.encode(reportMrvCreator, "UTF-8");
data += "&" + URLEncoder.encode("rpt_gi_recipient", "UTF-8") + "=" + URLEncoder.encode(reportGiRecipient, "UTF-8");
data += "&" + URLEncoder.encode("rpt_plant", "UTF-8") + "=" + URLEncoder.encode(reportPlant, "UTF-8");
data += "&" + URLEncoder.encode("rpt_sloc", "UTF-8") + "=" + URLEncoder.encode(reportStorageLoc, "UTF-8");
data += "&" + URLEncoder.encode("rpt_gi_no", "UTF-8") + "=" + URLEncoder.encode(reportGiNo, "UTF-8");
data += "&" + URLEncoder.encode("date_sap_gi_fr", "UTF-8") + "=" + URLEncoder.encode(reportDateGiFrom, "UTF-8");
data += "&" + URLEncoder.encode("date_sap_gi_to", "UTF-8") + "=" + URLEncoder.encode(reportDateGiTo, "UTF-8");
data += "&" + URLEncoder.encode("rpt_partno", "UTF-8") + "=" + URLEncoder.encode(reportPartNo, "UTF-8");
data += "&" + URLEncoder.encode("rpt_so_no", "UTF-8") + "=" + URLEncoder.encode(reportSvcOrderNo, "UTF-8");
data += "&" + URLEncoder.encode("date_scan_fr", "UTF-8") + "=" + URLEncoder.encode(reportDateScanFrom, "UTF-8");
data += "&" + URLEncoder.encode("date_scan_to", "UTF-8") + "=" + URLEncoder.encode(reportDateScanTo, "UTF-8");
System.out.println("[data]\n" + data);
// Send data
String urlString = "http://localhost:8080/aerobook/GIStatusReportDownload?" + data;
System.out.println("[url] " + urlString);
URL url = new URL(urlString);
URLConnection conn = url.openConnection();
//conn.setDoOutput(true);
//OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
//wr.write(data);
//wr.flush();
// Get the response
BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
while ((line = rd.readLine()) != null) {
System.out.println(line);
}
//wr.close();
rd.close();
} catch (Exception e) {
}
My debug output:
[data]
rpt_type=d&rpt_project=aaa&rpt_mrv_creator=bbb&rpt_gi_recipient=ccc&rpt_plant=ddd&rpt_sloc=eee&rpt_gi_no=fff&date_sap_gi_fr=02%2F05%2F2012&date_sap_gi_to=03%2F05%2F2012&rpt_partno=ggg&rpt_so_no=hhh&date_scan_fr=26%2F05%2F2012&date_scan_to=31%2F05%2F2012
[url] http://localhost:8080/aerobook/GIStatusReportDownload?rpt_type=d&rpt_project=aaa&rpt_mrv_creator=bbb&rpt_gi_recipient=ccc&rpt_plant=ddd&rpt_sloc=eee&rpt_gi_no=fff&date_sap_gi_fr=02%2F05%2F2012&date_sap_gi_to=03%2F05%2F2012&rpt_partno=ggg&rpt_so_no=hhh&date_scan_fr=26%2F05%2F2012&date_scan_to=31%2F05%2F2012
On my servlet (in a separate file from the code above), I generate an Excel file for download:
res.setContentType(sContentType);
res.setHeader("Content-Disposition", "attachment;filename=\"" + sExcelFileName + "\"");
OutputStream oOutStrm = res.getOutputStream();
wbBook.write(oOutStrm);
oOutStrm.close();
My issue here is that from the URL generated by my code (as shown in the debug output above), I can access my servlet and I manage to get the Save-As dialog.
I'd like to get the contents of the file generated for use within my code. Is there any way I can get the attachment from my code, in byte stream or any other format?
Edit #3: Cleaned up the top
When you enter the URI into the browser, you are doing a GET request. Your client Java code however produces a POST request, and sends the parameters in the body, not the URI.
You may want to look at an HTTP trace and compare.
I want to get the contents of the excel file on my code, but so far it's not working.
I find no errors in the code.
I believe you want to convert content from input stream to an HSSFWorkbook object.
Following code snippet will help you on it.
java.net.URLConnection conn = url.openConnection();
java.io.InputStream is = conn.getInputStream();
org.apache.poi.hssf.usermodel.HSSFWorkbook workBook = new org.apache.poi.hssf.usermodel.HSSFWorkbook( is );
System.out.println( "Number of Sheets: " + workBook.getNumberOfSheets() );
org.apache.poi.hssf.usermodel.HSSFSheet sheet = workBook.getSheetAt( 0 );
System.out.println( "Sheet Name: " + sheet.getSheetName() );
// rest of your code to handle the captured workBook
// cheers
Check wbBook.write(oOutStrm); whether anything has been written into outputStream, also you need call oOutStrm.flash() before close it.
I doubt that the problem lies at OutputStream oOutStrm = res.getOutputStream();.
I bet res is HttpServletResponse and it returns a ServletOutputStream suitable for writing binary data in the response. The servlet container does not encode the binary data
Check API
So, You might not be getting anything except fileName.
In Servlet Try
FileOutputStream stream = new FileOutputStream("c:/excel/Book1.xls");
workBook.write(stream);

Categories