I'm getting mad about HttpUrlConnection an Outputstreams.
I just want to send a string to php and from there put it in a database.
The last two nights I read nearly thousand guides and threads about sending data to webserver, tried almost everything I read - and it's still not working.
protected void phpPOST(final String ServerURL, final String StringToPost)
{
Thread newthread = new Thread() {
public void run() {
//1. set URL and connect to server
HttpURLConnection connection = null;
try {
URL server = new URL(ServerURL + "teilnehmer_update.php");
connection = (HttpURLConnection) server.openConnection();
//2. set method to POST and enable output
connection.setRequestMethod("POST");
connection.setDoOutput(true);
//3. open outputstream and send string to url
OutputStreamWriter outstream = new OutputStreamWriter(connection.getOutputStream());
outstream.write(StringToPost);
outstream.flush();
outstream.close();
} catch (Exception e) {
e.printStackTrace();
Log.i("Error!", "ERROR is " + e);}
finally {if (connection != null) {connection.disconnect();}}
}
};
newthread.start();
}
I reduced my php-file to very simple, to secure it's not a php problem. Tried from browser, works fine.
<?php
// for testing, should create an empty file when no no data is recieved.
$file = fopen('test.txt', 'w');
$id = $_POST['id'];
fwrite($file, $id);
fclose($file);
?>
I don't get any errors - so, I don't know what to fix. LogCat is also empty.
I think the Problem is something with the Outputstream (also tried versions BufferdOS,OS,DataOS). As far as I get it, the connection is should open when I create the OS and write to it. - But, in my case it does not do anything...
Any ideas what's wrong with the code ?
Thanks
Related
I am trying to make a mobile application, the data i am using is a huge nested JSON object which is a live API on some website. Instead of calling URL request to get the data, i have downloaded the json file and stored it on my asset folder in android. As the data was so huge thats why I stored it locally in the asset folder to avoid a lag in a request. Problem is, i have stored it locally and if the data get updated in website it wont come up to me. i want to make some kind of a method where an app user can update the data itself.
public void updatingJSONFile(){
HttpURLConnection urlConnection;
InputStream in = null;
try{
//the url we wish to connect to
URL url = new URL("my URL");
//open the connnection to the specific url
urlConnection = (HttpURLConnection) url.openConnection();
//get the response from the server in the input stream
in = new BufferedInputStream(urlConnection.getInputStream());
}catch(IOException e){`enter code here`
e.printStackTrace();
}
// convert the input stream to a string
String response = convertStreamToString(in);
// print the response to the android monitor/logcat
System.out.print("Server response = " + response);
try {
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(context.openFileOutput("config.txt", Context.MODE_PRIVATE));
outputStreamWriter.write(response);
outputStreamWriter.close();
}
catch (IOException e) {
Log.e("Exception", "File write failed: " + e.toString());
}
}
I want to send an Image to a localhost using a button in android a android app.At localhost that image pass to a model developed in python.
After do a process using the image,the model give an output to the android app. That result getting part is working fine.
I want to know how to do the image sending part ?
or suggestion for another way to do that process.
This is the code in the model that get an image which we copy to test folder in the pc. I want to develop this to get image from android app .
def process_test_data():
testing_data = []
for img in tqdm(os.listdir(TEST_DIR)):
path = os.path.join(TEST_DIR,img)
img_num = img.split('.')[0]
img = cv2.imread(path,cv2.IMREAD_GRAYSCALE)
img = cv2.resize(img, (IMG_SIZE,IMG_SIZE))
testing_data.append([np.array(img), img_num])
print("\n****testing_data********",testing_data)
shuffle(testing_data)
np.save('test_data.npy', testing_data)
return testing_data
It really depends on what library you are using to connect to the internet. But for sending pictures, I would suggest first to convert it to Base64 text and send that. Python will sure know how to deal with it.
fun bitmapToBase64StringInline(bitmap: Bitmap): String {
val byteArrayOutputStream = ByteArrayOutputStream()
bitmap.compress(Bitmap.CompressFormat.JPEG, 90, byteArrayOutputStream)
val bytes = byteArrayOutputStream.toByteArray()
return android.util.Base64.encodeToString(bytes, Base64.NO_WRAP)
}
Also, it is good to do it in a separate thread and watch out for OOM exception when using large images.
To send it, use some good connection library like OkHttp, Volley, Retrofit etc. Or, just implement kinda basic AsyncTask like this:
protected void doInBackground(String... params) {
URL url = new URL(yourTextUrl);
try {
connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setConnectTimeout(MyConstants.CONNECTION_TIMEOUT);
connection.setReadTimeout(MyConstants.READ_TIMEOUT);
connection.setRequestMethod("POST");
connection.setUseCaches(false);
connection.connect();
Writer writer = new OutputStreamWriter(connection.getOutputStream());
String out = params[0];
Log.d("Uploading this: ", out);
writer.write(out);
writer.flush();
writer.close();
} catch (IOException e) {
e.printStackTrace();
Log.e("ERR", e.getMessage());
if (null != e.getMessage() && e.getMessage().equals("timeout")) {
this.cancel(true);
}
} finally {
connection.disconnect();
}
}
connection is either HttpURLConnection or HttpsURLConnection, based on
your protocol.
I hope it's clear enough.
I am uploading a file to server using the HttpsURLConnection class in Android. I am using PUT method. In normal circumstances it is working fine, but when I am attempting to write a file to the folder in a server, which does not have write permissions, the write method should fail and then when I use getResponseCode() I should recieve a 403 Forbidden response from the server. I have to use the 403 response to show a "No Permissions" message to the user.
Now, when the file size that I upload is less than the buffer size (16K), the write method returns and the getResponseCode returns 403. However, when the file size is bigger (which is usually the case), the program stucks in the write method and thus does not reach the getResponseCode at all. This is happening in all Android devices including the simulator.
Here is the code snippet:
HttpsURLConnection connection = getSSLChannel();
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setConnectTimeout(connectionTimeout);
connection.setReadTimeout(readTimeout);
connection.setUseCaches(false);
connection.setRequestMethod("PUT");
connection.setFixedLengthStreamingMode(size);
connection.setRequestProperty("Connection", "Keep-Alive");
OutputStream out = connection.getOutputStream();
try{
int count =0;
long progress = 0;
byte[] chunkData = new byte[16384];
long fileSize = localFile.getLocalFileSize();
bis = getSourceBufferedStream();
while (((nRead = bis.read(chunkData)) != -1)) {
if(nRead < chunkData.length){
byte[] newBytes = Arrays.copyOf(chunkData, nRead);
out.write(newBytes, 0, nRead);
count++;
}else{
out.write(chunkData, 0, nRead);
count++;
}
}
out.flush();
}finally{
if(out != null){
try {
out.close();
out = null;
} catch (IOException e) {
e.printStackTrace();
}
}
int resCode = connection.getResponseCode();
System.out.println("Res Code :" + resCode);
}
I have put a debug pointer in the finally block. But the app never enters the finally block.
Some points:
1. The server does not support multipart upload.
2. There is no Separate web service to find out, if the folder has write permissions on the server.
3. In iOS this works fine. I am able to receive 403.
4. I have tried with Fiddler, which also gives me a 403.
5. Also, in fast networks (if the server is located in the local wifi domain), I am able to get 403 sometimes.
What am I doing wrong ? Please help !
Thanks.
This is where I got the socketIO files from.
https://github.com/Gottox/socket.io-java-client/tree/master/src/io/socket
I am on the client side.
I know connecting works when the server does not need authentication.
But when it needs authentication (Username and password), I get a handshaking error message.
How do I get passed authentication?? Could it be a server side error? Would the server side of things change if authentication was added?
This is the function that throws an error...I did not write it.
This line is the one causing problems: InputStream stream = connection.getInputStream();
It says it is caused by: java.io.FileNotFoundException: url:80/socket.io/1/
private void handshake() {
URL url;
String response;
URLConnection connection;
try {
setState(STATE_HANDSHAKE);
url = new URL(IOConnection.this.url.toString() + SOCKET_IO_1);
connection = url.openConnection();
if (connection instanceof HttpsURLConnection) {
((HttpsURLConnection) connection)
.setSSLSocketFactory(sslContext.getSocketFactory());
}
connection.setConnectTimeout(connectTimeout);
connection.setReadTimeout(connectTimeout);
/* Setting the request headers */
for (Entry<Object, Object> entry : headers.entrySet()) {
connection.setRequestProperty((String) entry.getKey(),
(String) entry.getValue());
}
InputStream stream = connection.getInputStream();
Scanner in = new Scanner(stream);
response = in.nextLine();
String[] data = response.split(":");
sessionId = data[0];
heartbeatTimeout = Long.parseLong(data[1]) * 1000;
closingTimeout = Long.parseLong(data[2]) * 1000;
protocols = Arrays.asList(data[3].split(","));
} catch (Exception e) {
error(new SocketIOException("Error while handshaking", e));
}
}
Problem solved (sort of), here: Android developpement, Gottox socket.io-java-client: file not fount Exception /socket.io/1/
(try using an earlier version of socket.io - by first deleting socket.io folder from node_modules and then install an older version, e.g., 0.9.16, using this command: npm install socket.io#0.9.16)
I'm trying to parse an xml file from a website. Let's say the website is "http://example.com"
This website has a htaccess rewrite rule setup to redirect anything with a "www" prefix to the host back to example.com. so "http://www.example.com" would redirect to "http://example.com"
In my code I have a URL that i get the InputStream of.
protected InputStream getInputStream() {
try {
return feedUrl.openConnection().getInputStream();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
In this case feedUrl is poingting to "http://www.example.com/file.xml" and when I do the following:
try {
Xml.parse(this.getInputStream(), Xml.Encoding.UTF_8, root.getContentHandler());
} catch (Exception e) {
throw new RuntimeException(e);
}
I get an exception thrown and I believe it's not redirecting to "http://example.com/file.xml"
I could obviously just statically change where my feedUrl variable is pointing to, but I need this to be dynamic.
If anyone ran into this problem like I did, then here's the solution. The HttpURLConnection is already setup to follow redirects by default if the response code is 300, 301, 302, or 303.
For some reason, the server I'm parsing from needs to have the response code be 307 which Android does not redirect automatically.
I would suggest using a different response code, but if your server needs it then here's work around.
HttpURLConnection conn = (HttpURLConnection) feedUrl.openConnection();
int responseCode = conn.getResponseCode();
if( responseCode == 307 ){
String location = conn.getHeaderField("location");
feedUrl = new URL(location);
conn = (HttpURLConnection) this.feedUrl.openConnection();
}
Now conn can open an input stream to the correct file.