FatalShutdown in Android with httpurlconnection - java

I'm actually srugling with my application using HttpUrlConnection, I tried the simplest code found on the internet and still got a FatalShutDown in the logcat and I don't understand the problem.
Here is the code :
try {
URL url = new URL("http://www.android.com/");
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
BufferedReader r = new BufferedReader(new InputStreamReader(in));
StringBuilder total = new StringBuilder();
String line;
while ((line = r.readLine()) != null) {
total.append(line).append('\n');
}
response_textview.setText(total.toString());
urlConnection.disconnect();
}
catch (MalformedURLException e){
response_textview.setText(e.getMessage());
}
catch (IOException e){
response_textview.setText(e.getMessage());
}
And I got this in the logcat :
Thanks

Wrap your code with Asynktask doInBackground() method.

You need to make request in new thread. Probably, your code (it is only try catch) is running on main thread. This operation is denied. Try to use e.g. Thread.class to make request in new thread.

You shouldn't perform network operation on main thread. Use AsyncTask.
1. Create AsyncTask object and move your code into doInBackground method as mentioned below:
AsyncTask task = new AsyncTask<Void,String,String>(){
#Override
protected String doInBackground(Void... params) {
// perform your network operation here and return response
try {
URL url = new URL("http://www.android.com/");
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
BufferedReader r = new BufferedReader(new InputStreamReader(in));
StringBuilder total = new StringBuilder();
String line;
while ((line = r.readLine()) != null) {
total.append(line).append('\n');
}
urlConnection.disconnect();
}
catch (MalformedURLException e){
return e.getMessage();
}
catch (IOException e){
return e.getMessage();
}
return total.toString();
}
protected void onPostExecute(String response){
// response returned by doInBackGround() will be received
// by onPostExecute(String response)
response_textview.setText(response);
}
};
2. Execute task
task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);

Related

Why got null from getResult

I want to get the result of getServerResult() method but return "null". However, the Logcat inside the httpURLConnectionPost() method is normal which return "sucessful". Please answer me! why I got null outside the httpURLConnectionPost() method with getServerResult() method in this case?
private String serverResult;
public void httpURLConnectionPost(final String urlString){
new Thread(new Runnable() {
public void run() {
try {
URL url = new URL(urlString);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setUseCaches(false);
connection.connect();
String body = stringBuilder();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(connection.getOutputStream(), "UTF-8"));
writer.write(body);
writer.close();
int responseCode = connection.getResponseCode();
if(responseCode == HttpURLConnection.HTTP_OK){
InputStream inputStream = connection.getInputStream();
String line;
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
while ((line = bufferedReader.readLine()) != null) {
stringBuilderResult.append(line);
}
String result = stringBuilderResult.toString();
Log.d("MSG","result= "+result);
setServerResult(result);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
}
public void setServerResult(String serverResult){
this.serverResult = serverResult;
}
public String getServerResult(){
return serverResult;
}
D/MSG: result = successful
using getServerResult() :
D/TAG: result = null
Where are you calling httpURLConnectionPost? Regardless you should be using an async task for this, functions that call HTTP requests are not going to return anything because the code is executing and finishing before the response is received.
You need to make sure the task is complete before trying to get any data. Usually you would use an async task and in the onPostExecute portion you would do something to let the app know that data is returned.

Getting Empty response From PHP web API in android

I'm using Asynctask For network call in android Studio.I have php web API's I dont know why but Some of them Not Working in android .
Following is My AsyncTask Class...
private class AsyncAddfriend extends AsyncTask<String, String, String> {
HttpURLConnection conn;
URL url = null;
#Override
protected String doInBackground(String... params) {
try {
url = new URL("http://ishook.com/users/friends/send_friend_request_json/");
} catch (MalformedURLException e) {
e.printStackTrace();
}
try {
conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(READ_TIMEOUT);
conn.setConnectTimeout(CONNECTION_TIMEOUT);
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
Uri.Builder builder = new Uri.Builder()
.appendQueryParameter("sessionId", params[0])
.appendQueryParameter("UserId", params[1])
.appendQueryParameter("friendId", params[2]);
String query = builder.build().getEncodedQuery();
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os, "UTF-8"));
writer.write(query);
writer.flush();
writer.close();
os.close();
conn.connect();
} catch (IOException e) {
e.printStackTrace();
}
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 "exception";
} finally {
conn.disconnect();
}
}
}
I'm using same Code for other API's also they all are working fine but this api is not working.
I have Tested This API in post man its working but in not working android .
Hope You will understand My problem....

Send HTTP POST - Android

I know that this has been asked but most are out dated, and method are deprecated. I have found this solution,
new Thread( new Runnable() {
#Override
public void run() {
try {
String query = "param=" +"item"+"&other="+"num";
URL url = new URL("http://www.url.com/url_post.php");
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
//Set to POST
connection.setDoOutput(true);
connection.setRequestMethod("POST");
connection.setReadTimeout(10000);
Writer writer = new OutputStreamWriter(connection.getOutputStream());
writer.write(query);
writer.flush();
writer.close();
} catch (Exception e) {
// TODO Auto-generated catch block
Log.e(TAG, e.toString());
}
}
}).start();
But, it does not provide how to get data that is returned for example, I am return some JSON, where get I get that data that is returned?
Thanks for the help :)
Do this
//Get Response
InputStream is = connection.getInputStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
String line;
StringBuffer response = new StringBuffer();
while((line = rd.readLine()) != null) {
response.append(line);
response.append('\r');
Finally in response you will get response JSON string then do what you want to do.
For more details visit this link
http://www.xyzws.com/javafaq/how-to-use-httpurlconnection-post-data-to-web-server/139
I recommend you to use this project as library:
https://github.com/matessoftwaresolutions/AndroidHttpRestService
It's extremely easy and I use it for all my projects. I commited it to Github because it is difficult for me to find an easy Rest client for general purpose.
I'm going to commit an update for integration with Android Studio ASAP.
I hope it helps!!
InputStream in = connection.getInputStream();
JsonReader reader = new JsonReader(new InputStreamReader(in, "UTF-8"));
Add this part after your writer.close()
connection.connect();
int statusCode = connection.getResponseCode();
Log.d("ON POST", " The status code is " + statusCode);
if (statusCode == 200) {
is = new BufferedInputStream(connection.getInputStream());
String response = convertInputStreamToString(is);
Log.d("ON POST", "The response is " + response);
return response;
} else {
Log.d("ON POST", "On Else");
return "";
}
The ConvertInputStreamToString() should be created to return your json as string
public static String convertInputStreamToString(InputStream in) {
BufferedReader reader = null;
StringBuffer response = new StringBuffer();
try {
reader = new BufferedReader(new InputStreamReader(in));
String line = "";
while ((line = reader.readLine()) != null) {
response.append(line);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return response.toString();
}

network timeout exception in android

I developed android app and tested in Samsung tab 2.The code fetch the data from java server page which hosted in server.It works day before,but now it shows network time out exception during urlConnection.getInputStream() .I d't change anything in my code. pls help me to overcome the error.
try {
String tally_ipaddr="XXXXXXX";
URL url = new URL(tally_ipaddr+"/Iplogin.jsp");
urlConnection = (HttpURLConnection) url.openConnection();
String line = "";
InputStreamReader isr = new InputStreamReader(urlConnection.getInputStream());
BufferedReader reader = new BufferedReader(isr);
StringBuilder sb = new StringBuilder();
while ((line = reader.readLine()) != null){
sb.append(line);
}
Toast.makeText(MyActivity.this, sb.toString(), Toast.LENGTH_LONG).show();
}
catch (Exception e) {
e.printStackTrace();
Toast.makeText(MyActivity.this, e.toString(), Toast.LENGTH_LONG).show();
}
class UrlFetch extends AsyncTask<Void,Void,Void>
{
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
try {
String tally_ipaddr="XXXXXXX";
URL url = new URL(tally_ipaddr+"/Iplogin.jsp");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(5000); // 5 seconds
conn.setRequestMethod("GET");
conn.connect();
BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
while ((line = rd.readLine()) != null) {
System.out.println(line);
}
conn.disconnect();
}
catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
and call the asynctask like given below
new UrlFetch().execute();
Hope the above code will works for you
I notice the address ends with "Iplogin.jsp".
Make sure the server is accepting connections from the IP address of your device. I think the IP address of your device has changed and the server is no longer responding to requests from that device.
The fact that you can access the service from your desktop browser but NOT from the device browser is highly suspect.

Java - URL Connection in Threads

I currently have a project where different parameters are requested from an online CGI file, and each request is supposed to be processed in different threads. When I run my code by itself it works great, however it doesn't seem to connect when I put it in a thread.
My code is below:
public void run() {
connect();
}
public synchronized void connect(){
StringBuffer response = new StringBuffer("");
try {
String data = "year=" + year + "&top=" + numNames + "number=";
// Send data
URL url = new URL("http://www.ssa.gov/cgi-bin/popularnames.cgi");
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(data);
wr.flush();
// Get the response
BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
while ((line = rd.readLine()) != null) {
response.append(line);
}
wr.close();
rd.close();
} catch (Exception e) {
System.out.println(e);
}
System.out.println(response);
}
}
Remove the synchronized call on connect. That should solve your problem
public synchronized void connect(){

Categories

Resources