Http Get using Android HttpURLConnection
Try getting the input stream from this you can then get the text data as so:-
URL url;
HttpURLConnection urlConnection = null;
try {
url = new URL("http://www.mysite.se/index.asp?data=99");
urlConnection = (HttpURLConnection) url
.openConnection();
InputStream in = urlConnection.getInputStream();
InputStreamReader isw = new InputStreamReader(in);
int data = isw.read();
while (data != -1) {
char current = (char) data;
data = isw.read();
System.out.print(current);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
}
You can probably use other inputstream readers such as buffered reader also.
The problem is that when you open the connection - it does not 'pull' any data.
Get text from a URL using Android HttpURLConnection
class GetData extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... params) {
HttpURLConnection urlConnection = null;
String result = "";
try {
URL url = new URL("http://ephemeraltech.com/demo/android_tutorial20.php");
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) {
yourTextView.setText(result);
super.onPostExecute(s);
}
}
and call this class by using
new GetData().execute();
How to use HttpURLConnection in an Android app?
Yes it work !!
I did what @code-demon told me to do :
Add at the Manifest
android:usesCleartextTraffic="true"
And use thred but I couldn't get any value back from API response, so I did research and came across it: stackoverflow post.
Finally I developed that :
ExecutorService executor = Executors.newSingleThreadExecutor();
Callable<String> callable = new Callable<String>() {
@Override
public String call() throws IOException {
// Call my API get function
return verifyLoginAndGetData(username, password);
}
};
Future<String> future = executor.submit(callable);
executor.shutdown();
// Get in String, the API response
String resultAPI = future.get();
Android HttpURLConnection: HTTP response always 403
I tried fetching it with curl. Your URL uses http
instead of https://...
, change it to https://www.youtube.com/oembed?url=
.
Trying to fetch the URL when it starts with just http
resulted in a 403 status for me. But https
was successful.
URL url = new URL("http://www.youtube.com/oembed?url=" + youtubeUrl + "&format=json");
Should be changed to:
URL url = new URL("https://www.youtube.com/oembed?url=" + youtubeUrl + "&format=json");
Android HttpURLConnection set GET Request method
the problem is
conn.setDoOutput(true);
when set to true the request method is changed to POST
, since GET or DELETE can't have a request body
Send request body with GET request using HttpURLConnection in java
use this code you will need to do a little modification but it will get the job done.
package com.kundan.test;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.Socket;
public class GetWithBody {
public static final String TYPE = "GET ";
public static final String HTTP_VERSION = " HTTP/1.1";
public static final String LINE_END = "\r\n";
public static void main(String[] args) throws Exception {
Socket socket = new Socket("localhost", 8080); // hostname and port default is 80
OutputStream outputStream = socket.getOutputStream();
outputStream.write((TYPE + "<Resource Address>" + HTTP_VERSION + LINE_END).getBytes());//
outputStream.write(("User-Agent: Java Socket" + LINE_END).getBytes());
outputStream.write(("Content-Type: application/x-www-form-urlencoded" + LINE_END).getBytes());
outputStream.write(LINE_END.getBytes()); //end of headers
outputStream.write(("parameter1=value¶meter2=value2" + LINE_END).getBytes()); //body
outputStream.flush();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
StringBuilder builder = new StringBuilder();
String read = null;
while ((read = bufferedReader.readLine()) != null) {
builder.append(read);
}
String result = builder.toString();
System.out.println(result);
}
}
this the Raw HTTP Request Dump
GET <Resource Address> HTTP/1.1
User-Agent: Java Socket
Content-Type: application/x-www-form-urlencoded
parameter1=value¶meter2=value2
Note : This is for http request if you want https Connection Please refer to the link SSLSocketClient
How to add parameters to HttpURLConnection using POST using NameValuePair
You can get output stream for the connection and write the parameter query string to it.
URL url = new URL("http://yoururl.com");
HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
conn.setReadTimeout(10000);
conn.setConnectTimeout(15000);
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("firstParam", paramValue1));
params.add(new BasicNameValuePair("secondParam", paramValue2));
params.add(new BasicNameValuePair("thirdParam", paramValue3));
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os, "UTF-8"));
writer.write(getQuery(params));
writer.flush();
writer.close();
os.close();
conn.connect();
...
private String getQuery(List<NameValuePair> params) throws UnsupportedEncodingException
{
StringBuilder result = new StringBuilder();
boolean first = true;
for (NameValuePair pair : params)
{
if (first)
first = false;
else
result.append("&");
result.append(URLEncoder.encode(pair.getName(), "UTF-8"));
result.append("=");
result.append(URLEncoder.encode(pair.getValue(), "UTF-8"));
}
return result.toString();
}
HttpURLConnection with JSON on Android 9, API 28
Try this add Manifest.xml
cleartextTrafficPermitted="true"
it look like this
How to allow all Network connection types HTTP and HTTPS in Android (9) Pie?
HttpUrlConnection method is always GET on android
404 is not an exception. It is a HTTP status code returned by the server you make the request to and it means that the url you make the request to is not found. That has nothing to do with POST being set or not.
Things to check:
- If the url you are making a request to is right.
- If the server has a POST controller/handler mapped to the url you are making the request to.
- Ask the guy who develops the server if he is handling the cases right ans if he's sending the correct response codes for the relevant scenarios.
Extra info: if the url is registered on the service but a POST request is not allowed you would get a 415 response code.
Related Topics
Android: Switch Camera When Button Clicked
Android Timer Updating a Textview (Ui)
Get Filepath and Filename of Selected Gallery Image in Android
How to Change a Bitmap's Opacity
Best Way to Implement View.Onclicklistener in Android
Google Firebase Check If Child Exists
What Is Difference Between @+Id/Android:List and @+Id/List
How to Save Bitmap to Android Gallery
How to Parse Date from Gmt Timezone to Ist Timezone and Vice Versa in Android
Send Sms Until It Is Successful
Java Doesn't Work with Regex \S, Says: Invalid Escape Sequence
Error Launching Android Studio: Failed to Create Jvm: Error Code-6
Change Listview Background - Strange Behaviour
Android: Email Client Receiver Email Id Empty in Android-Parse
Android Firestore Convert Array of Document References to List<Pojo>
Code Will Only Return 0.0, 0.0 Gps Coordinate While Throwing Nullpointerexception
Sort Data to Recyclerview Based on Latest Date from Firebase