Android HttpURLConnection Error - java

I have an issue on my Android Project,
I want to call php page with get method and I use HttpURLConnection,
when I run this application give an error "app has stopped"
This is my code
public void someFunction() throws IOException {
String inputLine = "";
URL url = new URL("http://www.domain.com/demo.php?test=abc");
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
StringBuilder result = new StringBuilder();
String line;
while((line = reader.readLine()) != null) {
result.append(line);
}
} finally{
in.close();
}
}
What should I do?
Thanks.

I have solved this issue with following code,
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);

Android is build to resist the developers to make network requests in the main (UI) thread. Changing Thread policy is not the solution. You should use AsyncTask to make all network requests.
public void someFunction() throws IOException {
AsyncTask task = new AsyncTask<Void,StringBuilder,StringBuilder>() {
#Override
protected StringBuilder doInBackground(Void... params) {
String inputLine = "";
URL url = new URL("http://www.domain.com/demo.php?test=abc");
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
StringBuilder result = new StringBuilder();
String line;
while((line = reader.readLine()) != null) {
result.append(line);
}
} finally{
in.close();
}
return result;
}
#Override
protected void onPostExecute(StringBuilder result) {
super.onPostExecute(o);
}
};
task.execute();
}
See the android documentation: http://developer.android.com/reference/android/os/AsyncTask.html

Related

Json Result from News API is null

#Override
protected String doInBackground(String... strings) {
String result = HttpRequest.getExecute("http://newsapi.org/v2/everything?q=bitcoin&from=2020-05-30&sortBy=publishedAt&apiKey=myAPIkey");
return result;
}
I am getting a null response on passing this URL even though the same URL when opened on the browser shows a lot of stuff. I am getting a Null Pointer Exception. Please help. Below is my HttpRequest class.
HTTPRequest Class:
public class HttpRequest {
public static String getExecute(String targetUrl)
{
URL url;
HttpURLConnection httpURLConnection = null;
try
{
url = new URL(targetUrl);
httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("GET");
InputStream inputStream;
if (httpURLConnection.getResponseCode() != HttpURLConnection.HTTP_OK)
inputStream = httpURLConnection.getErrorStream();
else
inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
String line;
StringBuffer response = new StringBuffer();
while ( (line = bufferedReader.readLine()) != null)
{
response.append(line);
response.append('\r');
}
bufferedReader.close();
return response.toString();
}
catch (Exception e)
{
e.printStackTrace();
return null;
}
finally {
if(httpURLConnection != null)
{
httpURLConnection = null;
}
}
}
}
You have to call connect method before reading the result or response code. Add the below line after setting up the request method
httpURLConnection.connect()

Android app, HttpURLConnection GET method, AsyncTask getting tag instead of result

It is simple app that needs to send two numbers using GET and reads back.
Button btnSaberi;
EditText txtAunos, txtBunos;
TextView txtIspis;
String sturl = "http://xxx.xxx.xx.x/PhpProject1/index.php";
Integer a, b;
HttpURLConnection httpURLConnection;
URL url;
public void posalji(View view){
a = Integer.parseInt(txtAunos.getText().toString());
b = Integer.parseInt(txtBunos.getText().toString());
sturl = sturl+"?a=" + a + "&b=" + b;
new Posalji().execute(sturl);
}
class Posalji extends AsyncTask<String, String, String> {
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
txtIspis.setText("Rezultat je : " + s);
}
#Override
protected String doInBackground(String... strings) {
try {
url = new URL(strings[0]);
httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("GET");
httpURLConnection.connect();
BufferedReader br = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream()));
rez = br.readLine();
}
return rez;
}
}
}
Using Emulator.
I have changed and now instead of showing me php output it shows me html tag.
"<!DOCTYPE html>"
Please remove txtIspis.setText("Rezultat je : " + br.readLine()); line from AsyncTask doInBackground. In doInBackground we never update UI like this. you can use onPostExecute for update your textbox values.
Please read this doc https://developer.android.com/reference/android/os/AsyncTask
As you are calling br.readLine(); just once, it is reading only the first line of data from the BufferedReader.
To read all the lines of data from BufferedReader you need to use a loop.
Update your doInBackground method
#Override
protected String doInBackground(String... params){
String url = params[0];
String result;
try {
URL myUrl = new URL(url);
HttpURLConnection connection =(HttpURLConnection) myUrl.openConnection();
connection.setRequestMethod("GET");
connection.connect()
InputStreamReader streamReader = new InputStreamReader(connection.getInputStream());
BufferedReader reader = new BufferedReader(streamReader);
StringBuilder stringBuilder = new StringBuilder();
String inputLine;
while((inputLine = reader.readLine()) != null){
stringBuilder.append(inputLine);
}
reader.close();
streamReader.close();
result = stringBuilder.toString();
}
return result;
}

Catch errors of HttpUrlConnection in AsyncTask

I'm searching for a best practice to handle errors in an HttpURLConnection especially if the host is not available. How did I have to change my source?:
protected String doInBackground(String... strings) {
URL aURL;
String line;
HttpURLConnection connection;
BufferedReader reader;
StringBuilder stringBuilder = null;
try {
aURL = new URL(strings[0]);
connection = (HttpURLConnection) aURL.openConnection();
InputStream aInputStream = connection.getInputStream();
BufferedInputStream aBufferedInputStream = new BufferedInputStream(aInputStream);
reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
stringBuilder = new StringBuilder();
while ((line = reader.readLine()) != null)
{
stringBuilder.append(line);
}
} catch (IOException e) {
Log.d("svc", e.toString());
}
return stringBuilder.toString();
}
you will get different responsecode using connection.getResponseCode()
Check for the response codes for host not available and you will be set.

How to parse a txt web service

I'm trying to obtain a result from a web service in a java program. I've done xml services before but this one is text based and i can't figure out how to record the response.
Here is the webService: http://ws.geonames.org/countryCode?lat=47.03&lng=10.2
Thanks!
If it's only text, and you doesn't use any standard format (like SOAP), you need to use Sockets:
URL myURL = new URL("http://ws.geonames.org/countryCode?lat=47.03&lng=10.2");
URLConnection serviceConnection = myURL.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(
serviceConnection.getInputStream()));
List<String> response =new ArrayList<String>();
Use this if you had many lines:
while ((inputLine = in.readLine()) != null)
response.add(inputLine);
Or use this if you had ONLY ONE line (like the Web Service in your question):
String countryCode = in.readLine();
And finish with:
serviceConnection.close();
In my case, countryCode it was "AT"
An alternative implementation in addition to URL is to use a HttpClient.
public class CountryCodeReader {
private String readAll(Reader rd) throws IOException {
StringBuilder sb = new StringBuilder();
int cp;
while ((cp = rd.read()) != -1) {
sb.append((char) cp);
}
return sb.toString();
}
public String readFromUrl(String url) throws IOException, JSONException {
InputStream is = new URL(url).openStream();
try {
InputStreamReader is = new InputStreamReader(is, Charset.forName("UTF-8"))
BufferedReader rd = new BufferedReader(is);
return readAll(rd);
} finally {
is.close();
}
return null;
}
public static void main(String[] argv) {
CountryCodeReader ccr = new CountryCodeReader();
String cc = ccr.readFromUrl("http://ws.geonames.org/countryCode?lat=47.03&lng=10.2");
}
}

How to read an HTTP input stream?

The code pasted below was taken from Javadocs on HttpURLConnection.
I get the following error:
readStream(in)
...as there is no such method.
I see this same thing in the Class Overview for URLConnection at
URLConnection.getInputStream
Where is readStream? The code snippet is provided below:
URL url = new URL("http://www.android.com/");
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
try
{
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
readStream(in); <-----NO SUCH METHOD
}
finally
{
urlConnection.disconnect();
}
Try with this code:
InputStream in = address.openStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
StringBuilder result = new StringBuilder();
String line;
while((line = reader.readLine()) != null) {
result.append(line);
}
System.out.println(result.toString());
It looks like the documentation is just using readStream() to mean:
Ok, we've shown you how to get the InputStream, now your code goes in readStream()
So you should either write your own readStream() method which does whatever you wanted to do with the data in the first place.
Spring has an util class for that:
import org.springframework.util.FileCopyUtils;
InputStream is = connection.getInputStream();
ByteArrayOutputStream bos = new ByteArrayOutputStream();
FileCopyUtils.copy(is, bos);
String data = new String(bos.toByteArray());
try this code
String data = "";
InputStream iStream = httpEntity.getContent();
BufferedReader br = new BufferedReader(new InputStreamReader(iStream, "utf8"));
StringBuffer sb = new StringBuffer();
String line = "";
while ((line = br.readLine()) != null) {
sb.append(line);
}
data = sb.toString();
System.out.println(data);
a complete code for reading from a webservice in two ways
public void buttonclick(View view) {
// the name of your webservice where reactance is your method
new GetMethodDemo().execute("http://wervicename.nl/service.asmx/reactance");
}
public class GetMethodDemo extends AsyncTask<String, Void, String> {
//see also:
// https://developer.android.com/reference/java/net/HttpURLConnection.html
//writing to see: https://docs.oracle.com/javase/tutorial/networking/urls/readingWriting.html
String server_response;
#Override
protected String doInBackground(String... strings) {
URL url;
HttpURLConnection urlConnection = null;
try {
url = new URL(strings[0]);
urlConnection = (HttpURLConnection) url.openConnection();
int responseCode = urlConnection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
server_response = readStream(urlConnection.getInputStream());
Log.v("CatalogClient", server_response);
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
url = new URL(strings[0]);
urlConnection = (HttpURLConnection) url.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(
urlConnection.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null)
System.out.println(inputLine);
in.close();
Log.v("bufferv ", server_response);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
Log.e("Response", "" + server_response);
//assume there is a field with id editText
EditText editText = (EditText) findViewById(R.id.editText);
editText.setText(server_response);
}
}

Categories