I'm getting following error in my app
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String java.lang.Object.toString()' on a null object reference
The JAVA Code where a HTTP Connection is started looks like this:
boolean l = true;
String[] ergebnisArray = new String[100];
for(int i = 0; i < ergebnisArray.length; i++) {
ergebnisArray[i] = "";
}
String count = "0";
if(l) {
try {
String login_url = "http://192.168.178.82:8080/webapp/test.php";
URL url = new URL(login_url);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true);
httpURLConnection.setDoInput(true);
OutputStream outputStream = httpURLConnection.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
String data = URLEncoder.encode("count", "UTF-8") + "=" + URLEncoder.encode(count, "UTF-8");
bufferedWriter.write(data);
bufferedWriter.flush();
bufferedWriter.close();
outputStream.close();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "iso-8859-1"));
String response = "";
String line = "";
while ((line = bufferedReader.readLine()) != null) {
response += line;
}
bufferedReader.close();
inputStream.close();
httpURLConnection.disconnect();
if (response != "") {
int c = Integer.parseInt(count);
ergebnisArray[c] = response;
c++;
count = Integer.toString(c);
} else {
l = false;
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
return ergebnisArray;
And finally the PHP Code:
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "webdb";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$zaehler = $_POST["count"];
$sql = "SELECT * FROM stundenplan";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc() ) {
for ($i = 0; $i <= (int)$zaehler; $i++) {
$output = "".$row["Lehrer"]." ".$row["Klasse"]." ".$row["Stunde"];
}
}
} else {
echo "";
}
echo $output;
$conn->close();
?>
Thanks in advance
You need to declare $output outside of function then put data inside function or you may print it inside for loop.
I think there is a problem of variable scope something like global or local.
Related
I'm making a Java application, and need the user to be able to upload a file to a server through PHP. The problem is that when the user uploads the file, the PHP script doesn't seem to "catch" the file.
This is the code I have so far.
PHP:
<?php
$target_path = "uploads/";
$target_path = $target_path . basename($_FILES['uploadedfile']['name']);
if (move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path)) {
echo "1";
exit();
}
echo "0";
?>
Java:
String filename = "C:\Users\XXX\Pictures\Capture.PNG";
public void uploadFile() {
text = "";
String CrLf = "\r\n";
String filename = filepath.split("/")[filepath.split("/").length-1];
URLConnection conn = null;
OutputStream os = null;
InputStream is = null;
try {
URL con = new URL(connection);
conn = con.openConnection();
conn.setDoOutput(true);
InputStream imgIS = new FileInputStream(filepath);
byte[] imgData = new byte[imgIS.available()];
imgIS.read(imgData);
String message1 = "";
message1 += "-----------------------------4664151417711" + CrLf;
message1 += "Content-Disposition: form-data; name=\"uploadedfile\"; filename=\"Image0001.png\""
+ CrLf;
message1 += "Content-Type: image/png" + CrLf;
message1 += CrLf;
// the image is sent between the messages in the multipart message.
String message2 = "";
message2 += CrLf + "-----------------------------4664151417711--"
+ CrLf;
conn.setRequestProperty("Content-Type",
"multipart/form-data; boundary=---------------------------4664151417711");
// might not need to specify the content-length when sending chunked
// data.
conn.setRequestProperty("Content-Length", String.valueOf((message1
.length() + message2.length() + imgData.length)));
System.out.println("open os");
os = conn.getOutputStream();
System.out.println(message1);
os.write(message1.getBytes());
// SEND THE IMAGE
int index = 0;
int size = 1024;
do {
System.out.println("write:" + index);
if ((index + size) > imgData.length) {
size = imgData.length - index;
}
os.write(imgData, index, size);
index += size;
} while (index < imgData.length);
System.out.println("written:" + index);
System.out.println(message2);
os.write(message2.getBytes());
os.flush();
System.out.println("open is");
is = conn.getInputStream();
char buff = 512;
int len;
byte[] data = new byte[buff];
do {
System.out.println("READ");
len = is.read(data);
if (len > 0) {
System.out.println(new String(data, 0, len));
}
} while (len > 0);
System.out.println("DONE");
} catch (Exception e) {
e.printStackTrace();
} finally {
System.out.println("Close connection");
try {
os.close();
} catch (Exception e) {
}
try {
is.close();
} catch (Exception e) {
}
try {
} catch (Exception e) {
}
}
}
When getting the output from the PHP script, it always returns a "0".
I've tried a lot of different things, but nothing seems to work.
I have a json file which contains only objects now i cant able to fetch all the object with iteration as here is no array.
Here is the code : That i have tried in my android studio & JSon Data Screenshot
#Override
protected String doInBackground(String... strings) {
try {
url = new URL("https://api.myjson.com/bins/r7dj6");
httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.connect();
inputStream = httpURLConnection.getInputStream();
bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
String line =" ";
while ((line = bufferedReader.readLine()) != null){
stringBuffer.append(line);
}
String fullfile = stringBuffer.toString();
JSONObject jsonObject = new JSONObject(fullfile);
JSONObject jsonObjectchild = jsonObject.getJSONObject("Apartment");
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
Here is a complete example. Works for me.
HttpURLConnection connection = null;
try {
URL url = new URL("https://api.myjson.com/bins/r7dj6");
connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream inputStream = connection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
StringBuilder stringBuffer = new StringBuilder();
while ((line = reader.readLine()) != null){
stringBuffer.append(line);
}
JSONObject jsonObject = new JSONObject(stringBuffer.toString());
JSONObject apartmentObject = jsonObject.getJSONObject("Apartment");
Iterator<String> keys = apartmentObject.keys();
while (keys.hasNext()) {
String flatName = keys.next();
JSONObject flat = apartmentObject.getJSONObject(flatName);
String age = flat.getString("age");
String color = flat.getString("color");
String name = flat.getString("name");
String owner = flat.getString("owner");
String partner = flat.getString("partner");
Log.d("Flat", flatName + ": " + age + ", " + color + ", " + name + ", " + owner + ", " + partner);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (connection != null) {
connection.disconnect();
}
}
You can still iterate:
for (Iterator key=jsonObjectchild.keys();key.hasNext();) {
JSONObject flatName = json.get(key.next());
...
}
I'm having this issue for posting data only, I got 401 (non-authorized) while my credential are correct! how to fix this?
ttpURLConnection urlConnection;
IgnoreSSL();
String url = null;
url = "http://" + nmap_node.getHost() + ":"+nmap_node.getPort() + "/post";
String result = null;
try {
String userpass = user_name + ":" + password; //stored in the class
String basicAuth = "Basic " + new String(Base64.getEncoder().encode(userpass.getBytes()));
//Connect
urlConnection = (HttpURLConnection) ((new URL(url).openConnection()));
urlConnection.setDoOutput(true);
urlConnection.setRequestProperty("Content-Type", "application/json");
urlConnection.setRequestProperty("Authorization", "Basic "+basicAuth);
urlConnection.setRequestProperty("Accept", "application/json");
urlConnection.setRequestMethod("POST");
urlConnection.setConnectTimeout(10000);
urlConnection.connect();
//data
String data = datajson.toString(); //method return json to use
OutputStream outputStream = urlConnection.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
writer.write(data);
writer.close();
outputStream.close();
int responseCode=urlConnection.getResponseCode();
if (responseCode == HttpsURLConnection.HTTP_OK) {
//Read
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream(), "UTF-8"));
String line = null;
StringBuilder sb = new StringBuilder();
while ((line = bufferedReader.readLine()) != null) {
sb.append(line);
}
bufferedReader.close();
result = sb.toString();
}else {
// return new String("false : "+responseCode);
new String("false : "+responseCode);
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
I tried in Linux with curl command It works perfectly - I got respond 200 and printed results in the screen.
I encode Images on server with php and send the encoded strings to android via get request and decode it with java but It outputs bad base64 .
so I decided to check the base64 string on online checker but the image doesn't appear is the problem with the php encoding ?
here is the encoded image string :
aW1hZ2VzL21haW4vd3d3L25ldCAtIENvcHkucG5n
PHP::
<?php
require_once("config.php");
if(isset($_GET["m"])) {
$dirname = "images/main/";
$arr = array();
$conn = new mysqli(HOST, USERNAME, PASSWORD, DATABASE);
if(!$conn) {
echo "Error connecting to database";
exit();
}
if($stmt = $conn->prepare("SELECT name_ FROM projects")) {
$stmt->execute();
$stmt->bind_result($n);
//$stmt->store_result();
$result = $stmt->get_result();
if($result->num_rows == 0) {
echo "No Projects";
$stmt->close();
$conn->close();
exit();
}else {
while ($row = $result->fetch_assoc()) {
$dirname = $dirname . $row["name_"] . "/";
$images = glob($dirname . "*.*", GLOB_BRACE);
foreach($images as $key => $image) {
$image = base64_encode($image);
//array_push($arr, $image);
$dirname = "images/main/";
echo $image;
echo "/n";
$image = "";
}
}
//echo "hi";//json_encode($arr);
}
}
$stmt->close();
$conn->close();
exit();
}
?>
ANDROID::
#Override
protected String doInBackground(String[] params) {
String add = "http://10.0.2.2/wael/getimages.php?m=all";
byte[] image = null;
Bitmap real = null;
String parsedString = "";
BufferedReader bufferedReader = null;
InputStream is = null;
StringBuilder sb = null;
HttpURLConnection httpConn = null;
URLConnection conn = null;
try {
URL url = new URL(add);
conn = url.openConnection();
httpConn = (HttpURLConnection) conn;
httpConn.setAllowUserInteraction(false);
httpConn.setInstanceFollowRedirects(true);
httpConn.setRequestMethod("GET");
httpConn.connect();
is = httpConn.getInputStream();
sb = new StringBuilder();
String line;
bufferedReader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
bitmaps = new ArrayList<>();
while ((line = bufferedReader.readLine()) != null) {
sb.append(line).append("\\n");
//image = Base64.decode(line, Base64.NO_PADDING);
//real = BitmapFactory.decodeByteArray(image, 0, image.length);
//bitmaps.add(real);
//image = null;
//real = null;
}
String[] lines = sb.toString().split("\\n");
for(String s: lines){
image = Base64.decode(s, Base64.URL_SAFE);
real = BitmapFactory.decodeByteArray(image, 0, image.length);
bitmaps.add(real);
image = null;
real = null;
}
} catch (IOException e) {
e.printStackTrace();
}
finally {
try {
if (is != null) {
is.close();
}
if (bufferedReader != null) {
bufferedReader.close();
}
if (httpConn != null) {
httpConn.disconnect();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return "done";
}
HINT::
all types of modes in decoding using java are not working . for exmaple URL_SAFE , DEFAULT and etc arenot working all output the same bad base64
You aren't base64 encoding an image, you are base64 encoding the path to an image.
It's like if someone said "Send me a picture of the empire state building", and then you wrote them a letter that said "A picture of the empire state building".
For example, in your comment you said
the following is still not outputing an image aW1hZ2VzL21haW4vd3d3L25ldCAtIENvcHkucG5n
But if I do the following:
console.log(atob("aW1hZ2VzL21haW4vd3d3L25ldCAtIENvcHkucG5n"))
when you hit run you will see
images/main/www/net - Copy.png
Clearly, not the intended result.
In PHP, you would instead do something like this:
$image = file_get_contents($filename);
$b64_image_raw = base64_encode($im);
$mime = mime_content_type($filetype)
$b64_image = "data:" . $mime . ";base64," . $b56_image_raw;
which will give you something like:
data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAB0AAAAdCAMAAABhTZc9AAAAP1BMVEU7V507V50AAAA7V507V507V53///9GYaP7/P33+Pvm6vPa4O2aqM3s7/bf5O+8xd6uutigrdBfd7BNZ6c+Wp9WPQrIAAAABXRSTlP0cwDze/4T5ZQAAABkSURBVCjP3c45DoAwDETRcUiclZ37n5UoFUUyEhIVv32yNTAyuX6TGIgbJwDRiqy36kuOGlNfj6StrvpZie7KdKmw+dGqUPUcbm5PP1d9FC6mmd6uVAtf9VcFUcAStTCCgULMDXttET4Wr4wGAAAAAElFTkSuQmCC
var image = document.createElement("img")
image.src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAB0AAAAdCAMAAABhTZc9AAAAP1BMVEU7V507V50AAAA7V507V507V53///9GYaP7/P33+Pvm6vPa4O2aqM3s7/bf5O+8xd6uutigrdBfd7BNZ6c+Wp9WPQrIAAAABXRSTlP0cwDze/4T5ZQAAABkSURBVCjP3c45DoAwDETRcUiclZ37n5UoFUUyEhIVv32yNTAyuX6TGIgbJwDRiqy36kuOGlNfj6StrvpZie7KdKmw+dGqUPUcbm5PP1d9FC6mmd6uVAtf9VcFUcAStTCCgULMDXttET4Wr4wGAAAAAElFTkSuQmCC";
document.getElementById("image").appendChild(image)
<div id="image"></div>
I am trying to execute various statements/queries in my PHP file, depending on what variables are received (moreover, is there a way to send variables and choose what kind of query I want to do, as opposed to making one query for each set of variables received? This is my first time writing in PHP so please forgive the possible stupid question).
In this case its a Username, Password, and UserID. I'd like an insert to occur when these 3 variables are received. However, I keep on receiving an error: java.net.ProtocolException: method does not support a request body: GET (this is when conn.setDoOutput isset to true). If I have it set to false, I get a IO URL error which states my URL cannot be found. What am I doing wrong? Below are both my php script and the java code used for GET requests.
<?php
$con=mysqli_connect("logindetailsgohere");
if (mysqli_connect_errno($con))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
if (isset($_GET['Username']) && isset($_Get['Password']) && isset($_GET['UserID'])){
$uname = mysql_real_escape_string($_GET['Username']);
$pass = mysql_real_escape_string($_GET['Password']);
$uid = intval($_GET['UserID']);
$sql = "INSERT IGNORE INTO Users (id, Username, Password) VALUES ('$uid', '$uname', '$pass')";
if(mysqli_query($con, $sql){
echo "Values have been inserted";
}
}
mysqli_close($con);
?>
Java code:
public String connect() {
try {
/*URL url = new URL("phpfilelocation.php");*/
String data = URLEncoder.encode("un", "UTF-8") + "=" + URLEncoder.encode(un, "UTF-8");
data += "&" + URLEncoder.encode("pw", "UTF-8") + "=" + URLEncoder.encode(pw, "UTF-8");
data += "&" + URLEncoder.encode("uid", "UTF-8") + "=" + URLEncoder.encode(Integer.toString(uid), "UTF-8");
URL url = new URL("phpfilelocation.php");
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 = null;
// Read Server Response
while((line = reader.readLine()) != null)
{
sb.append(line);
break;
}
return sb.toString();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return "fail";
}
Since this PHP script does an INSERT statement, it's strongly recommended that you use POST parameters.
Java code:
public String connect() {
try {
/*URL url = new URL("phpfilelocation.php");*/
String data = "&" + URLEncoder.encode("un", "UTF-8") + "=" + URLEncoder.encode(un, "UTF-8");
data += "&" + URLEncoder.encode("pw", "UTF-8") + "=" + URLEncoder.encode(pw, "UTF-8");
data += "&" + URLEncoder.encode("uid", "UTF-8") + "=" + URLEncoder.encode(Integer.toString(uid), "UTF-8");
URL url = new URL("phpfilelocation.php");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.connect();
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 = null;
// Read Server Response
while((line = reader.readLine()) != null)
{
sb.append(line);
break;
}
return sb.toString();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return "fail";
}
PHP script:
<?php
$con=mysqli_connect("logindetailsgohere");
if (mysqli_connect_errno($con))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
if (isset($_POST['un']) && isset($_POST['pw']) && isset($_POST['uid'])){
$uname = mysql_real_escape_string($_POST['un']);
$pass = mysql_real_escape_string($_POST['pw']);
$uid = intval($_POST['uid']);
$sql = "INSERT IGNORE INTO Users (id, Username, Password) VALUES ('$uid', '$uname', '$pass')";
if(mysqli_query($con, $sql){
echo "Values have been inserted";
}
}
mysqli_close($con);
?>
As an aside, for a GET request, you just append the parameters to the end of the url when you create the URL object.
public String connect() {
try {
/*URL url = new URL("phpfilelocation.php");*/
String data = URLEncoder.encode("un", "UTF-8") + "=" + URLEncoder.encode(un, "UTF-8");
data += "&" + URLEncoder.encode("pw", "UTF-8") + "=" + URLEncoder.encode(pw, "UTF-8");
data += "&" + URLEncoder.encode("uid", "UTF-8") + "=" + URLEncoder.encode(Integer.toString(uid), "UTF-8");
String urlString = "phpfilelocation.php" + "?" + data;
URL url = new URL(urlString);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(false);
conn.setRequestMethod("GET");
conn.connect();
//remove:
//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 = null;
// Read Server Response
while((line = reader.readLine()) != null)
{
sb.append(line);
break;
}
return sb.toString();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return "fail";
}
PHP :
mysql_query("INSERT INTO Users(id, UserName, Password)
VALUES ('$uid', '$uname', '$pass')");
JAVA :
String driver="com.mysql.jdbc.Driver";
String url="jdbc:mysql://localhost:3306/dbname";
String unameDB="username";
String passDB="password";
Class.forName(driver);
Connection c=(Connection) DriverManager.getConnection(url,unameDB,passDB);
Statement s=c.createStatement();
s.executeUpdate("INSERT INTO `Users`(ID,UserName,Password) VALUE ('"+uid+"','"+uname+"','"+pass+"')");