My code is as shown below:
public class YActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
try {
Log.d(TAG, "onCreate: page response" + getResponseFromUrl("www.iammjet.in"));
} catch (IOException e) {
e.printStackTrace();
}
}
public String getResponseFromUrl(String url) throws IOException {
HttpClient httpclient = new DefaultHttpClient(); // Create HTTP Client
HttpGet httpget = new HttpGet(URL); // Set the action you want to do
HttpResponse response = httpclient.execute(httpget); // Executeit
HttpEntity entity = response.getEntity();
InputStream is = entity.getContent(); // Create an InputStream with the response
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);
String resString = sb.toString();
is.close();
return resString;
}
}
Now what happens here is it gives me Target host must not be null, or set in parameters. scheme=null, host=null, path=www.iammjet.in error , what should I insert to make it work?
I am using compileSdkVersion 24. To support HttpClient I have added in my build.gradle as follows:
android {
compileSdkVersion 24
buildToolsVersion "25.0.1"
useLibrary 'org.apache.http.legacy'
}
My error stack trace is as shown below:
java.lang.RuntimeException: Unable to start activity ComponentInfo{demand.inn.com.xyz.staging/demand.inn.com.xyz.activity.YActivity}: android.os.NetworkOnMainThreadException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2325)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387)
at android.app.ActivityThread.access$800(ActivityThread.java:151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5254)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
Caused by: android.os.NetworkOnMainThreadException
at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1147)
at java.net.InetAddress.lookupHostByName(InetAddress.java:418)
at java.net.InetAddress.getAllByNameImpl(InetAddress.java:252)
at java.net.InetAddress.getAllByName(InetAddress.java:215)
at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:142)
at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:169)
at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:124)
at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:365)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:560)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:492)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:470)
at demand.inn.com.quflip.activity.YActivity.getResponseFromUrl(YActivity.java:328)
at demand.inn.com.quflip.activity.QuFlipActivity.onCreate(QuFlipActivity.java:94)
at android.app.Activity.performCreate(Activity.java:5990)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1106)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2278)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387)
at android.app.ActivityThread.access$800(ActivityThread.java:151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5254)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
--------- beginning of crash
There are three major problems with your code:
Your URL is badly formatted (giving the error)
You are doing networking on the main thread
The client library you are trying to use is being removed from later versions of android. Use an URLConnection if you can.
Formatting your URL
Your browser lies to you. www.iammjet.in is not an URL. It's just a host name. To be an URL you MUST have a scheme, host and path (as the error tells you.
http://www.iammjet.in/ is valid. It has the scheme http, host www.iammjet.in and path /. Because you have given it just the hostname it's misinterpreted it to be just the path and said that the hostname is null.
pass "http://www.iammjet.in" instead of "www.iammjet.in"
Related
I want to build a simple android mobile app, that will communicate through REST API with a python-Flask server -
So the android client will run on my Sumsung Galaxy J7 Prime phone (using USB connection through an android-studio script which runs on my computer), and the python-Flask server will run on my computer (using running python-Flask file through PyCharm workspace).
All i want to do is to pass a simple message between those client and server, with a regular connection (not localhost).
This is the simple server code:
from flask import Flask
app = Flask(__name__)
#app.route("/RESTfulExample/json/product/get")
def hello():
return "Hello World !!"
if __name__ == "__main__":
app.run(host='0.0.0.0', debug=True)
This code works well when i run this server, and enter the URL address with google chrome URL: http://127.0.0.1:5000/RESTfulExample/json/product/get
It works fine also when I run a script in Jave which sends this URL to the server (with localhost communication):
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
public class firstJava {
public static void main(String[] args) {
try {
URL url = new URL("http://localhost:5000/RESTfulExample/json/product/get");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("Accept", "application/json");
if (conn.getResponseCode() != 200) {
throw new RuntimeException("Failed : HTTP error code : "
+ conn.getResponseCode());
}
BufferedReader br = new BufferedReader(new InputStreamReader(
(conn.getInputStream())));
String output;
System.out.println("Output from Server .... \n");
while ((output = br.readLine()) != null) {
System.out.println(output);
}
conn.disconnect();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
The output is:
Output from Server ....
Hello World !!
The problem comes when i use the exact same code in the my andriod-studio project, except of changing the IP address from localhost(127.0.0.1) to the IP of my computer (10.0.0.54):
public void buttonClicked (View view){
EditText editText = (EditText) findViewById(R.id.passwordEditText);
try {
URL url = new URL("http://10.0.0.54:5000/RESTfulExample/json/product/get");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("Accept", "application/json");
System.out.println(conn.getResponseCode());
if (conn.getResponseCode() != 200) {
throw new RuntimeException("Failed : HTTP error code : "
+ conn.getResponseCode());
}
BufferedReader br = new BufferedReader(new InputStreamReader(
(conn.getInputStream())));
String output;
System.out.println("Output from Server .... \n");
while ((output = br.readLine()) != null) {
editText.setText(output);
}
conn.disconnect();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
When I run this script in android studio, the application in my phone collapses, and in the console in the android-studio, the error lines are those:
I/System.out: (HTTPLog)-Static: isSBSettingEnabled false
I/System.out: (HTTPLog)-Static: isSBSettingEnabled false
D/AndroidRuntime: Shutting down VM
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.owner.firstapp, PID: 25703
java.lang.IllegalStateException: Could not execute method for android:onClick
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:293)
at android.view.View.performClick(View.java:5721)
at android.widget.TextView.performClick(TextView.java:10931)
at android.view.View$PerformClick.run(View.java:22620)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:7409)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Method.invoke(Native Method)
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:288)
at android.view.View.performClick(View.java:5721)
at android.widget.TextView.performClick(TextView.java:10931)
at android.view.View$PerformClick.run(View.java:22620)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:7409)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)
Caused by: android.os.NetworkOnMainThreadException
at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1273)
at libcore.io.BlockGuardOs.connect(BlockGuardOs.java:110)
at libcore.io.IoBridge.connectErrno(IoBridge.java:137)
at libcore.io.IoBridge.connect(IoBridge.java:122)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:183)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:452)
at java.net.Socket.connect(Socket.java:884)
at com.android.okhttp.internal.Platform.connectSocket(Platform.java:117)
at com.android.okhttp.internal.http.SocketConnector.connectRawSocket(SocketConnector.java:438)
at com.android.okhttp.internal.http.SocketConnector.connectCleartext(SocketConnector.java:105)
at com.android.okhttp.Connection.connect(Connection.java:1333)
at com.android.okhttp.Connection.connectAndSetOwner(Connection.java:1412)
at com.android.okhttp.OkHttpClient$1.connectAndSetOwner(OkHttpClient.java:131)
at com.android.okhttp.internal.http.HttpEngine.nextConnection(HttpEngine.java:485)
at com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:466)
at com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:372)
at com.android.okhttp.internal.huc.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:476)
at com.android.okhttp.internal.huc.HttpURLConnectionImpl.getResponse(HttpURLConnectionImpl.java:418)
at com.android.okhttp.internal.huc.HttpURLConnectionImpl.getResponseCode(HttpURLConnectionImpl.java:540)
at com.example.owner.firstapp.MainActivity.buttonClicked(MainActivity.java:44)
at java.lang.reflect.Method.invoke(Native Method)
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:288)
at android.view.View.performClick(View.java:5721)
at android.widget.TextView.performClick(TextView.java:10931)
at android.view.View$PerformClick.run(View.java:22620)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:7409)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)
I/Process: Sending signal. PID: 25703 SIG: 9
Application terminated.
As the separated line above tells, the problem is with line 44 - System.out.println(conn.getResponseCode());
which means, that for some reason, the conn.getResponseCode() isn't work.
So i understand that the problem occures when i stop use the localhost connection and move to a regular connection between 2 devices. I just don't know how to fix it.
I didn't know i will stuck so much time with a simple server-client communication.. I will glad if someone here will help me solve this simple problem.
Thank you very much in advance, and sorry for my bad english :)
I know you posted this few months ago, but have you thought enabling internet permissions in your manifest file ?
I'm trying to retrieve some videos with a GameId from Helix API of Twitch. Using a REST client I can retrieve the data and it works, but when I try it on android it won't work.
I get a response code 200, but when I try to access the InputStream I get a FileNotFoundException.
Here's the code I'm using:
HttpURLConnection urlConnection = null;
URL url = new URL(urlString);
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestProperty("Client-ID", Configuration.TWITCH_CLIENT_ID);
urlConnection.setRequestMethod("GET");
urlConnection.connect();
System.out.println("ResponseCode: " + urlConnection.getResponseCode());
BufferedReader br = new BufferedReader(new InputStreamReader(url.openStream()));
StringBuilder sb = new StringBuilder();
String line;
while ((line = br.readLine()) != null) {
sb.append(line + "\n");
}
br.close();
String jsonString = sb.toString();
System.out.println("JSON: " + jsonString);
return new JSONObject(jsonString);
Where Configuration.TWITCH_CLIENT_ID is my Twitch Client ID.
The output I get is:
01-16 02:19:19.658 21184-21242/ec.com.aurinow.aurinow I/System.out: ResponseCode: 200
01-16 02:19:20.133 21184-21242/ec.com.aurinow.aurinow W/System.err: java.io.FileNotFoundException: https://api.twitch.tv/helix/videos?game_id=9435
01-16 02:19:20.133 21184-21242/ec.com.aurinow.aurinow W/System.err: at com.android.okhttp.internal.huc.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:238)
01-16 02:19:20.133 21184-21242/ec.com.aurinow.aurinow W/System.err: at com.android.okhttp.internal.huc.DelegatingHttpsURLConnection.getInputStream(DelegatingHttpsURLConnection.java:210)
01-16 02:19:20.133 21184-21242/ec.com.aurinow.aurinow W/System.err: at com.android.okhttp.internal.huc.HttpsURLConnectionImpl.getInputStream(HttpsURLConnectionImpl.java)
01-16 02:19:20.133 21184-21242/ec.com.aurinow.aurinow W/System.err: at java.net.URL.openStream(URL.java:470)
01-16 02:19:20.133 21184-21242/ec.com.aurinow.aurinow W/System.err: at ec.com.aurinow.aurinow.TwitchSearchActivity$RetrieveResponseTask.sendRequest(TwitchSearchActivity.java:272)
01-16 02:19:20.133 21184-21242/ec.com.aurinow.aurinow W/System.err: at ec.com.aurinow.aurinow.TwitchSearchActivity$RetrieveResponseTask.doInBackground(TwitchSearchActivity.java:233)
01-16 02:19:20.133 21184-21242/ec.com.aurinow.aurinow W/System.err: at ec.com.aurinow.aurinow.TwitchSearchActivity$RetrieveResponseTask.doInBackground(TwitchSearchActivity.java:229)
01-16 02:19:20.133 21184-21242/ec.com.aurinow.aurinow W/System.err: at android.os.AsyncTask$2.call(AsyncTask.java:295)
01-16 02:19:20.134 21184-21242/ec.com.aurinow.aurinow W/System.err: at java.util.concurrent.FutureTask.run(FutureTask.java:237)
01-16 02:19:20.134 21184-21242/ec.com.aurinow.aurinow W/System.err: at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:234)
01-16 02:19:20.134 21184-21242/ec.com.aurinow.aurinow W/System.err: at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
01-16 02:19:20.134 21184-21242/ec.com.aurinow.aurinow W/System.err: at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
01-16 02:19:20.134 21184-21242/ec.com.aurinow.aurinow W/System.err: at java.lang.Thread.run(Thread.java:818)
Thank You Guys
EDIT: So I make it work using urlConnection.getInputStream() instead of url.openStream(). I don't why in this specific case it works like that.
You should get the response from the HttpURLConnection object. That is where the response will be.
The URL object is as the documentation puts it:
Class URL represents a Uniform Resource Locator, a pointer to a
"resource" on the World Wide Web.
So the URL only points to the resource you wish to retrieve from. The HttpURLConnection object is what actually contains the response after being pointed to the resource.
The HttpURLConnection object:
Each HttpURLConnection instance is used to make a single request but
the underlying network connection to the HTTP server...
So do this instead:
(new InputStreamReader(urlConnection.getInputStream()));
HttpURLConnection urlConnection = null;
URL url = new URL(urlString);
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestProperty("Client-ID", Configuration.TWITCH_CLIENT_ID);
urlConnection.setRequestMethod("GET");
urlConnection.connect();
System.out.println("ResponseCode: " + urlConnection.getResponseCode());
BufferedReader br = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
StringBuilder sb = new StringBuilder();
String line;
while ((line = br.readLine()) != null) {
sb.append(line + "\n");
}
br.close();
String jsonString = sb.toString();
System.out.println("JSON: " + jsonString);
return new JSONObject(jsonString);
I need to send a HTTP post request and receive the output but when I run the app the app crashes.
Below is the code I use.
public String getRequest(String url) {
StringBuilder responseOutput = new StringBuilder();
try {
URL uri = new URL(url);
HttpURLConnection connection = (HttpURLConnection)uri.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("USER-AGENT", "Mozilla/5.0");
connection.setRequestProperty("ACCEPT-LANGUAGE", "en-US,en;0.5");
connection.setDoOutput(true);
DataOutputStream dStream = new DataOutputStream(connection.getOutputStream());
dStream.flush();
dStream.close();
BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line = "";
while((line = br.readLine()) != null ) {
responseOutput.append(line);
}
br.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return responseOutput.toString();
}
This is the crash log.
05-18 16:34:50.915 18272-18272/com.prisonvoicemail.appupdater E/AndroidRuntime:
FATAL EXCEPTION: main
Process: com.prisonvoicemail.appupdater, PID: 18272
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.prisonvoicemail.appupdater/com.prisonvoicemail.appupdater.MainActivity}: android.os.NetworkOnMainThreadException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2426)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2490)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1354)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5443)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:728)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)
Caused by: android.os.NetworkOnMainThreadException
at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1287)
at java.net.InetAddress.lookupHostByName(InetAddress.java:431)
at java.net.InetAddress.getAllByNameImpl(InetAddress.java:252)
at java.net.InetAddress.getAllByName(InetAddress.java:215)
at com.android.okhttp.internal.Network$1.resolveInetAddresses(Network.java:29)
at com.android.okhttp.internal.http.RouteSelector.resetNextInetSocketAddress(RouteSelector.java:188)
at com.android.okhttp.internal.http.RouteSelector.nextProxy(RouteSelector.java:157)
at com.android.okhttp.internal.http.RouteSelector.next(RouteSelector.java:100)
at com.android.okhttp.internal.http.HttpEngine.createNextConnection(HttpEngine.java:357)
at com.android.okhttp.internal.http.HttpEngine.nextConnection(HttpEngine.java:340)
at com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:330)
at com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:248)
at com.android.okhttp.internal.huc.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:437)
at com.android.okhttp.internal.huc.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:114)
at com.android.okhttp.internal.huc.HttpURLConnectionImpl.getOutputStream(HttpURLConnectionImpl.java:245)
at com.android.okhttp.internal.huc.DelegatingHttpsURLConnection.getOutputStream(DelegatingHttpsURLConnection.java:218)
at com.android.okhttp.internal.huc.HttpsURLConnectionImpl.getOutputStream(HttpsURLConnectionImpl.java)
at com.prisonvoicemail.appupdater.HTTPRequest.getRequest(HTTPRequest.java:72)
at com.prisonvoicemail.appupdater.MainActivity.onCreate(MainActivity.java:79)
at android.app.Activity.performCreate(Activity.java:6259)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1130)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2379)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2490)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1354)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5443)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:728)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)
Android doens't allow network calls on main thread(which controls the ui) in order to keep him free , you need to do some easy multithreading , you can take a look at Asynctask for that operation , or use an outside library such as Retrofit , Volley , Loopj etc...
You can start with Asynctask for a first lesson:
http://developer.android.com/reference/android/os/AsyncTask.html
put the code of the call in doinbackground ( another thread and not the main thread ) , after getting your result and finishing the doinbackground you'll get to OnPost method (is on the main thread , you can make ui changes here)
Hope it helps.
You are having NetworkOnMainThreadException, this is because you are calling this method from application main thread.
You should not do any network operation (blocking operation) in the main thread, this will stuck your application until the operation is finished. Besides, wrap the function call inside an AsyncTask then call AsyncTask.execute() this will fix your issue. e.g
AsyncTask task = new AsyncTask() {
#Override
protected Object doInBackground(Object[] params) {
//do your stuff here
return null;
}
};
task.execute();
Hope that helps. cheers :)
Here is the code:
#Override
public String doInBackground(String... params)
{
try
{
URL url = new URL("http://spreadsheets.google.com/tq?key=BLAHBLOAHBLAH");
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection(); //Cast HttpUrlConnection because URL does not contain methods available to url, creates object
httpURLConnection.setRequestMethod("GET"); //Request data from source
httpURLConnection.setDoInput(true);
httpURLConnection.connect(); //Object actually connects, connect() invoked by getInputStream() etc.
//Reads data from network stream
InputStream inputStream = httpURLConnection.getInputStream();
//Rather than read one character at a time from the network or disk, BufferedReader reads a larger block at a time
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
//Used to create mutable string e.g. append()
StringBuilder stringBuilder = new StringBuilder();
String line = "";
//Change stream data to StringBuilder data
while ((line = bufferedReader.readLine()) != null)
{
stringBuilder.append(line + "\n");
}
String result = stringBuilder.toString();
bufferedReader.close();
inputStream.close();
httpURLConnection.disconnect();
return result;
}
catch(IOException e)
{
e.printStackTrace();
}
return null;
}
I'm basically downloading the JSON data from Google Spreadsheets, but the result returned from the doInBackground function continues to return some sort of a null object reference. What does this mean?...
EDIT*
Here is my logcat:
07-28 12:41:30.289 3796-3891/com.example.steven.app E/AndroidRuntime: FATAL EXCEPTION: AsyncTask #2
Process: com.example.steven.app, PID: 3796
java.lang.RuntimeException: An error occurred while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:309)
at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:354)
at java.util.concurrent.FutureTask.setException(FutureTask.java:223)
at java.util.concurrent.FutureTask.run(FutureTask.java:242)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:234)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
at java.lang.Thread.run(Thread.java:818)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.app.AlertDialog.setMessage(java.lang.CharSequence)' on a null object reference
at com.example.steven.database.DownloadGS.doInBackground(DownloadGS.java:95)
at com.example.steven.database.DownloadGS.doInBackground(DownloadGS.java:49)
at android.os.AsyncTask$2.call(AsyncTask.java:295)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:234)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
at java.lang.Thread.run(Thread.java:818)
Picture of what is actually being stored inside String result...
My problem was:
URL url = new URL("http://spreadsheets.google.com/tq?key=BLAHBLOAHBLAH");
I found out that by reading here:
URLConnection Doesn't Follow Redirect
the setFollowRedirect and setInstanceFollowRedirects only work automatically when the redirected protocol is same . ie from http to http and https to https. (Shalvika)
I changed the statement to:
URL url = new URL("https://spreadsheets.google.com/tq?key=BLAHBLOAHBLAH");
Your code looks fine, the problem is that you are not allowed to get data from that URL.
On hitting this URL "http://spreadsheets.google.com/tq?key=BLAHBLOAHBLAH"
I am getting following response, so i guess you are getting access denied from server.
google.visualization.Query.setResponse (
{
"version": "0.6",
"status": "error",
"errors": [
{
"reason": "access_denied",
"message": "Access denied",
"detailed_message": "Access denied"
}]
}
)
I am trying to get JSON from Google Maps Geocoding API using okHTTP (http://square.github.io/okhttp/) in Android Studio and my program crashes with the following error log:
java.lang.IllegalStateException: Could not execute method of the activity
at android.view.View$1.onClick(View.java:4020)
at android.view.View.performClick(View.java:4780)
at android.view.View$PerformClick.run(View.java:19866)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5257)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at android.view.View$1.onClick(View.java:4015)
at android.view.View.performClick(View.java:4780)
at android.view.View$PerformClick.run(View.java:19866)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5257)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
Caused by: android.os.NetworkOnMainThreadException
at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1147)
at java.net.InetAddress.lookupHostByName(InetAddress.java:418)
at java.net.InetAddress.getAllByNameImpl(InetAddress.java:252)
at java.net.InetAddress.getAllByName(InetAddress.java:215)
at com.squareup.okhttp.Dns$1.lookup(Dns.java:39)
at com.squareup.okhttp.internal.http.RouteSelector.resetNextInetSocketAddress(RouteSelector.java:184)
at com.squareup.okhttp.internal.http.RouteSelector.nextProxy(RouteSelector.java:153)
at com.squareup.okhttp.internal.http.RouteSelector.next(RouteSelector.java:95)
at com.squareup.okhttp.internal.http.HttpEngine.createNextConnection(HttpEngine.java:345)
at com.squareup.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:328)
at com.squareup.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:246)
at com.squareup.okhttp.Call.getResponse(Call.java:276)
at com.squareup.okhttp.Call$ApplicationInterceptorChain.proceed(Call.java:234)
at com.squareup.okhttp.Call.getResponseWithInterceptorChain(Call.java:196)
at com.squareup.okhttp.Call.execute(Call.java:79)
...
The last error log's Caused by gives a hint that the issue might be in okHTTP security communication. I did not set it up because I can not figure out whether I need to do it at all and how to do it then. This page might be relevant, but I am not sure: https://github.com/square/okhttp/wiki/HTTPS
Communication with Google Geocoding API happens through https.
Here is the code I am trying to use:
OkHttpClient client = new OkHttpClient();
String strAddress = "Winnetka";
String googleMapsAPIKey = this.getString(R.string.google_maps_api_key);
String url = null;
try {
url = "https://maps.googleapis.com/maps/api/geocode/json" +
"?address=" + URLEncoder.encode(strAddress, "UTF-8") + "&key=" + googleMapsAPIKey;
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
return null;
}
Request request = new Request.Builder()
.url(url)
.build();
try {
Response response = client.newCall(request).execute();
} catch (IOException e) {
e.printStackTrace();
return null;
}
It fails on the line Response response = client.newCall(request).execute();
I logged out the url that I formed and it looks identical to the one that is used in the examples on the API's website (https://developers.google.com/maps/documentation/geocoding/intro):
https://maps.googleapis.com/maps/api/geocode/json?address=Winnetka&key=...
Could anyone, please, help?
Your issue: Caused by: android.os.NetworkOnMainThreadException
You should use OkHttps async method:
client.newCall(request).enqueue(new Callback() {
#Override
public void onFailure(Request request, IOException throwable) {
throwable.printStackTrace();
}
#Override
public void onResponse(Response response) throws IOException {
if (!response.isSuccessful()) {
throw new IOException("Unexpected code " + response);
}
// Do Stuff
});