Download Not Working [closed] - java

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
It Just Exits. What's the problem ?
I can't find anything wrong.
If there Is a better Way to download XML to inputstream please let me know.
Or a good way to read 3 or more XMLs simultaneously
package com.some.some;
import java.io.IOException;
import java.io.InputStream;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import android.os.Bundle;
import android.app.Activity;
import android.util.Base64;
import android.view.Menu;
import android.view.View;
public class Login extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
InputStream stream1 = downloadXmlFileStreamUsingUrl("URL IS CORRECT :|");
// Parse check is login or not ...
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.login, menu);
return true;
}
public InputStream downloadXmlFileStreamUsingUrl(final String url) {
final HttpGet getRequest = new HttpGet(url);
String encodedStr = Base64.encodeToString("user:pass".getBytes(), 0);
getRequest.setHeader("Authorization", "Basic " + encodedStr);
HttpClient client = null;
try {
client = new DefaultHttpClient();
client.getConnectionManager();
final HttpResponse getResponse = client.execute(getRequest);
final int statusCode = getResponse.getStatusLine().getStatusCode();
if (statusCode != HttpStatus.SC_OK) {
return null;
}
final HttpEntity getResponseEntity = getResponse.getEntity();
final InputStream content = getResponseEntity.getContent();
return content;
} catch (final IOException e) {
getRequest.abort();
}
finally {
client.getConnectionManager().shutdown();
}
return null;
}
}

First thing you have to understand is where we have to perform network operation.
On google developer docs they had explain step by step process here is the link and here is one more important link about network operation we perform.
Because the code you have posted I think your running network operation on main thread.

I assume you are getting a NetworkOnMainThreadException because are trying to access the network from UI.
Starting with Android 3.0 the network access should be done on a separate thread. With other words, downloadXmlFileStreamUsingUrl() should run in a separate thread.
You could use an AsyncTask for this purpose.

Related

Carrying and reusing information (json string) from an AsyncTask?

I have created a simple android app with 3 TextViews and then run an AsyncTask Task via a different class the next step would be to carry the information over and make the task reusable.
The Task will consume a String (URL) and the context of the MainActivity.
The Task will make a simple REST Request (GET) and retrieve a json string.
I have then created another class that which gets the json response and creates a .json file saves it to
..../0/Notes/launch.json
The folder "Notes is created by myself via file.mkdirs().
In the MainActivity I created an InputStream to read the .json file saved by the AsyncTask but once I try to open it, it gives me a FileNotFoundException.
Here's the code of my MainActivity.class
package com.example.root.example;
import android.Manifest;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.widget.ImageView;
import android.widget.TextView;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 200);
String url = "https://api.spacexdata.com/v3/launches/upcoming"; //Copy the url and open it in your browser to see the json.
AsyncCall asyncCall = new AsyncCall(getApplicationContext());
asyncCall.myAsyncTask(url);
try {
InputStream inputStream = this.getAssets().open("launch.json");
int size = inputStream.available();
byte[] buffer = new byte[size];
inputStream.read(buffer);
inputStream.close();
String jsonStringFromFile= new String(buffer,"UTF-8");
JSONObject launchObject = new JSONObject(jsonStringFromFile);
System.out.println(launchObject.get("flight_number"));
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
}
}
This is the AsyncCall.class (making and retrieving the json etc..)
package com.example.root.example;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Environment;
import java.io.IOException;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
public class AsyncCall {
FileCreator fileCreator = new FileCreator();
private final Context myContext;
public AsyncCall(final Context context) {
myContext = context;
}
public void myAsyncTask(final String url) {
AsyncTask asyncTask = new AsyncTask() {
#Override
protected Object doInBackground(Object[] objects) {
OkHttpClient okHttpClient = new OkHttpClient();
Request request = new Request.Builder()
.url(url)
.build();
Response response = null;
try {
response = okHttpClient.newCall(request).execute();
fileCreator.generateFile(myContext, myContext.getString(R.string.fileName), response.body().string());
} catch (IOException ioe) {
ioe.getMessage();
}
return null;
}
}.execute();
}
}
what am I trying to archive? I'm trying to save information (json here) and make it reusable just as the Falcon 9.
The issue lies in carrying information over to a different class.
If there's an alternative solution (other than saving a .json file) to fix this issue then please don't hesitate to post it.
This is just my first issue, the second issue appears once you open the api link and see that there are a few more than just one JSON String (0,1,2,3,4... upcoming missions).
I have no clue in any way to tacle the first let alone the second problem and have started over a few times, a while ago multiple times.
Within your Activity, you can get the JSON like so
OkHttpClient okHttpClient = new OkHttpClient();
Request request = new Request.Builder().url(url).build();
okHttpClient.newCall(request).enqueue(new Callback() {
#Override
public void onResponse(Call call, final Response response) throws IOException {
try {
final String responseData = response.body().string();
JSONObject json = new JSONObject(responseData);
String flightNumber = json.getString("flight_number");
// TODO: Load number into a TextView
} catch (JSONException e) {
e.printStackTrace();
}
}
});
Looking at your API response, though, you'll actually need new JSONArray(responseData), and you would have to loop over that to get each individual object's flight number

how do i send Json request to a server- java project (NetBeans) [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
i'm trying to send Json request to a server from my java project, the problem is, i found a class that someone wrote, in which he uses Apache, i tried to make path to the apache but it still doesnt import this stuff:
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
here's the class:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
public class JsonHTTPRequest {
private static String postToURL(String url, String message, DefaultHttpClient httpClient) throws IOException, IllegalStateException, UnsupportedEncodingException, RuntimeException {
HttpPost postRequest = new HttpPost(url);
StringEntity input = new StringEntity(message);
input.setContentType("application/json");
postRequest.setEntity(input);
HttpResponse response = httpClient.execute(postRequest);
if (response.getStatusLine().getStatusCode() != 200) {
throw new RuntimeException("Failed : HTTP error code : "
+ response.getStatusLine().getStatusCode());
}
BufferedReader br = new BufferedReader(
new InputStreamReader((response.getEntity().getContent())));
String output;
StringBuffer totalOutput = new StringBuffer();
System.out.println("Output from Server .... \n");
while ((output = br.readLine()) != null) {
System.out.println(output);
totalOutput.append(output);
}
return totalOutput.toString();
}
}
Apatche is third party so you have to include apatche lib take a look at this page

Android calling page that returns JSON error [duplicate]

This question already has answers here:
How can I fix 'android.os.NetworkOnMainThreadException'?
(66 answers)
Closed 9 years ago.
I have a aspx page that I am calling from my android app that is returning JSON text but the java code below breaks here BufferedReader reader = new BufferedReader(new InputStreamReader(jc.getInputStream()));
with this error.
error android.os.NetworkOnMainThreadException
ARe you able to help plesae? Thanks
default.aspx return json
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
Response.ContentType = "text/plain";
//Write the message
Response.Write("{'testvar':'testtext'}");
//End the response causing it to be sent
Response.End();
}
}
android java
public void connectWCF() {
try {
URL json = new URL("http://localhost:50851/Default.aspx");
URLConnection jc = json.openConnection();
BufferedReader reader = new BufferedReader(new InputStreamReader(jc.getInputStream()));
String line = reader.readLine();
reader.close();
} catch(Exception e){
}
links where I got the code ideas from
http://wyousuf.wordpress.com/2012/03/01/android-with-wcf-services/
http://matijabozicevic.com/blog/android-development/android-with-wcf-service
You are placing network communication on the main thread. You should use AsyncTask
http://developer.android.com/reference/android/os/AsyncTask.html
here's a nice video that explains JSON Parsing using AsyncTask.
http://www.youtube.com/watch?v=qcotbMLjlA4
For testing ONLY you can add the following in your Main Activity but it is consider bad practice.
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
Since android 3.0, you can't put any calls to webpages or similar external resources in the main thread (in other words, any part of the activity) unless you do it with an AsyncTask, in order to avoid apps to look "locked" and unresponsive when waiting for a response from an external datasource. Therefore, you'll need to implement the webservice call with and AsyncTask.
Example class for AsyncTask:
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONObject;
import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;
public class cargaDatosRest extends AsyncTask<Context, Void, Void> {
private Context c;
private boolean resul = false;
private String control = "";
private String respStrS = "";
public cargaDatosRest(Context C)
{
c = C;
}
public String getStr()
{
return respStrS;
}
public String getControl()
{
return control;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
//mProgressDialog.show();
}
#Override
protected Void doInBackground(Context... params) {
HttpClient httpClient = new DefaultHttpClient();
HttpGet get = new HttpGet("url");
HttpResponse resp;
get.setHeader("content-type", "application/json");
try
{
/*resp contains the response from the webService. respStr and respJSON allows to read that resp in JSON format. Just delete them if you don't need them. You can asign the values returned by the webservice to local variables in the AsyncTask class and then read them with public methods, like the resul variable.*/
resp = httpClient.execute(getUsuarios);
String respStr = EntityUtils.toString(resp.getEntity());
JSONArray respJSON = new JSONArray(respStr);
this.resul = true;
}
catch(Exception ex)
{
Log.e("ServicioRest","Error!", ex);
this.resul = false;
}
}
public boolean getResul()
{
return this.resul;
}
protected void onProgressUpdate(String... progress) {
Log.d("ANDRO_ASYNC",progress[0]);
//mProgressDialog.setProgress(Integer.parseInt(progress[0]));
}
#Override
protected void onPostExecute(Void unused) {
//mProgressDialog.dismiss();
}
}
//calling the AsyncTask from the activity:
CargaDatosRest CallRest = new CargaDatosRest(this.getApplicationContext());
CallRest.execute();
Log.v("WebService", "Just trying "+arest.getResul());

Is possible to call servlet from applet

I am not familiar with java and applets, so any one please let me know the possibilities for the following my questing.
I would like to call the Servlet from applet.. is this possible?
If the 1st one is possible can we store the Servlet output like XML data or string in the applet variable?
If the 2nd one is possible, then can get that that variable value using JavaScript or J Query?
If possible please give me the simple example.
Thanks in advance.
Yes you can. The servlet exposes a URL, which you can get with the help of the URLConnection class.
Again you can do this, see here on how you can use the URL connection.
You can do that too, create an applet to get the applet field, and look here on how you can invoke the method.
But all these sound awfully complicated. Why don't you tell us what you are trying to achieve, maybe there is a simpler way to do things.
One : yes you can call the servlet from applet making http calls
step 1 : make a http call to your servlet
step 2 : make your servlet return XML response
step 3 : parse xml response
using this program you can make a call to your servlet
package com.hussain;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URI;
import java.util.ArrayList;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class callServlet {
public static void main(String[] args)
{
String servletResponse = callServlet.sendRequest("http://gdata.youtube.com/feeds/base/videos?max-results=10&start-//index=1&alt=json&orderby=published&author=astrobixweb");
callServlet.parseFromXMLResponse(servletResponse);
}
public static String sendRequest(String url) {
String result = "";
try {
HttpClient client = new DefaultHttpClient();
HttpParams httpParameters = client.getParams();
HttpConnectionParams.setConnectionTimeout(httpParameters, 5000);
HttpConnectionParams.setSoTimeout(httpParameters, 5000);
HttpConnectionParams.setTcpNoDelay(httpParameters, true);
HttpGet request = new HttpGet();
request.setURI(new URI(url));
HttpResponse response = client.execute(request);
InputStream ips = response.getEntity().getContent();
BufferedReader buf = new BufferedReader(new InputStreamReader(ips,"UTF-8"));
StringBuilder sb = new StringBuilder();
String s;
while (true) {
s = buf.readLine();
if (s == null || s.length() == 0)
break;
sb.append(s);
}
buf.close();
ips.close();
result = sb.toString();
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
public static void parseFromXMLResponse(String respo)
{
// parse your XML response here
}
}
Moving in the flow of your question,
You may call the servlet from your applet:
Construct the url that will hit your servlet.
Use java.net.URLConnection object to hold the connection from your appletURLConnection con = urlToServlet.openConnection()
'con.setDoOutput(true)' => Application intends to write data to the URL connection.
Use the input and output streams to communicate with the Servlet.
con.getInputStream() and con.getOutputStream()
[Note: Don't forget to close all the connections and streams]
Now, use the data you obtained from the InputStream, in what so ever form you want.
Its extreamly simple, use this code:
In Applet:
public String getYourString(){ return responseFromServlet;}
In Javascript:
var jsResp = document.name_of_your_applet.getYourString();
Hope, you've got your answers!

Android Simple HTTP Request?

I have this code for an Android application I'm trying to create into interact with my PHP website. I have the android.permission.INTERNET permission activated and it keeps creating a toast that says "ERROR." instead of the contents of the website. Here is my only java file:
package com.http.request;
import java.io.IOException;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import android.app.Activity;
import android.os.Bundle;
import android.widget.Toast;
public class HttprequestActivity extends Activity {
/** Called when the activity is first created. */
private String doHTTPRequest(String url){
String results = "ERROR";
try
{
HttpClient hc = new DefaultHttpClient();
HttpPost post = new HttpPost(url);
HttpResponse rp = hc.execute(post);
if(rp.getStatusLine().getStatusCode() == HttpStatus.SC_OK)
{
results = EntityUtils.toString(rp.getEntity());
}
}catch(IOException e){
e.printStackTrace();
}
return results;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
String results = doHTTPRequest("http://www.yahoo.com");
Toast.makeText(getApplicationContext(), results, Toast.LENGTH_LONG).show();
}
}
I would check to make sure that,
If there is an exception being thrown, investigate what is causing the IOException
Your server could potentially be returning a non-200 response code.
Put in some breakpoints and see whats happening there. My bet is on the response code.
That is your own "ERROR" string which the Toast() displays. Better change
catch(IOException e){
e.printStackTrace();
}
to
catch(IOException e){
result = "ERROR IOException";
e.printStackTrace();
}
The exception is thrown as you try to connect in the main thread which is not permitted. Put doHTTPRequest() in a thread or AsyncTask.
What is your stacktrace says, LogCat? What is the error? Add more info, make it more clear to understand than "guessing of coffee beans"
My guess is: this happens because you are trying to do network operation in UI thread which is not allowed in 3.0+ versions.
http://developer.android.com/reference/android/os/NetworkOnMainThreadException.html

Categories