I'm building an app for a company that communicates with MySQL database, I'm trying to send a new entry to the server, but I can't get the outputstream write method to work, I know there's an error but I can't seem to find a solution
Here's my code:
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(new OutputStream() {
#Override
public void write(int b) throws IOException {
Log.e("Car DetailStream Writer","outputStreamWriter write method called");
try {
int isLargeAsInt = car.isLarge() ? 1 : 0;
int isDieselAsInt = car.isDiesel() ? 1 : 0;
Log.e("Car Details Write Data",car.getCarModel());
writeData =
URLEncoder.encode("carModel", "UTF-8") + "=" + URLEncoder.encode(car.getCarModel(), "UTF-8") + "&" +
URLEncoder.encode("carYear", "UTF-8") + "=" + URLEncoder.encode(car.getYear(), "UTF-8") + "&" +
URLEncoder.encode("carPlate", "UTF-8") + "=" + URLEncoder.encode(car.getPlateNumber(), "UTF-8") + "&" +
URLEncoder.encode("isLarge", "UTF-8") + "=" + isLargeAsInt + "&" +
URLEncoder.encode("isDiesel", "UTF-8") + "=" + isDieselAsInt + "&" +
URLEncoder.encode("currentMileage", "UTF-8") + "=" + car.getCurrentMileage();
Log.e("Written Data", writeData);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
});
BufferedWriter bufferedWriter = new BufferedWriter(outputStreamWriter);
Log.d("Buffered Writer","Buffered Writer Created");
bufferedWriter.write(writeData);
bufferedWriter.flush();
and here's the error:
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'int java.lang.String.length()' on a null object reference
at java.io.Writer.write(Writer.java:157)
at com.example.trknil.turknilmanagement.utils.SendUtils.makeHttpRequest(SendUtils.java:124)
and this is line 124:
bufferedWriter.write(writeData);
Can anyone fix the code please and tell me where I went wrong.
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 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)
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/
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);
So I'm writing a small app to dump a directory of images into the user's tumblr blog, using their provided API: http://www.tumblr.com/docs/en/api
I've gotten plaintext posting to work, but now I need to find out how to send an image file in the POST instead of UTF-8 encoded text, and I'm lost. My code at the moment is returning a 403 forbidden error, as if the username and password were incorrect (they're not), and everything else I try gives me a bad request error. I'd rather not have to use external libraries for this if I can. This is my ImagePost class:
public class ImagePost {
String data = null;
String enc = "UTF-8";
String type;
File img;
public ImagePost(String imgPath, String caption, String tags) throws IOException {
//Construct data
type = "photo";
img = new File(imgPath);
data = URLEncoder.encode("email", enc) + "=" + URLEncoder.encode(Main.getEmail(), enc);
data += "&" + URLEncoder.encode("password", enc) + "=" + URLEncoder.encode(Main.getPassword(), enc);
data += "&" + URLEncoder.encode("type", enc) + "=" + URLEncoder.encode(type, enc);
data += "&" + URLEncoder.encode("data", enc) + "=" + img;
data += "&" + URLEncoder.encode("caption", enc) + "=" + URLEncoder.encode(caption, enc);
data += "&" + URLEncoder.encode("generator", "UTF-8") + "=" + URLEncoder.encode(Main.getVersion(), "UTF-8");
data += "&" + URLEncoder.encode("tags", "UTF-8") + "=" + URLEncoder.encode(tags, "UTF-8");
}
public void send() throws IOException {
// Set up connection
URL tumblrWrite = new URL("http://www.tumblr.com/api/write");
HttpURLConnection http = (HttpURLConnection) tumblrWrite.openConnection();
http.setDoOutput(true);
http.setRequestMethod("POST");
http.setRequestProperty("Content-Type", "image/png");
DataOutputStream dout = new DataOutputStream(http.getOutputStream());
//OutputStreamWriter out = new OutputStreamWriter(http.getOutputStream());
// Send data
http.connect();
dout.writeBytes(data);
//out.write(data);
dout.flush();
System.out.println(http.getResponseCode());
System.out.println(http.getResponseMessage());
dout.close();
}
}
I suggest you use MultipartRequestEntity (successor of deprecated MultipartPostMethod) of the Apache httpclient package. With MultipartRequestEntity you can send a multipart POST request including a file. An example is below:
public static void postData(String urlString, String filePath) {
log.info("postData");
try {
File f = new File(filePath);
PostMethod postMessage = new PostMethod(urlString);
Part[] parts = {
new StringPart("param_name", "value"),
new FilePart(f.getName(), f)
};
postMessage.setRequestEntity(new MultipartRequestEntity(parts, postMessage.getParams()));
HttpClient client = new HttpClient();
int status = client.executeMethod(postMessage);
} catch (HttpException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}