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.
Related
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.
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) –
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.
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!
I have been stuck on this problem for a day or two now, so i decided to see if anyone out there could help me.
The current goal i have, is to make a HttpPost that connects to, and executes a script that i have on my Wamp server. I have implemented a class that extends AsyncTask, and includes the 3 necessary methods, that are required in order for it to work effectively.
I will first show you the code that i have used to put the variables into a Json Object, followed by the JSONParser class, that initializes the HttpPost and then executes it.
Afterwards i will tell you all about the log errors and the narrowing down of the problem; you all problem know what the problem may be already, and if you don't want to read below, briefly, it is caused by the line of code that calls the parser class.
Note: I am using this as a starting point for this type of work, so please understand that it is simple in terms of its passed parameters.
Further Note: I am using Eclipse, and i am testing with the inbuilt Emulator.
METHOD - CreateNewUser
/**
* Background Async Task to Create new user
*/
class CreateNewUser extends AsyncTask<String, String, String>{
/**
* Before starting background thread show progress dialog
*/
#Override
protected void onPreExecute(){
super.onPreExecute();
pDialog = new ProgressDialog(AddUserActivity.this);
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
/*
* Creating user
*/
#Override
protected String doInBackground(String... args){
String username = inputUsername.getText().toString();
String password = inputPassword.getText().toString();
// Building parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("username", username));
params.add(new BasicNameValuePair("password", password));
// getting JSON object
// Note that create user url accepts POST method
JSONObject json = jsonParser.makeHttpRequest(url_create_user, "POST",params);
// check log cat for response
Log.d("Create Response", json.toString());
// check for success tag
try {
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// successfully created product
Intent i = new Intent(getApplicationContext(), MainActivity.class);
startActivity(i);
// closing this screen
finish();
} else {
// failed to create product
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
#Override
protected void onPostExecute(String file_url) {
// dismiss the dialog once done
pDialog.dismiss();
}
}
Next, the JSONParser Class:
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
// function get JSON from URL
// by making HTTP POST or GET method
public JSONObject makeHttpRequest(String url, String method,
List<NameValuePair> params) {
// Making HTTP request
try {
// check for request method
if(method == "POST"){
// request method is POST
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}else if(method == "GET"){
// request method is GET
DefaultHttpClient httpClient = new DefaultHttpClient();
String paramString = URLEncodedUtils.format(params, "utf-8");
url += "?" + paramString;
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
If i remove the line : ( JSONObject json = jsonParser.makeHttpRequest(url_create_user, "POST",params); ) - of course with intending the try catch out, then the program does not crash, when i press the button that calls the CreateNewUser class.
If i do not do that, my program brings up a loading screen that swirls around until it becomes unresponsive, and asks me to close down the application.
The logs describe Async errors, and illegal state ones:
E/AndroidRuntime(1132): FATAL EXCEPTION: AsyncTask #2
E/AndroidRuntime(1132): Process: com.example.propertypanther, PID: 1132
E/AndroidRuntime(1132): java.lang.RuntimeException: An error occured while executing
doInBackground()
E/AndroidRuntime(1132): at android.os.AsyncTask$3.done(AsyncTask.java:300)
E/AndroidRuntime(1132): at
java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
E/AndroidRuntime(1132): at
java.util.concurrent.FutureTask.setException(FutureTask.java:222)
E/AndroidRuntime(1132): at java.util.concurrent.FutureTask.run(FutureTask.java:242)
E/AndroidRuntime(1132): at
android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
E/AndroidRuntime(1132): at
java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
E/AndroidRuntime(1132): at
java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
E/AndroidRuntime(1132): at java.lang.Thread.run(Thread.java:841)
E/AndroidRuntime(1132): Caused by: java.lang.IllegalStateException: Target host must not
be null, or set in parameters. scheme=null, host=null,
path=localhost/android_connect/sqlconfig/create_user.php
E/AndroidRuntime(1132): at
org.apache.http.impl.client.DefaultRequestDirector.determineRoute(DefaultRequestDirector.jav
a:591)
E/AndroidRuntime(1132): at
org.apache.http.impl.client.DefaultRequestDirector.execute
(DefaultRequestDirector.java:293)
E/AndroidRuntime(1132): at
org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
E/AndroidRuntime(1132): at
org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
E/AndroidRuntime(1132): at
org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
E/AndroidRuntime(1132): at
com.example.propertypanther.JSONParser.makeHttpRequest(JSONParser.java:51)
E/AndroidRuntime(1132): at
com.example.propertypanther.AddUserActivity$CreateNewUser.doInBackground
(AddUserActivity.java:116)
E/AndroidRuntime(1132): at
com.example.propertypanther.AddUserActivity$CreateNewUser.doInBackground
(AddUserActivity.java:1)
E/AndroidRuntime(1132): at android.os.AsyncTask$2.call(AsyncTask.java:288)
E/AndroidRuntime(1132): at java.util.concurrent.FutureTask.run(FutureTask.java:237)
E/AndroidRuntime(1132): ... 4 more
I/Choreographer(1132): Skipped 82 frames! The application may be doing too much work on
its main thread.
I/Choreographer(1132): Skipped 58 frames! The application may be doing too much work on
its main thread.
E/WindowManager(1132): android.view.WindowLeaked: Activity
com.example.propertypanther.AddUserActivity has leaked window
com.android.internal.policy.impl.PhoneWindow$DecorView{b1e3d240 V.E..... R.....ID 0,0-
729,192} that was originally added here
E/WindowManager(1132): at android.view.ViewRootImpl.<init>(ViewRootImpl.java:348)
E/WindowManager(1132): at
android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:248)
E/WindowManager(1132): at
android.view.WindowManagerImpl.addView(WindowManagerImpl.java:69)
E/WindowManager(1132): at android.app.Dialog.show(Dialog.java:286)
E/WindowManager(1132): at
com.example.propertypanther.AddUserActivity$CreateNewUser.onPreExecute
(AddUserActivity.java:97)
E/WindowManager(1132): at
android.os.AsyncTask.executeOnExecutor(AsyncTask.java:587)
E/WindowManager(1132): at android.os.AsyncTask.execute(AsyncTask.java:535)
E/WindowManager(1132): at
com.example.propertypanther.AddUserActivity$2.run(AddUserActivity.java:78)
E/WindowManager(1132): at android.os.Handler.handleCallback(Handler.java:733)
E/WindowManager(1132): at android.os.Handler.dispatchMessage(Handler.java:95)
E/WindowManager(1132): at android.os.Looper.loop(Looper.java:136)
E/WindowManager(1132): at android.app.ActivityThread.main(ActivityThread.java:5017)
E/WindowManager(1132): at java.lang.reflect.Method.invokeNative(Native Method)
E/WindowManager(1132): at java.lang.reflect.Method.invoke(Method.java:515)
E/WindowManager(1132): at
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
E/WindowManager(1132): at
com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
E/WindowManager(1132): at dalvik.system.NativeStart.main(Native Method)
The script files themselves work as far as i am aware - besides, the program never executes the script from what i can tell.
If anyone could help me out, i would really appreciate it! I understand you are all busy people, so thank you so much for taking some time out of your day if you do post ideas :)
The clue is in the exception thrown:
Caused by: java.lang.IllegalStateException: Target host must not be
null, or set in parameters. scheme=null, host=null,
path=localhost/android_connect/sqlconfig/create_user.php
I'm going to guess that there is an encoding problem, have you correctly included the "http://" at the beginning of your URL and have you printed the url you are requesting to LogCat to make sure it looks correct?