I am trying to write the following section of php code in java. I will provide the php code and the java code. What I would like help with is a) am I even on the right track and b) the line with the "Please help here" comment, I am unsure of how to do this in java. This line is header("Location: ".$strCitiRedirectURL.$content."");
Thank you in advance.
php code:
$req =& new HTTP_Request($strCitiLoginURL);
$req->setMethod(HTTP_REQUEST_METHOD_POST);
$req->addPostData("instusername", $strInstUsername);
$req->addPostData("institution", $strInstitution);
$req->addPostData("key", $strInstitutionKey);
$req->addPostData("type", "returning");
$response = $req->sendRequest();
if(isset($_GET['showDebug'])){
print $req->_buildRequest();
}
if (PEAR::isError($response)) {
$content = $response->getMessage();
} else {
$content = $req->getResponseBody();
}
/* Check for 44 Character UUID */
if (preg_match($pattern,$content)){
print 'Success';
ob_start();
header("Location: ".$strCitiRedirectURL.$content."");
ob_flush();
/* No UUID. Login to CITI failed. We may need a new user */
}elseif ($content == "- error: learner not affiliated with institution, add learner or provide username and password"){
// Resubmit as a new user
/* Package data up to post to CITI */
$req =& new HTTP_Request($strCitiLoginURL);
$req->setMethod(HTTP_REQUEST_METHOD_POST);
$req->addPostData("instusername", $strInstUsername);
$req->addPostData("institution", $strInstitution);
$req->addPostData("key", $strInstitutionKey);
$req->addPostData("type", "new");
$req->addPostData("first", $strFirst);
$req->addPostData("last", $strLast);
$req->addPostData("email", $strEmail);
$response = $req->sendRequest();
if(isset($_GET['showDebug'])){
print $req->_buildRequest();
}
if (PEAR::isError($response)) {
$content = $response->getMessage();
} else {
$content = $req->getResponseBody();
}
/* Check for 44 Character UUID */
if (preg_match($pattern,$content)){
print 'Success';
ob_start();
/*PLEASE HELP ON THIS LINE*/ header("Location: ".$strCitiRedirectURL.$content."");
ob_flush();
}else{
$errMsg = $errMsg.' <li>CITI Error Returned: '.$content.'.</li>';
}
java code
//****CITI CONFIGURATION****
final String pattern = "([0-9A-\\-]{44})";
final String CitiRedirectUrl = "https://www.citiprogram.org/members/mainmenu.asp?strKeyID=";
final String CitiLoginUrl = "http://www.citiprogram.org/remoteloginII.asp";
//****END CITI CONFIGURATION****
try {
// Construct data
String data = URLEncoder.encode("instusername", "UTF-8") + "=" + URLEncoder.encode(c_form.getCan(), "UTF-8");
data += "&" + URLEncoder.encode("institution", "UTF-8") + "=" + URLEncoder.encode("value2", "UTF-8");
data += "&" + URLEncoder.encode("key", "UTF-8") + "=" + URLEncoder.encode("value2", "UTF-8");
data += "&" + URLEncoder.encode("type", "UTF-8") + "=" + URLEncoder.encode("returning", "UTF-8");
// Send data
URL url = new URL("http://www.citiprogram.org/remoteloginII.asp");
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);
if (pregMatch(pattern, line)) {
//Do the header part from the php code
} else if (line.equals("- error: learner not affiliated with institution, add learner or provide username and password")) {
// Resubmit as a new user
/* Package data up to post to CITI */
// Construct data
String newdata = URLEncoder.encode("instusername", "UTF-8") + "=" + URLEncoder.encode(c_form.getCan(), "UTF-8");
newdata += "&" + URLEncoder.encode("institution", "UTF-8") + "=" + URLEncoder.encode("value2", "UTF-8");
newdata += "&" + URLEncoder.encode("key", "UTF-8") + "=" + URLEncoder.encode("value2", "UTF-8");
newdata += "&" + URLEncoder.encode("type", "UTF-8") + "=" + URLEncoder.encode("returning", "UTF-8");
// Send data
OutputStreamWriter newwr = new OutputStreamWriter(conn.getOutputStream());
newwr.write(data);
newwr.flush();
// Get the response
BufferedReader newrd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String newline;
while ((newline = newrd.readLine()) != null) {
System.out.println(newline);
if (pregMatch(pattern, newline)) {
} else {
//Print error message
}
}
}
}
wr.close();
rd.close();
} catch (Exception e) {
}
//Check for 44 character UUID
public static boolean pregMatch(String pattern, String content) {
Pattern p = Pattern.compile(pattern);
Matcher m = p.matcher(content);
boolean b = m.matches();
return b;
}
I believe
header("Location: ".$strCitiRedirectURL.$content."");
in PHP would be the same as the following in Java (using your wr object):
wr.sendRedirect("http://path.to.redirect/");
You could also forward the request, but I have a feeling you just want the client to redirect to citirewards or whatever, in which case sendRedirect is the solution.
EDIT: Source - http://docs.oracle.com/javaee/1.3/api/javax/servlet/http/HttpServletResponse.html#sendRedirect(java.lang.String)
Related
I have an activity where the user enters his / her name, username, and password. I want to send this information as an entry in a MySQL database. Here is my code:
protected String doInBackground(String... params) {
String reg_url = "http://MyIPAddress:ServerPort#/Register.php";
String name = params[1];
String user_name = params[2];
String user_pass = params[3];
try {
URL url = new URL(reg_url);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true);
OutputStream OS = httpURLConnection.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(OS, "UTF-8"));
String data = URLEncoder.encode("user", "UTF-8") + "=" + URLEncoder.encode(name, "UTF-8") + "&" +
URLEncoder.encode("user_name", "UTF-8") + "=" + URLEncoder.encode(user_name, "UTF-8") + "&" +
URLEncoder.encode("user_pass", "UTF-8") + "=" + URLEncoder.encode(user_pass, "UTF-8");
bufferedWriter.write(data);
bufferedWriter.flush();
bufferedWriter.close();
OS.close();
return "Registration Success!";
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
The code runs without any errors, but the database remains empty after the program is executed. Here is my PHP file (Register.php):
<?php
require "Connection.php"; //Establishes connection to database
$name = $_POST["user"];
$user_name = $_POST["user_name"];
$user_pass = $_POST["user_pass"];
$sql_query = "insert into user_info values('$name','$user_name','$user_pass');";
if (mysqli_real_query($link, $sql_query)) {
echo "<h1> Data Insertion Success! </h1>";
}
else {
echo "Data Insertion Error...";
}
?>
And the code to connect to the database (Connection.php):
<?php
$link = mysqli_init();
$success = mysqli_real_connect($link,$host,$user,$password,$db,$port);
if($success) {
echo "<h1> Success! </h1>";
}
else {
echo "Error...".mysqli_connect_error();
}
?>
Am I missing something here? I would gladly appreciate your help. Thanks!
Here's the code I ended up using to send the data to my database within the doInBackground method:
try{
String data = URLEncoder.encode("user", "UTF-8") + "=" + URLEncoder.encode(name, "UTF-8") + "&" +
URLEncoder.encode("user_name", "UTF-8") + "=" + URLEncoder.encode(user_name, "UTF-8") + "&" +
URLEncoder.encode("user_pass", "UTF-8") + "=" + URLEncoder.encode(user_pass, "UTF-8");
URL url = new URL(reg_url);
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(data);
wr.flush();
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuilder sb = new StringBuilder();
String line;
// Read Server Response
while((line = reader.readLine()) != null)
{
sb.append(line);
break;
}
Log.e("TAG", sb.toString());
return sb.toString();
}catch(Exception e){
return new String("Exception: " + e.getMessage());
}
Reference: Android login to mysql database
Also turned out the port number I had entered for my server was incorrect. I fixed that as well, and now everything seems to work fine. Thank you to all of you guys for the help!
i'm devoloping an Android app. For the signin i need to send a database the data, but when i try to use $_POST array after the encode it seems be empty (i've tried to print the response, and i think this is my problem).
Here is the javacode inside my app:
private String register (String username, String password, String number) {
String reg_url = "myDomain/register.php";
try {
URL url = new URL(reg_url);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true);
httpURLConnection.setRequestProperty("Accept-Charset", "UTF-8");
httpURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
OutputStream OS = httpURLConnection.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(OS, "UTF-8"));
String data = URLEncoder.encode("username", "UTF-8") + " = " + URLEncoder.encode(username, "UTF-8") + "&" +
URLEncoder.encode("password", "UTF-8") + " = " + URLEncoder.encode(password, "UTF-8") + "&" +
URLEncoder.encode("number", "UTF-8") + " = " + URLEncoder.encode(number, "UTF-8");
bufferedWriter.write(data);
bufferedWriter.flush();
bufferedWriter.close();
OS.close();
InputStream IS = httpURLConnection.getInputStream();
BufferedReader bufferedReader= new BufferedReader(new InputStreamReader(IS,"iso-8859-1"));
String response = "";
String line;
while ((line = bufferedReader.readLine())!=null) response += line ;
Log.i("Response", response);
IS.close();
bufferedReader.close();
if (!response.toLowerCase().contains("fail"))
return Language.registered;
else
return Language.aProblemOccurred;
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
return Language.aProblemOccurred;
} catch (IOException e) {
e.printStackTrace();
return Language.aProblemOccurred;
}
}
And this is the simple php code of the registration:
<?php
require "init.php";
$username = $_POST["username"];
$password = $_POST["password"];
$number = $_POST["number"];
$mpt = "1";
$sql_query = "insert into Users values( '$mpt' , '$number' , '$username' , '$password' , '$number', '$mpt' , '$mpt' , '$mpt' , '$mpt' , '$mpt' , '$mpt' , '$mpt' );";
if ( mysqli_query ( $res , $sql_query ) )
{
echo "<h3> Data Insert Success...".$number.$password.$username.$_POST["password"]."<h3>";
}
else
{
echo "Data Insert fail: Error:".mysqli_error($res).$number.$password.$username;
}
?>
Can someone help me????
I actually dont know java i know the basics but i haven't used it in 3 years, so i dont know how you are getting the value from the user from the post method to php. However you can use the url as get method to get input from the user.
"myDomain/register.php?username=abc&password=qwqw1w1"
and then get it as a get funtion in php. Or you can first take the user input in a variable and then send them to php using POST method, that should work
$username = $_GET["username"];
$password = $_GET["password"];
$number = $_GET["number"];
I have a bash script when I logged in a web page to then parse the html. The command that I've used is wget:
wget --save-cookies=cookies.txt --post-data "uid=USER&pass=PWD" http://www.spanishtracker.com/login.php
wget --load-cookies=cookies.txt "http://www.spanishtracker.com/torrents.php" -O OUTPUT
Now, I'm trying to make these with Java. Firs of all, I'm trying to POST the request but when I execute the output don't gives as I was logged. These is the code of Java:
try {
data = URLEncoder.encode("uid", "UTF-8") + "=" + URLEncoder.encode("USER", "UTF-8");
data += "&" + URLEncoder.encode("pass", "UTF-8") + "=" + URLEncoder.encode("PASS", "UTF-8");
// Send the request
URL url = new URL("http://www.spanishtracker.com/index.php");
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());
//write parameters
writer.write(data);
writer.flush();
// Get the response
StringBuffer answer = new StringBuffer();
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
answer.append(line);
}
writer.close();
reader.close();
// temporary to build request cookie header
StringBuilder sb = new StringBuilder();
// find the cookies in the response header from the first request
List<String> cookies = conn.getHeaderFields().get("Set-Cookie");
if (cookies != null) {
System.out.println("Hay cookies para guardar");
for (String cookie : cookies) {
if (sb.length() > 0) {
sb.append("; ");
}
// only want the first part of the cookie header that has the value
String value = cookie.split(";")[0];
sb.append(value);
}
}
Could you help me please.
Many thanks and sorry for my english!
Use apache HttpClient library link
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);
I'm trying to create a Foursquare application using its Java API v2 but I couldn't find any sample source code for the checkin process. I don't need to full source code (authentication, venue search, etc), I just need to checkin part.
Can somebody help me?
import java.net.*;
import java.io.*;
class HelloCheckin {
public static void main(String[] args) {
try {
// Construct data
String data = URLEncoder.encode("ll", "UTF-8") + "=" + URLEncoder.encode("53.576317,0.113386", "UTF-8");
data += "&" + URLEncoder.encode("venueId", "UTF-8") + "=" + URLEncoder.encode("4e144a2cc65bedaeefbb824a", "UTF-8");
data += "&" + URLEncoder.encode("oauth_token", "UTF-8") + "=" + URLEncoder.encode("YOUR_OAUTHTOKEN", "UTF-8");
// Send data
URL url = new URL("https://api.foursquare.com/v2/checkins/add");
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) {
// Process line...
}
wr.close();
rd.close();
} catch (Exception e) {
}
} }
The body of this code came from Simple Java Post