FileNotFoundException encountered when trying to send JSON over network [duplicate] - java

This question already has answers here:
FileNotFoundException while getting the InputStream object from HttpURLConnection
(8 answers)
Closed 6 years ago.
My code to that sends JSON over the network works until OutputStream is invoked, but when I try actually sending the data, I get the following exception. Can anyone help me figure it out?
java.io.FileNotFoundException: http://hmkcode.appspot.com/jsonservlet
at
com.android.okhttp.internal.huc.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:238)
at app.test.testapp2.MainActivity$HttpAsyncTask.doInBackground(MainActivity.java:84)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button) findViewById(R.id.accept);
textView = (TextView) findViewById(R.id.textView);
editName = (EditText) findViewById(R.id.editName);
editCountry = (EditText) findViewById(R.id.editCountry);
editTwitter = (EditText) findViewById(R.id.editTwitter);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
HttpAsyncTask httpAsyncTask = new HttpAsyncTask(MainActivity.this);
httpAsyncTask.execute("http://hmkcode.appspot.com/jsonservlet", editName.getText().toString(), editCountry.getText().toString(), editTwitter.getText().toString());
}
});
}
private class HttpAsyncTask extends AsyncTask<String, Void, String> {
private MainActivity mainActivity;
String result = "";
HttpAsyncTask(MainActivity mainActivity) {
this.mainActivity = mainActivity;
}
#Override
protected String doInBackground(String... strings) {
Person person = new Person();
person.setName(strings[1]);
person.setCountry(strings[2]);
person.setTwitter(strings[3]);
try {
URL url = new URL(strings[0]);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
String json = "";
JSONObject jsonObject = new JSONObject();
jsonObject.accumulate("name", "!!!");
jsonObject.accumulate("country", "###");
jsonObject.accumulate("twitter", "####");
json = jsonObject.toString();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true);
httpURLConnection.setDoInput(true);
httpURLConnection.setRequestProperty("Accept", "application/json");
httpURLConnection.setRequestProperty("content-type", "application/json");
InputStream is = httpURLConnection.getInputStream();
OutputStream os = httpURLConnection.getOutputStream();
os.write(json.getBytes("utf-8"));
os.flush();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(is));
String line = "";
while ((line = bufferedReader.readLine()) != null) {
result += line;
}
is.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
#Override
protected void onPostExecute(String result) {
str = result;
mainActivity.runOnUiThread(new Runnable() {
#Override
public void run() {
try {
JSONArray jsonArray = new JSONArray(str);
mainActivity.textView.setText(jsonArray.toString());
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
}
}
W/System.err: java.io.FileNotFoundException: http://hmkcode.appspot.com/jsonservlet
W/System.err: at com.android.okhttp.internal.huc.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:238)
W/System.err: at app.test.testapp2.MainActivity$HttpAsyncTask.doInBackground(MainActivity.java:84)
.....

This is equivalent to HTTP status 404 - Not Found.

Related

Content from web-site won't display in my logcat

I am trying to download content of some random web content to my Logcat. I already did this many time but now I am getting only 2020-05-17 13:24:20.850 24632-24632/com.example.jsondownload I/RezultatĀ URLa:: { and nothing else.Content is some random JSON small sample and I want to show it in my logcat, and nothing else.
I added internet permission.
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String string = "https://api.openweathermap.org/data/2.5/weather?q=London,uk&appid=6...3";
DownloadAsync downloadAsync = new DownloadAsync();
downloadAsync.execute(string);
}
public static class DownloadAsync extends AsyncTask<String,Void,String> {
#Override
protected String doInBackground(String... strings) {
StringBuilder rezultat = new StringBuilder();
URL url;
HttpURLConnection httpURLConnection;
try {
url = new URL(strings[0]);
httpURLConnection = (HttpURLConnection) url.openConnection();
InputStream inputStream = httpURLConnection.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
int podaci = inputStreamReader.read();
while (podaci!=-1){
char trenutnoSlovoKojeSeCita = (char) podaci;
rezultat.append(trenutnoSlovoKojeSeCita);
podaci = inputStream.read();
}
return rezultat.toString();
}
catch (Exception e){
e.printStackTrace();
return "Neuspesno";
}
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
Log.i("Rezultat URLa: ",s);
}
}
}
I find a solution: I added BufferReader:
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String string = "https://api.openweathermap.org/data/2.5/weather?q=Belgrade&appid=6c5022949de1b8e8448bc7232238dcf3";
DownloadAsync downloadAsync = new DownloadAsync();
downloadAsync.execute(string);
}
public static class DownloadAsync extends AsyncTask<String,Void,String> {
#Override
protected String doInBackground(String... strings) {
StringBuilder rezultat = new StringBuilder();
URL url;
HttpURLConnection httpURLConnection;
try {
url = new URL(strings[0]);
httpURLConnection = (HttpURLConnection) url.openConnection();
InputStream inputStream = httpURLConnection.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream, Charset.forName("UTF-8"));
BufferedReader reader = new BufferedReader(inputStreamReader);
String line = reader.readLine();
while (line!=null){
rezultat.append(line);
line = reader.readLine();
}
return rezultat.toString();
}
catch (Exception e){
e.printStackTrace();
return "Neuspesno " ;
}
}
#Override
protected void onPostExecute(String rezultat) {
super.onPostExecute(rezultat);
try {
JSONObject jsonObject = new JSONObject(rezultat);
String weatherInfo = jsonObject.getString("weather");
JSONArray arr = new JSONArray(weatherInfo);
for (int i = 0; i < arr.length();i++){
JSONObject jsonObject1 = arr.getJSONObject(i);
String main = jsonObject1.getString("main");
String desc = jsonObject1.getString("description");
Log.i("main: ",main);
Log.i("description: ",desc);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}

Refresh json url when button pressed

I found out how i did what i asked in an earlyer question but i am wondering how i can reload URL url = new URL("https://www.lurkinator.net/api/data?username="+typedText+""); After the user presses a button? I have a button called "button" i want it to refresh the url since i have the typedText at the end and when user edits the edittext i want data to refresh from the api
Here is my code. And here is a screenshot of how the app looks so you have an idea.
Photo
public class MainActivity extends AppCompatActivity {
TextView points, username;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
points = (TextView) findViewById(R.id.textView8);
username = (TextView) findViewById(R.id.textView9);
new getData().execute();
}
class getData extends AsyncTask<String, String, String> {
// get EditText by id and store it into "inputTxt"
EditText USERNAME = (EditText) findViewById(R.id.UserSet);
// Store EditText - Input in variable
String typedText = USERNAME.getText().toString();
HttpURLConnection urlConnection = null;
#Override
protected String doInBackground(String... args) {
StringBuilder result = new StringBuilder();
try {
URL url = new URL("https://www.lurkinator.net/api/data?username="+typedText+"");
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setDoOutput(true);
urlConnection.connect();
BufferedReader br=new BufferedReader(new InputStreamReader(url.openStream()));
char[] buffer = new char[1024];
String line;
while ((line = br.readLine()) != null) {
result.append(line+"\n");
}
br.close();
String jsonString = result.toString();
System.out.println("JSON: " + jsonString);
} catch (Exception e) {
e.printStackTrace();
} finally {
urlConnection.disconnect();
}
return result.toString();
}
#Override
protected void onPostExecute(String result) {
try {
JSONArray jsonArray = new JSONArray(result);
JSONObject jsonObject = jsonArray.getJSONObject(0);
String t = jsonObject.getString("points");
String u = jsonObject.getString("username");
points.setText(t);
username.setText(u);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
Thanks!
Add ok button click listener
Button clickButton = (Button) findViewById(R.id.clickButton);
clickButton.setOnClickListener( new OnClickListener() {
#Override
public void onClick(View v) {
new getData().execute();
}
});

Can we use two Interface for two different asynctask

AsyncResponse.java:
public interface AsyncResponse {
void ProcessFinish(String Output);
}
AsyncResponseSecond.java:
public interface AsyncResponseSecond {
void ProcessFinishSecond(String Output);
}
This is for Asynctask OnPostExecute to get the result and save it in TextView.
I want to Know if the method which I am Using is correct or not . I am not getting the response
Asyncresponse is for one button and AsyncresponseSecond is for other Button
IntimeWorker.java:
public class InTImeWorker extends AsyncTask<String, Void, String> {
Context context;
AlertDialog alertDialog;
public AsyncResponse delegate = null;
InTImeWorker(Context ctx) {
context = ctx;
}
#Override
protected void onPreExecute() {
alertDialog = new AlertDialog.Builder(context).create();
alertDialog.setTitle("In Time Status !");
}
#Override
protected void onPostExecute(String result) {
delegate.ProcessFinish(result);
}
#Override
protected String doInBackground(String... params) {
String Emp_id = params[0];
String in_time_url = "http://192.168.0.107/RTOS/intime.php";
try {
URL url = new URL(in_time_url);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
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("emp_id", "UTF-8") + "=" + URLEncoder.encode(Emp_id, "UTF-8");
bufferedWriter.write(post_data);
bufferedWriter.flush();
bufferedWriter.close();
outputStream.close();
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();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
OuttimeWorker.java:
public class OutTimeWorker extends AsyncTask<String,Void,String> {
Context context;
AlertDialog alertDialog;
public AsyncResponseSecond delegate = null;
OutTimeWorker(Context ctx){
context = ctx;
}
#Override
protected void onPreExecute() {
alertDialog = new AlertDialog.Builder(context).create();
alertDialog.setTitle("Out Time Status !");
}
#Override
protected void onPostExecute(String result) {
delegate.ProcessFinishSecond(result);
}
#Override
protected String doInBackground(String... params) {
String Emp_id = params[0];
String out_time_url = "http://192.168.0.107/RTOS/outtime.php";
try {
URL url = new URL(out_time_url);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
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("emp_id","UTF-8")+"="+URLEncoder.encode(Emp_id,"UTF-8");
bufferedWriter.write(post_data);
bufferedWriter.flush();
bufferedWriter.close();
outputStream.close();
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();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
EmployeeActivity.java:
public class EmployeeActivity extends AppCompatActivity implements AsyncResponse , AsyncResponseSecond {
TextView name, In_time, Out_time;
SharedPreferences sp,sp1;
Button in_time_button, out_time_button;
private static final String KEY_IN_TIME_TEXTVIEW = "intimetextview_key";
private static final String KEY_OUT_TIME_TEXTVIEW = "outtimetextview_key";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_employee);
name = findViewById(R.id.text_name);
sp = getSharedPreferences("attendlogin", MODE_PRIVATE);
String emp_name = sp.getString("name", null);
name.setText(emp_name);
in_time_button = findViewById(R.id.buttonlogin);
out_time_button = findViewById(R.id.buttonlogout);
out_time_button.setEnabled(false);
In_time = findViewById(R.id.text_in_time);
Out_time = findViewById(R.id.text_out_time);
public void OnAttendLogin(View view) {
sp = getSharedPreferences("attendlogin", MODE_PRIVATE);
String emp_id = sp.getString("emp_id", null);
InTImeWorker inTImeWorker = new InTImeWorker(this);
inTImeWorker.delegate = (AsyncResponse) this;
inTImeWorker.execute(emp_id);
//shared pref for saving In_time in textview
sp1 = getSharedPreferences("InTime", MODE_PRIVATE);
SharedPreferences.Editor editor1 = sp1.edit();
String in_time_sharedpref = In_time.getText().toString();
editor1.putString("in_time_sp", in_time_sharedpref);
editor1.apply();
editor1.commit();
out_time_button.setEnabled(true);
in_time_button.setEnabled(false);
}
public void OnLogout(View view) {
sp = getSharedPreferences("attendlogin", MODE_PRIVATE);
String emp_id = sp.getString("emp_id", null);
OutTimeWorker outTimeWorker = new OutTimeWorker(this);
outTimeWorker.delegate = (AsyncResponseSecond) this;
outTimeWorker.execute(emp_id);
out_time_button.setEnabled(false);
in_time_button.setEnabled(false);
}
#Override
public void ProcessFinish(String Output) {
In_time.setText(Output);
}
#Override
public void ProcessFinishSecond(String Output) {
Out_time.setText(Output);
}}
Do it like this
CallAPI asyncTask = new CallAPI(getContext());
CallAPI asyncTask2 = new CallAPI(getContext());
final chat text = this;
sendb.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
try {
String data = null;
//data to send
CallAPI asyncTask = new CallAPI(getContext());
asyncTask.delegate = text;
asyncTask.execute("", data, "sendMsg");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
sendb2.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
try {
String data = null;
//data to send
CallAPI asyncTask2 = new CallAPI(getContext());
asyncTask2.delegate = text;
asyncTask2.execute("", data, "sendMsg");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
});
#Override
public void onTaskCompleted(String output, String output2) {
}

Update ViewPager after Asynctask from the result

I had a problem here.
I have a login_activity that execute asynctask to get some result from a php file which it connects to mysql database.
public class login_main extends AppCompatActivity implements OnDataSendToActivity{
ViewPager viewPager;
CustomAdapter adapter;
ArrayList<String> image = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
//setSupportActionBar(toolbar);
String type = "getProfileImages";
RetrieveData retrieveData = new RetrieveData(this);
retrieveData.execute(type);
//After Asycntask, get the result and put back into image array
viewPager = (ViewPager) findViewById(R.id.view_pager);
adapter = new CustomAdapter(login_main.this,image);
viewPager.setAdapter(adapter);
}
public void sendData(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray result = jsonObject.getJSONArray("result");
for (int i = 0 ; i < result.length(); i++) {
JSONObject obj = result.getJSONObject(i);
String id = obj.getString("image"+i);
image.add("http://192.168.12.252/"+id+"/profile.png");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
When i get the result i try to process the result by using interface from the asynctask
protected void onPostExecute(String result) {
super.onPostExecute(result);
dataSendToActivity.sendData(result);
}
Everything is working fine except that the image array always empty when i pass it to the PageAdapter. How can i pass the data back to activity from asycntask and push into the array image, by using interface, it cant work.
Or anyway i can directly process it in Asyntask and update the ViewPager.
Here is my Asynctask
public class RetrieveData extends AsyncTask<String,Void,String>{
Context context;
RetrieveData(Context ctx) {
context = ctx;
}
private OnDataSendToActivity dataSendToActivity;
public RetrieveData(Activity activity){
dataSendToActivity = (OnDataSendToActivity)activity;
}
#Override
protected String doInBackground(String... params) {
String profile_url = "http://192.168.12.252/getprofile.php";
String image_url = "http://192.168.12.252/imagelist.php";
String type = params[0];
if(type.equals("getProfile")){
try {
String user_name = params[1];
URL url = new URL(profile_url);
HttpURLConnection httpURLConnection = null;
httpURLConnection = (HttpURLConnection)url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true);
httpURLConnection.setDoInput(true);
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");
bufferedWriter.write(post_data);
bufferedWriter.flush();
bufferedWriter.close();
outputStream.close();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream,"iso-8859-1"));
String result = null;
result = bufferedReader.readLine();
bufferedReader.close();
inputStream.close();
httpURLConnection.disconnect();
return result;
} catch (IOException e) {
e.printStackTrace();
}
}else if(type.equals("getProfileImages")){
try {
URL url = new URL(image_url);
HttpURLConnection httpURLConnection = null;
httpURLConnection = (HttpURLConnection)url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true);
httpURLConnection.setDoInput(true);
httpURLConnection.setDoOutput(true);
httpURLConnection.setDoInput(true);
OutputStream outputStream = httpURLConnection.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
String post_data = URLEncoder.encode("Image", "UTF-8")+"="+URLEncoder.encode("Image", "UTF-8");
bufferedWriter.write(post_data);
bufferedWriter.flush();
bufferedWriter.close();
outputStream.close();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream,"iso-8859-1"));
String result = null;
result = bufferedReader.readLine();
bufferedReader.close();
inputStream.close();
httpURLConnection.disconnect();
return result;
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
dataSendToActivity.sendData(result);
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
}
The execution sequence is all messed up. by the time ur adding data to ur image array the,the empty image array has already been passed to the view pager adapter,therfore ur image array is empty.
u continue to do the same thing but instead of setting view pager adapter in onCreate() set the adapter after u call the method sendData();
modify the sendData() method like this.
public void sendData(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray result = jsonObject.getJSONArray("result");
for (int i = 0 ; i < result.length(); i++) {
JSONObject obj = result.getJSONObject(i);
String id = obj.getString("image"+i);
image.add("http://192.168.12.252/"+id+"/profile.png");
}
} catch (JSONException e) {
e.printStackTrace();
}
adapter = new CustomAdapter(login_main.this,image);//set ur image array here
viewPager.setAdapter(adapter);
}

AsyncTask dont show me message from server (HttpUrlConnection)

So I'm trying to read a message from the server by HttpURLConnection in a AsyncTask class. The problem is, when i send the request to read the data from the server, it just keeps displaying the ProgresssDialog, like it doesn't read the data from the server:
public class MainActivity extends Activity{
EditText name, password;
Button login;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
name = (EditText) findViewById(R.id.name);
password = (EditText) findViewById(R.id.password);
login = (Button) findViewById(R.id.login);
login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String serverURL = "http://192.168.1.1/my/text.php";
LongOperation longOperation = new LongOperation();
longOperation.execute(serverURL);
}
});
}
private class LongOperation extends AsyncTask<String, Void, Void> {
private String content;
private String error = null;
private ProgressDialog dialog = new ProgressDialog(MainActivity.this);
TextView uiUpdate = (TextView) findViewById(R.id.output);
#Override
protected void onPreExecute() {
uiUpdate.setText("Output : ");
dialog.setMessage("Downloading source..");
dialog.show();
}
#Override
protected Void doInBackground(String... urls) {
try {
URL url = new URL(urls[0]);
HttpURLConnection client = (HttpURLConnection)url.openConnection();
client.connect();
InputStream inputStream = client.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
content = bufferedReader.readLine();
bufferedReader.close();
inputStream.close();
client.disconnect();
} catch (IOException e) {
error = e.getMessage();
}
return null;
}
#Override
protected void onPostExecute(Void unused) {
dialog.dismiss();
if (error != null) {
uiUpdate.setText("Output : "+error);
} else {
uiUpdate.setText("Output : "+content);
}
}
I already tryed before the connectivity to server via HttpClient, so thats not the problem.Thanks!
Try debugging it and see if OnPostExecute() method is getting called or not.!
This seems to get stuck in your stream reader code. Also, add a connection timeout of, say, 5-10 seconds for better user experience.!
Moreover, there seems to be an issue with your return type of doInBackground() method and input parameter type of OnPostExecute() method. As per your AsyncTask definition, they both should be string, isnt it?
See this
Try remove client.connect();
try {
URL url = new URL(urls[0]);
HttpURLConnection client = (HttpURLConnection)url.openConnection();
//remove client.connect();
int response = client.getResponse();
if(response == HttpURLConnection.HTTP_OK){
InputStream inputStream = client.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
content = bufferedReader.readLine();
bufferedReader.close();
inputStream.close();
}
finally{
client.disconnect();
}
} catch (IOException e) {
error = e.getMessage();
}
return null;
Make sure your server is running. Also set request time out.
You are not always required to explicitly call the connect method to initiate the connection. Operations that depend on being connected, like getInputStream, getOutputStream will implicitly perform the connection, when necessary.
This link
Try this:
private class LongOperation extends AsyncTask<String, Void, String>
{
private String content;
private String error = null;
private ProgressDialog dialog = new ProgressDialog(MainActivity.this);
TextView uiUpdate = (TextView) findViewById(R.id.output);
#Override
protected void onPreExecute() {
uiUpdate.setText("Output : ");
dialog.setMessage("Downloading source..");
dialog.show();
}
#Override
protected Strinh doInBackground(String... urls) {
try {
URL url = new URL(urls[0]);
HttpURLConnection client = (HttpURLConnection)url.openConnection(); client.connect();
InputStream inputStream = client.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
content = bufferedReader.readLine();
bufferedReader.close();
inputStream.close();
//client.discon dialog.dismiss();
}
catch (IOException e)
{
content = e.getMessage();
}
return content ;
}
#Override
protected void onPostExecute(String returnValue) {
if (return value != null) {
uiUpdate.setText("Output : "+error);
}
else {
uiUpdate.setText("Output No Value Returned");
}
dialog.dismiss();
}

Categories

Resources