Getting FileNotFoundException when trying to upload File to Google Cloud Storage - java

I'm trying to upload an image from Android to Cloud Storage. I'm following this official guide on how to upload files to Google Cloud Storage using the JSON API. Here is my code
private class uploadImage extends AsyncTask<File, Void, String> {
File file = mPhotoFile;
private String delimiter = "--";
#Override
protected void onPreExecute() {
Toast.makeText(getActivity(), mPhotoFile.getPath(), Toast.LENGTH_SHORT).show();
}
#Override
protected String doInBackground(File... params) {
try {
URL url = new URL("https://www.googleapis.com/upload/storage/v1/b/backend-images/o?uploadType=media&name=myObject?key=my_key");
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("POST");
urlConnection.setChunkedStreamingMode(0);
urlConnection.setRequestProperty("Content-Type", "image/jpeg");
urlConnection.setRequestProperty("Content-Length", String.valueOf(mPhotoFile.getPath().getBytes().length));
urlConnection.setRequestProperty("Authorization", "my_key");
urlConnection.setDoOutput(true);
urlConnection.setDoOutput(true);
OutputStream out = new BufferedOutputStream(urlConnection.getOutputStream());
InputStream responseStream = new BufferedInputStream(urlConnection.getInputStream());
BufferedReader responseStreamReader = new BufferedReader(new InputStreamReader(responseStream));
out.write(("Content-Type: image/jpeg\r\n").getBytes());
out.write(("Content-Length: " + String.valueOf(mPhotoFile.getPath().getBytes().length)).getBytes());
out.write("\r\n".getBytes());
out.write(mPhotoFile.getPath().getBytes());
out.write("\r\n".getBytes());
String line = "";
StringBuilder stringBuilder = new StringBuilder();
while((line = responseStreamReader.readLine()) != null) {
stringBuilder.append(line).append("\n");
}
String response = stringBuilder.toString();
Log.i("CloudStorage", response);
} catch (IOException e) {
e.printStackTrace();
return e.getMessage();
}
return "Everything was a success";
}
}
I'm using the Public API access method and appending the Api key to the link like the guide says I could to authorize requests
Here is the error i'm getting
05-22 10:24:01.798 3747-4045/com.example.kid.uimockup W/System.err: java.io.FileNotFoundException:https://www.googleapis.com/upload/storage/v1/b/backend-images/o?uploadType=media&name=myObject?key=my_key
05-22 10:24:01.798 3747-4045/com.example.kid.uimockup W/System.err: at com.android.okhttp.internal.http.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:197)
05-22 10:24:01.798 3747-4045/com.example.kid.uimockup W/System.err: at com.android.okhttp.internal.http.DelegatingHttpsURLConnection.getInputStream(DelegatingHttpsURLConnection.java:210)
05-22 10:24:01.798 3747-4045/com.example.kid.uimockup W/System.err: at com.android.okhttp.internal.http.HttpsURLConnectionImpl.getInputStream(HttpsURLConnectionImpl.java:25)
05-22 10:24:01.798 3747-4045/com.example.kid.uimockup W/System.err: at com.example.kid.uimockup.HomeFragment$uploadImage.doInBackground(HomeFragment.java:636)
05-22 10:24:01.803 3747-4045/com.example.kid.uimockup W/System.err: at com.example.kid.uimockup.HomeFragment$uploadImage.doInBackground(HomeFragment.java:605)
05-22 10:24:01.803 3747-4045/com.example.kid.uimockup W/System.err: at android.os.AsyncTask$2.call(AsyncTask.java:288)
05-22 10:24:01.803 3747-4045/com.example.kid.uimockup W/System.err: at java.util.concurrent.FutureTask.run(FutureTask.java:237)
05-22 10:24:01.803 3747-4045/com.example.kid.uimockup W/System.err: at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
05-22 10:24:01.803 3747-4045/com.example.kid.uimockup W/System.err: at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
05-22 10:24:01.803 3747-4045/com.example.kid.uimockup W/System.err: at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
05-22 10:24:01.803 3747-4045/com.example.kid.uimockup W/System.err: at java.lang.Thread.run(Thread.java:818)
I don't have a clue if this is a problem on the client side or the server side

I got it work after making a few changes. I was getting a 401 Unauthorized Error code which means I didn't have authorization to access the bucket.
So instead of appending the query parameter key=api_key, i appended access_token=auth_token to authorize requests.
I then added allUsers permission to my bucket (making it public for everyone to write and read) and it worked.

Related

Error occurs while using Google Cloud Vision Face Detection API

In my application, I am uploading image to get emotion response from Google Cloud Vision API. But while sending the captured image to cloud, I am getting error as
Error
401-1982/com.emotionrecognition W/System.err: java.io.FileNotFoundException: https://vision.googleapis.com/v1/images:annotate?key=AIzaSyAbr--TMSjNERLbwHB4p6a0EnYvVaFlqus
03-08 16:30:41.588 1401-1982/com.emotionrecognition W/System.err: at com.android.okhttp.internal.huc.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:255)
03-08 16:30:41.588 1401-1982/com.emotionrecognition W/System.err: at com.android.okhttp.internal.huc.DelegatingHttpsURLConnection.getInputStream(DelegatingHttpsURLConnection.java:210)
03-08 16:30:41.588 1401-1982/com.emotionrecognition W/System.err: at com.android.okhttp.internal.huc.HttpsURLConnectionImpl.getInputStream(Unknown Source:0)
03-08 16:30:41.588 1401-1982/com.emotionrecognition W/System.err: at com.emotionrecognition.CloudVision.send(CloudVision.java:81)
03-08 16:30:41.589 1401-1982/com.emotionrecognition W/System.err: at com.emotionrecognition.DetectedEmotionAnalysis$DetectEmotion.doInBackground(DetectedEmotionAnalysis.java:177)
03-08 16:30:41.589 1401-1982/com.emotionrecognition W/System.err: at com.emotionrecognition.DetectedEmotionAnalysis$DetectEmotion.doInBackground(DetectedEmotionAnalysis.java:172)
03-08 16:30:41.589 1401-1982/com.emotionrecognition W/System.err: at android.os.AsyncTask$2.call(AsyncTask.java:333)
03-08 16:30:41.589 1401-1982/com.emotionrecognition W/System.err: at java.util.concurrent.FutureTask.run(FutureTask.java:266)
03-08 16:30:41.589 1401-1982/com.emotionrecognition W/System.err: at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:245)
03-08 16:30:41.590 1401-1982/com.emotionrecognition W/System.err: at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1162)
03-08 16:30:41.590 1401-1982/com.emotionrecognition W/System.err: at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:636)
03-08 16:30:41.590 1401-1982/com.emotionrecognition W/System.err: at java.lang.Thread.run(Thread.java:764)
03-08 16:30:41.590 1401-1982/com.emotionrecognition D/GCV Error: java.io.FileNotFoundException: https://vision.googleapis.com/v1/images:annotate?key=AIzaSyAbr--TMSjNERLbwHB4p6a0EnYvVaFlqus
03-08 16:30:55.951 1401-1401/com.emotionrecognition V/InputMethodManager: Starting input: tba=android.view.inputmethod.EditorInfo#8a9b4a4 nm : com.emotionrecognition ic=null
03-08 16:30:55.952 1401-1401/com.emotionrecognition I/InputMethodManager: startInputInner - mService.startInputOrWindowGainedFocus
This is the code i have written to send image to URL,i am not getting response from Google Cloud Vision API ,when i paste that url in web browser i am getting error as 404 file not found
Bitmap bmp = BitmapFactory.decodeFile(imagePath);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] imageByteArray = stream.toByteArray();
String encodedImageString = Base64.encodeToString(imageByteArray, Base64.DEFAULT);
URL url = new URL(Config.CLOUD_VISION_URL);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setUseCaches(false);
con.setDoInput(true);
con.setDoOutput(true);
con.setRequestMethod("POST");
con.setRequestProperty("Content-Type", "application/json");
// Features JSON
JSONObject featuresJson = new JSONObject();
featuresJson.put("type", "FACE_DETECTION");
featuresJson.put("maxResults", 1);
JSONArray featuresJSONArray = new JSONArray();
featuresJSONArray.put(featuresJson);
// Image JSON
JSONObject imageJson = new JSONObject();
imageJson.put("content", encodedImageString);
// Requests JSON
JSONObject requestsJson = new JSONObject();
requestsJson.put("image", imageJson);
requestsJson.put("features", featuresJSONArray);
JSONArray requestsJSONArray = new JSONArray();
requestsJSONArray.put(requestsJson);
JSONObject wholeRequest = new JSONObject();
wholeRequest.put("requests", requestsJSONArray);
OutputStreamWriter out = new OutputStreamWriter(con.getOutputStream());
out.write(wholeRequest.toString());
out.flush();
out.close();
int response_code = con.getResponseCode();
Log.d("GCV Response Code", ""+response_code);
BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream()));
StringBuilder sb = new StringBuilder("");
String temp;
while((temp = br.readLine()) != null)
sb.append(temp);
String response = sb.toString();
JSONObject responseJSONObject = new JSONObject(response);
if (response_code == 200) {
Log.d("GCV", "Successful response");
}
JSONArray responsesArray = responseJSONObject.getJSONArray("responses");
JSONObject faceAnnotationsJson = responsesArray.getJSONObject(0);
JSONObject annotedEmotionsJson = faceAnnotationsJson.getJSONArray("faceAnnotations").getJSONObject(0);
return annotedEmotionsJson;
As far as I know you cannot print cloud vision url in chrome as it needs your credentials to access.
You can either access cloud vision url using api_key or OATH2.0 service account
Either way you do, you need to provide those credentials in your post requests.
Another thing is that you need to make sure your image url is accessible by Vision API.
Either your image url is an public http url, or it is a GCS url with is either public or can be accessed by your credential.
Or you can send image bytes directly.
It seems to me that you are using API_KEY instead of OATH2.0 credentials
401-1982/com.emotionrecognition W/System.err: java.io.FileNotFoundException: https://vision.googleapis.com/v1/images:annotate?key=AIzaSyAbr--TMSjNERLbwHB4p6a0EnYvVaFlqus
Are you uploading image to your private GCS bucket? If that is true I suggest you mark your image as public image and try again.
As far as I know api_key cannot be used to access private GCS bucket.
And it is not recommended to paste your api_key directly, you may want to remove that key you use.

Android http connection refused

I created an Android test program with service and activity.
In activity I start sticky service. Service make http requests every 10 seconds.
If I not exit from activity, all works fine. If I exit, service works sometime, then killed by system and restarted. After restart sometimes http requests works, sometimes gives an error message:
09-28 14:55:18.053 31161-31184/home.xmpp W/System.err: java.net.ConnectException: failed to connect to www.ya.ru/87.250.250.242 (port 80) after 15000ms: isConnected failed: ECONNREFUSED (Connection refused)
09-28 14:55:18.053 31161-31184/home.xmpp W/System.err: at libcore.io.IoBridge.isConnected(IoBridge.java:238)
09-28 14:55:18.053 31161-31184/home.xmpp W/System.err: at libcore.io.IoBridge.connectErrno(IoBridge.java:171)
09-28 14:55:18.053 31161-31184/home.xmpp W/System.err: at libcore.io.IoBridge.connect(IoBridge.java:122)
09-28 14:55:18.053 31161-31184/home.xmpp W/System.err: at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:183)
09-28 14:55:18.053 31161-31184/home.xmpp W/System.err: at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:456)
09-28 14:55:18.053 31161-31184/home.xmpp W/System.err: at java.net.Socket.connect(Socket.java:882)
09-28 14:55:18.053 31161-31184/home.xmpp W/System.err: at com.android.okhttp.internal.Platform.connectSocket(Platform.java:174)
09-28 14:55:18.053 31161-31184/home.xmpp W/System.err: at com.android.okhttp.Connection.connect(Connection.java:152)
09-28 14:55:18.053 31161-31184/home.xmpp W/System.err: at com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:276)
09-28 14:55:18.053 31161-31184/home.xmpp W/System.err: at com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:211)
09-28 14:55:18.053 31161-31184/home.xmpp W/System.err: at com.android.okhttp.internal.http.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:382)
09-28 14:55:18.053 31161-31184/home.xmpp W/System.err: at com.android.okhttp.internal.http.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:106)
09-28 14:55:18.053 31161-31184/home.xmpp W/System.err: at com.android.okhttp.internal.http.HttpURLConnectionImpl.getOutputStream(HttpURLConnectionImpl.java:217)
09-28 14:55:18.053 31161-31184/home.xmpp W/System.err: at home.xmpp.MyService.sendPostRequest(MyService.java:160)
09-28 14:55:18.053 31161-31184/home.xmpp W/System.err: at home.xmpp.MyService$MyTask.doInBackground(MyService.java:128)
09-28 14:55:18.053 31161-31184/home.xmpp W/System.err: at home.xmpp.MyService$MyTask.doInBackground(MyService.java:109)
09-28 14:55:18.053 31161-31184/home.xmpp W/System.err: at android.os.AsyncTask$2.call(AsyncTask.java:292)
09-28 14:55:18.053 31161-31184/home.xmpp W/System.err: at java.util.concurrent.FutureTask.run(FutureTask.java:237)
09-28 14:55:18.053 31161-31184/home.xmpp W/System.err: at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
09-28 14:55:18.053 31161-31184/home.xmpp W/System.err: at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
09-28 14:55:18.053 31161-31184/home.xmpp W/System.err: at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
09-28 14:55:18.053 31161-31184/home.xmpp W/System.err: at java.lang.Thread.run(Thread.java:818)
09-28 14:55:18.053 31161-31184/home.xmpp W/System.err: Caused by: android.system.ErrnoException: isConnected failed: ECONNREFUSED (Connection refused)
09-28 14:55:18.053 31161-31184/home.xmpp W/System.err: at libcore.io.IoBridge.isConnected(IoBridge.java:223)
09-28 14:55:18.053 31161-31184/home.xmpp W/System.err: ... 21 more
After the appearance of this error, the following requests will also fail.
I tried to start service in another process, tried to start each http request in new IntentService, tried to restart service after this error, but no results.
If an error has occurred, then other subsequent requests will also give an error. Only application restart helps.
Has anyone encountered such problem? How to make a stable connection? I read a lot of topics, but did not find the right answer.
MyService.java
package home.xmpp;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.ComponentCallbacks2;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Handler;
import android.os.IBinder;
import android.util.Log;
import javax.net.ssl.HttpsURLConnection;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
public class MyService extends Service implements ComponentCallbacks2 {
private Boolean disconnectAppeared = false;
static MyService instance;
private Handler mHandler = new Handler();
MyTask mt;
Boolean mtruned = false;
public static MyService getInstance(){
return instance;
}
#Override
public IBinder onBind(final Intent intent) {
//throw new UnsupportedOperationException("Not yet implemented");
return new LocalBinder<MyService>(this);
}
#Override
public void onCreate() {
super.onCreate();
instance = this;
mHandler.postDelayed(timeUpdaterRunnable, 100);
Log.e("MyService"," created");
}
#Override
public int onStartCommand(final Intent intent, final int flags,
final int startId) {
return Service.START_STICKY;
}
#Override
public boolean onUnbind(final Intent intent) {
return super.onUnbind(intent);
}
#Override
public void onDestroy() {
super.onDestroy();
Log.e("MyService"," destroyed");
mHandler.removeCallbacks(timeUpdaterRunnable);
}
public void onTrimMemory(int level) {
switch (level) {
case ComponentCallbacks2.TRIM_MEMORY_RUNNING_CRITICAL: //Release any memory that your app doesn't need to run.
//the system will begin killing background processes. !!!
Log.e("Memory level","4");
break;
default:
break;
}
}
private Runnable timeUpdaterRunnable = new Runnable() {
public void run() {
if (mtruned == false) {
Log.e("Time", " update");
mt = new MyTask();
mt.execute();
mHandler.postDelayed(this, 10000);
} else {
cancelTask();
}
}
};
private void cancelTask() {
if (mt == null) return;
Log.d("MyService", "cancel result: " + mt.cancel(false));
}
class MyTask extends AsyncTask<String,Void,String> {
#Override
protected void onPreExecute() {
mtruned = true;
super.onPreExecute();
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
Log.e("http","updated");
mtruned = false;
}
#Override
protected String doInBackground(String... params) {
String result = "";
HashMap<String,String> data = new HashMap<>();
data.put("data", "data");
result = sendPostRequest("http://www.ya.ru", data);
return result;
}
#Override
protected void onCancelled() {
super.onCancelled();
mtruned = false;
}
}
public String sendPostRequest(String requestURL,
HashMap<String, String> postDataParams) {
//Creating a URL
URL url;
//StringBuilder object to store the message retrieved from the server
StringBuilder sb = new StringBuilder();
try {
//Initializing Url
url = new URL(requestURL);
//Creating an httmlurl connection
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
//Configuring connection properties
conn.setReadTimeout(15000);
conn.setConnectTimeout(15000);
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
//Creating an output stream
OutputStream os = conn.getOutputStream();
//Writing parameters to the request
//We are using a method getPostDataString which is defined below
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os, "UTF-8"));
writer.write(getPostDataString(postDataParams));
writer.flush();
writer.close();
os.close();
int responseCode = conn.getResponseCode();
if (responseCode == HttpsURLConnection.HTTP_OK) {
BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
sb = new StringBuilder();
String response;
//Reading server response
while ((response = br.readLine()) != null){
sb.append(response);
}
}
} catch (Exception e) {
e.printStackTrace();
}
return sb.toString();
}
private String getPostDataString(HashMap<String, String> params) throws UnsupportedEncodingException {
StringBuilder result = new StringBuilder();
boolean first = true;
for (Map.Entry<String, String> entry : params.entrySet()) {
if (first)
first = false;
else
result.append("&");
result.append(URLEncoder.encode(entry.getKey(), "UTF-8"));
result.append("=");
result.append(URLEncoder.encode(entry.getValue(), "UTF-8"));
}
return result.toString();
}
}
Update 05.10.17 I still not find a solution. I tested this programm on Android 4.1.2. It works fine. On Android 5.1.1 it works about 3 minutes after exiting the activity and then I receive connection refused error. When I return to activity, errors disappears. On Android 6.0.1 similar situation, but the error is slightly different java.net.SocketTimeoutException: failed to connect to /94.130.25.242 (port 80) after 10000ms. I think that the system blocks network activity in services after a while, but never in activities (?).
Update 05.10.17
I noticed that the connection disappears not only after the restart of the service, but also after 2-3 minutes, when exiting activity. When I return to activity, connections are restored.
I have made a video Link
Update 06.10.17
One Android specialist told me, that this problem appear only in Xiaomi phones. MIUI rejects network connections after some minutes. Only OkHttp helps. I will try it and will make feedback here.
A "connect failed: ECONNREFUSED (Connection refused)" most likely means that there is nothing listening on that port AND that IP address. Possible explanations include:
the service has crashed or hasn't been started,
your client is trying to connect using the wrong IP address or port,
or
server access is being blocked by a firewall that is "refusing" on
the server/service's behalf. This is pretty unlikely given that
normal practice (these days) is for firewalls to "blackhole" all
unwanted connection attempts.
It is impossible to use long network connections in background on Xiaomi phones. It's MIUI blocks any network connections after some time. For critical network connections, you can use Firebase Cloud Messaging, which have high priority in Android system. It can initiate necesary background job.

how to resolve failed to connect to /192.168.15.186 (port 80): connect failed: ETIMEDOUT (Connection timed out) in Windows Firewall

I'm trying to test android studio connection to mysql based on this tutorial using my android device for debugging purposes instead of android emulator. But the problem is, it results to:
java.net.ConnectException: failed to connect to /192.168.15.186 (port 80): connect failed: ETIMEDOUT (Connection timed out)
Take note that this is running on real device. localhost or 127.0.0.1:80 would return a result of ECONNREFUSED because obviously, this are computer addresses that the database aren't in the device but in the computer itself so it would be a completely waste of time if I test these 2 out or any alternative IP's.
I've tested out 10.0.2.2:80/login.php on emulator and it returns a true result hinting that the login and connection is success.
So I'm guessing that maybe the connection is block through the windows firewall, but I dont know how to modify it.
LOGCAT
03-06 13:59:29.935 20951-20951/com.example.smdojt.mysqldemo W/InputEventReceiver: Attempted to finish an input event but the input event receiver has already been disposed.
03-06 14:01:30.744 20951-25612/com.example.smdojt.mysqldemo W/System.err: java.net.ConnectException: failed to connect to /192.168.15.186 (port 80): connect failed: ETIMEDOUT (Connection timed out)
03-06 14:01:30.744 20951-25612/com.example.smdojt.mysqldemo W/System.err: at libcore.io.IoBridge.connect(IoBridge.java:124)
03-06 14:01:30.744 20951-25612/com.example.smdojt.mysqldemo W/System.err: at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:200)
03-06 14:01:30.744 20951-25612/com.example.smdojt.mysqldemo W/System.err: at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:513)
03-06 14:01:30.744 20951-25612/com.example.smdojt.mysqldemo W/System.err: at java.net.Socket.connect(Socket.java:894)
03-06 14:01:30.744 20951-25612/com.example.smdojt.mysqldemo W/System.err: at com.android.okhttp.internal.Platform.connectSocket(Platform.java:174)
03-06 14:01:30.744 20951-25612/com.example.smdojt.mysqldemo W/System.err: at com.android.okhttp.Connection.connect(Connection.java:152)
03-06 14:01:30.744 20951-25612/com.example.smdojt.mysqldemo W/System.err: at com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:276)
03-06 14:01:30.744 20951-25612/com.example.smdojt.mysqldemo W/System.err: at com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:211)
03-06 14:01:30.744 20951-25612/com.example.smdojt.mysqldemo W/System.err: at com.android.okhttp.internal.http.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:382)
03-06 14:01:30.744 20951-25612/com.example.smdojt.mysqldemo W/System.err: at com.android.okhttp.internal.http.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:106)
03-06 14:01:30.744 20951-25612/com.example.smdojt.mysqldemo W/System.err: at com.android.okhttp.internal.http.HttpURLConnectionImpl.getOutputStream(HttpURLConnectionImpl.java:217)
03-06 14:01:30.745 20951-25612/com.example.smdojt.mysqldemo W/System.err: at com.example.smdojt.mysqldemo.BackgroundWorker.doInBackground(BackgroundWorker.java:48)
03-06 14:01:30.745 20951-25612/com.example.smdojt.mysqldemo W/System.err: at com.example.smdojt.mysqldemo.BackgroundWorker.doInBackground(BackgroundWorker.java:23)
03-06 14:01:30.745 20951-25612/com.example.smdojt.mysqldemo W/System.err: at android.os.AsyncTask$2.call(AsyncTask.java:292)
03-06 14:01:30.745 20951-25612/com.example.smdojt.mysqldemo W/System.err: at java.util.concurrent.FutureTask.run(FutureTask.java:237)
03-06 14:01:30.745 20951-25612/com.example.smdojt.mysqldemo W/System.err: at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
03-06 14:01:30.745 20951-25612/com.example.smdojt.mysqldemo W/System.err: at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
03-06 14:01:30.745 20951-25612/com.example.smdojt.mysqldemo W/System.err: at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
03-06 14:01:30.745 20951-25612/com.example.smdojt.mysqldemo W/System.err: at java.lang.Thread.run(Thread.java:818)
03-06 14:01:30.745 20951-25612/com.example.smdojt.mysqldemo W/System.err: Caused by: android.system.ErrnoException: connect failed: ETIMEDOUT (Connection timed out)
03-06 14:01:30.745 20951-25612/com.example.smdojt.mysqldemo W/System.err: at libcore.io.Posix.connect(Native Method)
03-06 14:01:30.745 20951-25612/com.example.smdojt.mysqldemo W/System.err: at libcore.io.BlockGuardOs.connect(BlockGuardOs.java:111)
03-06 14:01:30.745 20951-25612/com.example.smdojt.mysqldemo W/System.err: at libcore.io.IoBridge.connectErrno(IoBridge.java:137)
03-06 14:01:30.745 20951-25612/com.example.smdojt.mysqldemo W/System.err: at libcore.io.IoBridge.connect(IoBridge.java:122)
03-06 14:01:30.745 20951-25612/com.example.smdojt.mysqldemo W/System.err: ... 18 more
03-06 14:01:30.748 20951-20951/com.example.smdojt.mysqldemo D/wangcy9: setStatusIcon occur wrong theme!
03-06 14:01:30.782 20951-20951/com.example.smdojt.mysqldemo D/ViewRootImpl: loadSystemProperties PersistDebugEvent: false RoDebugEvent: false
03-06 14:02:30.313 20951-20951/com.example.smdojt.mysqldemo W/InputEventReceiver: Attempted to finish an input event but the input event receiver has already been disposed.
MAINACTIVITY.java
public class MainActivity extends AppCompatActivity {
EditText UsernameEt, PasswordEt;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
UsernameEt = (EditText) findViewById(R.id.etUserName);
PasswordEt = (EditText) findViewById(R.id.etPassword);
}
public void OnLogin(View view)
{
String username = UsernameEt.getText().toString();
String password = PasswordEt.getText().toString();
String type = "login";
BackgroundWorker backgroundWorker = new BackgroundWorker(this);
backgroundWorker.execute(type, username, password);
}
}
BACKGROUNDWORKER.java
public class BackgroundWorker extends AsyncTask<String, Void, String> {
Context context;
AlertDialog alertDialog;
BackgroundWorker (Context ctx)
{
context = ctx;
}
#Override
protected String doInBackground(String... params) {
String type = params[0];
String login_url = "http://192.168.15.186:80/login.php"; //declare want you want to connect with
if (type.equals("login"))
{
try {
String user_name = params[1];
String password = params[2];
URL url = new URL(login_url);
HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection(); //declare http connection class
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true);
httpURLConnection.setDoInput(true);
OutputStream outputStream = httpURLConnection.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
String post_data = URLEncoder.encode("user_name","UTF-8") + "=" +URLEncoder.encode(user_name, "UTF-8")+"&"
+URLEncoder.encode("password","UTF-8") + "=" +URLEncoder.encode(password, "UTF-8");
bufferedWriter.write(post_data);
bufferedWriter.flush();
bufferedWriter.close();
outputStream.close();
//below: read and get post respone
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "iso-8859-1"));
String result="";
String line="";
while ((line = bufferedReader.readLine())!=null)
{
result += line;
}
bufferedReader.close();
inputStream.close();
httpURLConnection.disconnect();
return result;
} catch (MalformedURLException e) {
e.printStackTrace();
}
//Clause for httpurlconnection
catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPreExecute() {
alertDialog = new AlertDialog.Builder(context).create();
alertDialog.setTitle("Login Status");
}
#Override
protected void onPostExecute(String result) {
alertDialog.setMessage(result);
alertDialog.show();
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
}
I had the same Issue today, and i solved it by making my PC discoverable in private networks.
Steps to make your PC Discoverable:
Go to network settings.
>Go to Manage known networks.
>Choose your network.
>Now turn on the PC discoverable feature.
It helped for me, i hope it will help you.
I have faced such problem but overcome through allow port 1433(my port) to firewall .
I have Followed below Steps:
Configure Firewall and Security Setting -> Advanced Setting ->Inbound Rules -> New Rule-> Port -> Next ->Specific Local Port(1433)->Next-> Allow the Connection -> Next ->Next-> Add Name-> Finish
I also faced the same problem today and I solved it when I turned off the fire wall and network protection setting.
I solved my problem when I change Network profile from private to public.

java.net.SocketTimeoutException: failed to connect to /192.168.1.8 (port 8383) after 10000ms

I a new to Android programming.While trying to connect to PHP from my Android Client (WAMP) I get the following error
java.net.SocketTimeoutException: failed to connect to /192.168.1.8 (port 8383) after 10000ms
'I had searched for this type of error and had made all prescribed changes including Changing localhost to ipv address, changing the Timeout interval, configuring the httpd.conf file, still couldn't resolve.Pls find below the code, conf file changes and error log
Error Log:
java.net.SocketTimeoutException: failed to connect to /192.168.1.8 (port 8383) after 10000ms
02-20 07:42:34.857 3370-3512/com.example.vijayar.phpconnect W/System.err: at libcore.io.IoBridge.connectErrno(IoBridge.java:169)
02-20 07:42:34.857 3370-3512/com.example.vijayar.phpconnect W/System.err: at libcore.io.IoBridge.connect(IoBridge.java:122)
02-20 07:42:34.857 3370-3512/com.example.vijayar.phpconnect W/System.err: at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:183)
02-20 07:42:34.857 3370-3512/com.example.vijayar.phpconnect W/System.err: at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:456)
02-20 07:42:34.857 3370-3512/com.example.vijayar.phpconnect W/System.err: at java.net.Socket.connect(Socket.java:882)
02-20 07:42:34.857 3370-3512/com.example.vijayar.phpconnect W/System.err: at com.android.okhttp.internal.Platform.connectSocket(Platform.java:139)
02-20 07:42:34.857 3370-3512/com.example.vijayar.phpconnect W/System.err: at com.android.okhttp.Connection.connect(Connection.java:148)
02-20 07:42:34.857 3370-3512/com.example.vijayar.phpconnect W/System.err: at com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:276)
02-20 07:42:34.857 3370-3512/com.example.vijayar.phpconnect W/System.err: at com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:211)
02-20 07:42:34.857 3370-3512/com.example.vijayar.phpconnect W/System.err: at com.android.okhttp.internal.http.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:373)
02-20 07:42:34.857 3370-3512/com.example.vijayar.phpconnect W/System.err: at com.android.okhttp.internal.http.HttpURLConnectionImpl.getResponse(HttpURLConnectionImpl.java:323)
02-20 07:42:34.857 3370-3512/com.example.vijayar.phpconnect W/System.err: at com.android.okhttp.internal.http.HttpURLConnectionImpl.getResponseCode(HttpURLConnectionImpl.java:491)
02-20 07:42:34.857 3370-3512/com.example.vijayar.phpconnect W/System.err: at com.example.vijayar.phpconnect.MainActivity$AsyncRetrieve.doInBackground(MainActivity.java:80)
02-20 07:42:34.857 3370-3512/com.example.vijayar.phpconnect W/System.err: at com.example.vijayar.phpconnect.MainActivity$AsyncRetrieve.doInBackground(MainActivity.java:33)
02-20 07:42:34.857 3370-3512/com.example.vijayar.phpconnect W/System.err: at android.os.AsyncTask$2.call(AsyncTask.java:288)
02-20 07:42:34.857 3370-3512/com.example.vijayar.phpconnect W/System.err: at java.util.concurrent.FutureTask.run(FutureTask.java:237)
02-20 07:42:34.857 3370-3512/com.example.vijayar.phpconnect W/System.err: at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
02-20 07:42:34.857 3370-3512/com.example.vijayar.phpconnect W/System.err: at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
02-20 07:42:34.857 3370-3512/com.example.vijayar.phpconnect W/System.err: at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
02-20 07:42:34.857 3370-3512/com.example.vijayar.phpconnect W/System.err: at java.lang.Thread.run(Thread.java:818)
02-20 07:42:35.007 3370-3510/com.example.vijayar.phpconnect V/RenderScript: 0xb0f4b600 Launching thread(s), CPUs 3
Java Code
public class MainActivity extends AppCompatActivity {
// CONNECTION_TIMEOUT and READ_TIMEOUT are in milliseconds
public static final int CONNECTION_TIMEOUT = 10000;
public static final int READ_TIMEOUT = 10000;
TextView textPHP;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textPHP = (TextView) findViewById(R.id.textPHP);
//Make call to AsyncRetrieve
new AsyncRetrieve().execute();
}
private class AsyncRetrieve extends AsyncTask<String, String, String> {
ProgressDialog pdLoading = new ProgressDialog(MainActivity.this);
HttpURLConnection conn;
URL url = null;
//this method will interact with UI, here display loading message
#Override
protected void onPreExecute() {
super.onPreExecute();
pdLoading.setMessage("\tLoading...");
pdLoading.setCancelable(false);
pdLoading.show();
}
// This method does not interact with UI, You need to pass result to onPostExecute to display
#Override
protected String doInBackground(String... params) {
try {
// Enter URL address where your php file resides
url = new URL("http://192.168.1.8:8383/Checking/Checking.php");
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return e.toString();
}
try {
// Setup HttpURLConnection class to send and receive data from php
conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(READ_TIMEOUT);
conn.setConnectTimeout(CONNECTION_TIMEOUT);
conn.setRequestMethod("GET");
// setDoOutput to true as we recieve data from json file
conn.setDoOutput(true);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
return e1.toString();
}
try {
int response_code = conn.getResponseCode();
// Check if successful connection made
if (response_code == HttpURLConnection.HTTP_OK) {
// Read data sent from server
InputStream input = conn.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(input));
StringBuilder result = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
result.append(line);
}
// Pass data to onPostExecute method
return (result.toString());
} else {
return ("unsuccessful");
}
} catch (IOException e) {
e.printStackTrace();
return e.toString();
} finally {
conn.disconnect();
}
}
// this method will interact with UI, display result sent from doInBackground method
#Override
protected void onPostExecute(String result) {
pdLoading.dismiss();
if(result.equals("Success! This message is from PHP")) {
textPHP.setText(result.toString());
}else{
// you to understand error returned from doInBackground method
Toast.makeText(MainActivity.this, result.toString(), Toast.LENGTH_LONG).show();
}
}
}
}
Manifest File
<uses-permission android:name="android.permission.INTERNET"/>
In Httpd.conf the following changes are made
#Listen 12.34.56.78:8383
Listen 0.0.0.0:8383
Listen [::0]:8383
<Directory />
AllowOverride None
Options None
Allow from All
Require all granted
</Directory>
PHP file -> Checking.Php
<?php
echo "Success! This message is from PHP";
?>
The PHP page works fine when invoked from browser.
The problem looks like your Apache configuration might be listening on the wrong ip address. Android is trying to access the ip address 192.168.1.8:8383 and your Apache server needs to be on the same network with your Android device. I would recommend that you make sure your Android device is on the same network as the Apache server and that your server is setup to listen on the correct ip address that Android is trying to connect too.
Timeout issue is resolved, this is what I did, I had added IPV4 to Listen command in httpd.conf file and disabled temporarily the antivirus gateway (that was preventing request from hitting the server) –

BufferedInputStream is closed when setting postDelayed Runnable

I have my GameActivity that is a simple quiz. I set up two Runnables, mRunnableQuestion and mRunnableQuestionWithPenalty. The logic is: mRunnableQuestion shows new question and waits 30 seconds, when user doesn't answer in this time, the other Runnable is called, which gives user points penalty:
private Runnable mRunnableQuestion = new Runnable() {
#Override
public void run() {
new AsyncAPIGetQuestion().execute(mCategoryId);
mHandler.postDelayed(mRunnableQuestionWithPenalty, 30000);
}
};
Of course, when user answers in time, I give user points and restart the Runnable:
mHandler.removeCallbacksAndMessages(null);
mHandler.post(mRunnableQuestion);
It works very well. However, I wanted to color the Cards based on correct/wrong answer and wait 5 seconds. So i changed code above to:
mHandler.removeCallbacksAndMessages(null);
colorAnswers();
mHandler.postDelayed(mRunnableQuestion, 5000);
This is where the problem begins. When I run my app, after 2, 3 or 4 questions I get a EOF/BufferedInputStream error:
03-04 13:38:24.107 16506-16532/com.my.pkg W/System.err: java.io.EOFException
03-04 13:38:24.107 16506-16532/com.my.pkg W/System.err: at com.android.okio.RealBufferedSource.readUtf8LineStrict(RealBufferedSource.java:95)
03-04 13:38:24.107 16506-16532/com.my.pkg W/System.err: at com.
android.okhttp.internal.http.HttpConnection.readResponse(HttpConnection.java:175)
03-04 13:38:24.107 16506-16532/com.my.pkg W/System.err: at com.android.okhttp.internal.http.HttpTransport.readResponseHeaders(HttpTransport.java:101)
03-04 13:38:24.107 16506-16532/com.my.pkg W/System.err: at com.android.okhttp.internal.http.HttpEngine.readResponse(HttpEngine.java:616)
03-04 13:38:24.107 16506-16532/com.my.pkg W/System.err: at com.android.okhttp.internal.http.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:379)
03-04 13:38:24.107 16506-16532/com.my.pkg W/System.err: at com.android.okhttp.internal.http.HttpURLConnectionImpl.getResponse(HttpURLConnectionImpl.java:323)
03-04 13:38:24.108 16506-16532/com.my.pkg W/System.err: at com.android.okhttp.internal.http.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:190)
03-04 13:38:24.108 16506-16532/com.my.pkg W/System.err: at com.my.pkg.JSONParser.getJSONFromUrl(JSONParser.java:45)
03-04 13:38:24.108 16506-16532/com.my.pkg W/System.err: at com.my.pkg.GameActivity$AsyncAPIGetQuestion.doInBackground(GameActivity.java:317)
03-04 13:38:24.108 16506-16532/com.my.pkg W/System.err: at com.my.pkg.GameActivity$AsyncAPIGetQuestion.doInBackground(GameActivity.java:299)
03-04 13:38:24.108 16506-16532/com.my.pkg W/System.err: at android.os.AsyncTask$2.call(AsyncTask.java:288)
03-04 13:38:24.108 16506-16532/com.my.pkg W/System.err: at java.util.concurrent.FutureTask.run(FutureTask.java:237)
03-04 13:38:24.108 16506-16532/com.my.pkg W/System.err: at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
03-04 13:38:24.108 16506-16532/com.my.pkg W/System.err: at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
03-04 13:38:24.108 16506-16532/com.my.pkg W/System.err: at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
03-04 13:38:24.108 16506-16532/com.my.pkg W/System.err: at java.lang.Thread.run(Thread.java:818)
03-04 13:38:24.108 16506-16532/com.my.pkg E/JSONParser.java: Error converting result java.io.IOException: BufferedInputStream is closed
It ONLY happens, when I add the extra postDelayed() there. No problems before.
My doInBackground part of AsyncTask that is executed by Runnable and that returns an error as stated above
#Override
protected JSONArray doInBackground(String... params) {
JSONParser jParser = new JSONParser();
JSONArray json = jParser.getJSONFromUrl(apiURL);
return json;
}
And the JSONParser.getJSONFromURL:
public JSONArray getJSONFromUrl(String urlSource) {
try {
URL url = new URL(urlSource);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setDoOutput(true);
urlConnection.setChunkedStreamingMode(0);
inputStream = new BufferedInputStream(urlConnection.getInputStream());
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
if(!reader.ready()) {
break;
}
}
inputStream.close();
json = sb.toString();
} catch (Exception e) {
Log.e(TAG, "Error converting result " + e.toString());
}
try {
jArr = new JSONArray(json);
} catch (JSONException e) {
Log.e(TAG, "Error parsing data " + e.toString());
}
return jArr;
}
I would really appreciate any help. All the best!
It looks like I solved this issue.
The problem was in my jParser.getJSONFromUrl() method, specifically these lines:
URL url = new URL(urlSource);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setDoOutput(true);
It seems that you only set setDoOutput parameter as true, when you are using POST/PUT requests. If you want only perform a GET request, such as in my case, you should set it as false:
urlConnection.setDoOutput(false);
Otherwise, you can end up getting errors as described above.
Best regards to the Community!

Categories