Make simply HTTP request and receive the content - java

I have found a working code for makeing simply HTTP requests here, from How can I make a simple HTTP request in MainActivity.java? (Android Studio) and I am going to post it below (with some changes, if I am not wrong it is now necessery to use try{} catch{}). But I would like to ask how I can receive the content? I work with the code in the following way:
GetUrlContentTask req = new GetUrlContentTask();
req.execute("http://192.168.1.10/?pin=OFF1");
textView3.setText(req.doInBackground("http://192.168.1.10/?pin=OFF1"));
GetUrlContentTask
private class GetUrlContentTask extends AsyncTask<String, Integer, String> {
protected String doInBackground(String... urls) {
// String content1 = "";
try {
URL url = new URL(urls[0]);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setDoOutput(true);
connection.connect();
BufferedReader rd = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String content = "", line;
while ((line = rd.readLine()) != null) {
content += line + "\n";
}
// content1 = content;
}
catch (Exception e) {
e.printStackTrace();
}
// return content1; - returns "", wrong
return "aaa";
//does not work return content;
}
protected void onProgressUpdate(Integer... progress) {
}
protected void onPostExecute(String result) {
// this is executed on the main thread after the process is over
// update your UI here
}
}

Add this to your onPostExecute(String result) call
protected void onPostExecute(String result) {
// this is executed on the main thread after the process is over
// update your UI here
setMyData(result);
}
And then fill your textfield or whatever other data you need to update.
private void setMyData(String result){
textView3.setText(result);
}

Where exactly are you stuck? Your code mostly correct although you may need to rearrange it slightly. Your scope is a bit off and your commented code almost gets there. See below
protected String doInBackground(String... urls) {
String content = "", line = "";
HttpURLConnection httpURLConnection;
BufferedReader bufferedReader;
URL url;
try {
for(String uri : urls) {
url = new URL(uri);
url = new URI(url.toURI().getScheme(), url.getAuthority(), url.getPath(), "pin=" + URLEncoder.encode("&OFF1", "UTF-8"), null).toURL();
httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("GET");
httpURLConnection.setDoOutput(true);
httpURLConnection.connect();
bufferedReader = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream()));
while ((line = bufferedReader.readLine()) != null) {
content += line + System.lineSeparator();
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
bufferedReader.close();
} catch(Exception e) {
e.printStackTrace();
}
}
return content;
}
That will return a String representation of your page. If the page contains HTML it will return text/html, if it contains text it will return just text.
Then as a previous user stated you can set the response on your GUI
protected void onPostExecute(String result) {
textView3.setText(result);
}
The above example will technically work. However, I would highly recommend using http://loopj.com/android-async-http/ over HttpURLConnection. Your code will be much nicer which will matter down the line.
The code I sent you assumes that the parameter is always pin=OFF1 because it's more a proof of concept

Related

Why my android program works fine on 4.4.3 version but doesnt work on 10.0

On the phone string is empty, why thats happend?
Phone is android version 10, nox is 4.4.3 if thats matters?
I try more codes for read web page but result is same, i dont know why its happend?
class GetData extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
HttpURLConnection urlConnection = null;
String result = "";
try {
URL url = new URL("http://www.b92.net/info/rss/sport.xml");
urlConnection = (HttpURLConnection) url.openConnection();
int code = urlConnection.getResponseCode();
if(code==200){
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
if (in != null) {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(in));
String line = "";
while ((line = bufferedReader.readLine()) != null)
result += line;
}
in.close();
}
return result;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
finally {
urlConnection.disconnect();
}
return result;
}
#Override
protected void onPostExecute(String result) {
tv.setText(result);
}
}
}
To turn #intellij-amiya s comment into an answer:
Use https instead of http: https://www.b92.net/info/rss/sport.xml
this blog post tells us that clear-traffic is (basically) forbidden now (as #morrison-chang pointed out)
You need to add Internet Permission in Manifest.

PHP is not receieving data from a POST request with AsyncTask

I am trying to receieve a simple string from my PHP script by using a POST request in Android Studio.
If I write for example echo "Hello"; I can receive this message in my app, but it seems like as soon as I send a POST request my webserver doesen't really get the message.
Here is how I do the POST request in my AsyncTask:
class HTTPReqTask extends AsyncTask<String, Void, String>
{
Activity activity;
OnDataSendToActivity dataSendToActivity;
Context context;
public HTTPReqTask(Context context)
{
this.context = context;
dataSendToActivity = (OnDataSendToActivity) ((Activity) context);
}
#Override
public String doInBackground(String... params)
{
HttpURLConnection urlConnection = null;
String param1 = params[0];
String line = "";
String result = "";
try
{
JsonObject postData = new JsonObject();
postData.addProperty("a", "1");
URL url = new URL(param1);
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestProperty("Content-Type", "application/json");
urlConnection.setRequestMethod("POST");
urlConnection.setDoOutput(true);
urlConnection.setDoInput(true);
urlConnection.setChunkedStreamingMode(0);
OutputStream out = new BufferedOutputStream(urlConnection.getOutputStream());
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(out,"UTF-8"));
writer.write(postData.toString());
int code = urlConnection.getResponseCode();
if (code != HttpURLConnection.HTTP_OK) {
throw new IOException("Invalid response from server: " + code);
}
BufferedReader rd = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
while ((line = rd.readLine()) != null)
{
result += line;
}
}
catch (Exception e)
{
e.printStackTrace();
}
finally
{
if (urlConnection != null)
{
urlConnection.disconnect();
}
}
return result;
}
#Override
protected void onPostExecute(String s)
{
try
{
if(dataSendToActivity != null)
{
Log.i("Data", s);
dataSendToActivity.sendData(s);
}
}
catch(Exception e)
{
// Nichts
}
}
}
As you can see I am using this:
JsonObject postData = new JsonObject();
postData.addProperty("a", "1");
to generate my POST request.
The postData string is: {"a":"1"}
This is my PHP script:
$post = file_get_contents("php://input");
$data = json_decode($post, true);
print_r($data);
UPDATE 1
I added now writer.flush(); (Thanks to Andy)
Now I'm getting this exception after sendung the request:
java.io.IOException: Invalid response from server: 500
So something with my PHP script is wrong.
Any suggestions?
I found now the problem.
The problem was not serversided as I expected it.
I was logging in my code some informations for the POST request and there I found this:
Log.i("LOG", urlConnection.getOutputStream().toString());
gave me this:
buffer(com.android.okhttp.internal.http.HttpConnection$ChunkedSink#843d1c8).outputStream()
So I commented this line out:
urlConnection.setChunkedStreamingMode(0);
and it works fine. I get all my data I need.
I also updated my PHP script to this:
$post = file_get_contents("php://input");
if (!empty($post))
{
$data = json_decode($post, true);
$a = $data['a'];
}
Thanks for all the help!

HTTP Post Request over a Login Application

I am not able to send HTTP Post request. I am developing a login application where it should login from a post method API link using appropriate credentials. Once it logins, next activity should show other information present in the API(JSON).
Can anyone please guide me to do this by sending any references or explain with a sample code.
You can login using following code. This uses AsyncTask since android won't allow you to use Main Thread for networking stuff. However be cautious using Async Task . These are a good way to leak memory.
Also you can always use Firebase Auth API to facilitate login, which are more secure, more easy, don't have to worry about server side programming and require very less code on your side.
public class RegistryHelper extends AsyncTask<String, Void, String> {
public static final String link = "http://www.yourlink.com/login.php";
public String data = null;
public RegistryHelper() {
}
#Override
protected void onPreExecute() {
}
#Override
protected String doInBackground(String... params) {
try {
URL url = new URL(link);
data = URLEncoder.encode("username", "UTF-8") + "=" + URLEncoder.encode(params[0], "UTF-8") + "&"
+ URLEncoder.encode("password", "UTF-8") + "=" + URLEncoder.encode(params[1], "UTF-8");
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
conn.setConnectTimeout(20000);
OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());
writer.write(data);
writer.flush();
BufferedReader read = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line = null;
StringBuffer sb = new StringBuffer();
while ((line = read.readLine()) != null) {
sb.append(line);
}
return sb.toString();
} catch (Exception e) {
e.printStackTrace();
return e.toString();
}
}
#Override
protected void onPostExecute(String result) {
if (result.equals("LOGIN_SUCCESS")) {
//Your action
} else {
//Your else action
}
}
}

Trouble with "inputstream" when creating mobile app that downloads weather information (with AsyncTask)

I'm trying to make a mobile app that downloads info from the openweathermap.org apis. For example, if you feed that app this link: http://api.openweathermap.org/data/2.5/weather?q=Boston,us&appid=fed33a8f8fd54814d7cbe8515a5c25d7 you will get the information about the weather in Boston, MA. My code seems to work up to the point where I have to convert the input stream to a string variable. When I do that, I get garbage. Is there a particular way to do this seemingly simple task in a proper way? Here is my code so far...
private class DownloadWebpageTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
// params comes from the execute() call: params[0] is the url.
try {
return downloadUrl(urls[0]);
} catch (IOException e) {
return null;
}
}
// onPostExecute displays the results of the AsyncTask.
#Override
protected void onPostExecute(String result) {
TextView test = (TextView) findViewById(R.id.test);
if(result!=null) test.setText(result);
else{
Log.i(DEBUG_TAG, "returned result is null");}
}
}
private String downloadUrl(String myurl) throws IOException {
InputStream is = null;
try {
URL url = new URL(myurl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(10000 /* milliseconds */);
conn.setConnectTimeout(15000 /* milliseconds */);
conn.setRequestMethod("GET");
conn.setDoInput(true);
// Starts the query
conn.connect();
int response = conn.getResponseCode();
Log.i(DEBUG_TAG, "The response is: " + response);
is = conn.getInputStream();
String text = getStringFromInputStream(is);
//JSONObject json = new JSONObject(text);
//try (Scanner scanner = new Scanner(is, StandardCharsets.UTF_8.name())) {
//text = scanner.useDelimiter("\\A").next();
//}
//Bitmap bitmap = BitmapFactory.decodeStream(is);
return text;
}catch(Exception e) {
Log.i(DEBUG_TAG, e.toString());
}finally {
if (is != null) {
is.close();
}
}
return null;
}
private static String getStringFromInputStream(InputStream is) {
BufferedReader br = null;
StringBuilder sb = new StringBuilder();
String line;
try {
br = new BufferedReader(new InputStreamReader(is));
while ((line = br.readLine()) != null) {
sb.append(line);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return sb.toString();
}
Check this library . Is An asynchronous callback-based Http client for Android built on top of Apache’s HttpClient libraries.

AsyncTask LIFX Bulb response

I have got problem with read output form request.
public JSONArray listLights()
{
try
{
URL adres = new URL("https://api.lifx.com/v1/lights/all");
HttpURLConnection polaczenie = (HttpURLConnection) adres.openConnection();
polaczenie.setRequestProperty("Authorization", "Bearer " + apiKey);
polaczenie.setRequestMethod("GET");
BufferedReader wejscie = new BufferedReader(new InputStreamReader((polaczenie.getInputStream())));
StringBuilder odpowiedz = new StringBuilder();
String json;
while ((json = wejscie.readLine()) != null)
odpowiedz.append(json);
wejscie.close();
return new JSONArray(odpowiedz.toString());
}
catch (Exception wyjatek)
{
wyjatek.printStackTrace();
}
return new JSONArray();
}
StackTrace
I added to AndroidManifest Internet access too.
Welcome to leave any comments. :P
EDIT:
I google internet and found partial solution. Added AsyncTask, but now I'm receiving '429' response code.
public class JSONTask extends AsyncTask<String, String, String>
{
String apiKey = "blah_blah_blah";
String txtresult;
#Override
protected String doInBackground(String... params) {
HttpsURLConnection connection = null;
BufferedReader reader = null;
try
{
URL adres = new URL(params[0]);
HttpsURLConnection polaczenie = (HttpsURLConnection) adres.openConnection();
polaczenie.setRequestProperty("Authorization", "Bearer " + apiKey);
polaczenie.setRequestMethod("GET");
System.out.println(polaczenie.getResponseCode());
InputStream stream = polaczenie.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null)
{
buffer.append(line);
}
return buffer.toString();
}
catch (MalformedURLException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
finally {
if (connection != null)
connection.disconnect();
try
{
if (reader != null)
reader.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(String s)
{
super.onPostExecute(s);
widok.setText(s);
}
}
My current StackTrace
EDIT2:
New day, new surprise. I figure out that I'm making connection with Bulb once/twice on every 10 attempts. Any ideas?
HTTP Status code 429 means too many requests in a given an amount of time. So how many requests exactly are you doing?
android.os.NetworkOnMainThreadException it means, that You have to make a htttp request from another threat than UIthread. Why are you using async task ?
Edit: You can also try make a call from postman and maybe You will see the problem.
In the end, everything is working. Problem was on the side of bulb or Lifx Cloud.

Categories