Updated 26 October 2021
In this blog, we will learn how to create a HTTP Request without using any library.
In Mobile App Development , we usually depend on a server and to make a connection with the server, we need to create http calls.
For this purpose we use networking libraries in our project so that we can easily create the http request for our use.
Some of the popular libraries are Volley, Retrofit etc.
Of course, these libraries help us a lot and make our work easy and our calls faster.
But what if we don’t wan to use any of these libraries.
Let us see how to do this :
AsyncTask for the request :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 |
private class MyHttpRequestTask extends AsyncTask<String,Integer,String>{ @Override protected String doInBackground(String... params) { String my_url = params[0]; String my_data = params[1]; try { URL url = new URL(my_url); HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection(); // setting the Request Method Type httpURLConnection.setRequestMethod("POST"); // adding the headers for request httpURLConnection.setRequestProperty("Content-Type", "application/json"); try{ //to tell the connection object that we will be wrting some data on the server and then will fetch the output result httpURLConnection.setDoOutput(true); // this is used for just in case we don't know about the data size associated with our request httpURLConnection.setChunkedStreamingMode(0); // to write tha data in our request OutputStream outputStream = new BufferedOutputStream(httpURLConnection.getOutputStream()); OutputStreamWriter outputStreamWriter = new OutputStreamWriter(outputStream); outputStreamWriter.write(my_data); outputStreamWriter.flush(); outputStreamWriter.close(); // to log the response code of your request Log.d(ApplicationConstant.TAG, "MyHttpRequestTask doInBackground : " +httpURLConnection.getResponseCode()); // to log the response message from your server after you have tried the request. Log.d(ApplicationConstant.TAG, "MyHttpRequestTask doInBackground : " +httpURLConnection.getResponseMessage()); }catch (Exception e){ e.printStackTrace(); }finally { // this is done so that there are no open connections left when this task is going to complete httpURLConnection.disconnect(); } }catch (Exception e){ e.printStackTrace(); } return null; } } |
Calling the Async Task :
1 2 3 |
String my_url = "http://192.168.15.107/mylocalserver";// Replace this with your own url String my_data = "Hello my First Request Without any library";// Replace this with your data new MyHttpRequestTask().execute(my_url,my_data); |
That’s all you have created your first HTTP request without using any library.
Keep coding and Keep Sharing 🙂
If you have more details or questions, you can reply to the received confirmation email.
Back to Home
12 comments
Well AsyncTask causes memory leaks, usually, this statement itself is wrong, it’s our faulty code that causes memory leaks. Still, I will not get into the depths of this topic as i don’t know what eactly is your scenario and code.
Regarding any other approaches, I can only suggest using FutureTask or threads for each network calls (This might give you even bigger memory leaks if not handled properly).
where put this line in code ?
Thanks
In order to catch the response to a variable, you will need to modify the request and an InputStream object that will actually catch the response.
After you get the correct InputStream, then you will need to decode the data and assign it to a variable.
So your final AsyncTask will ideally be something like below :
private class MyHttpRequestTask extends AsyncTask {
@Override
protected String doInBackground(String… params) {
String my_url = params[0];
String my_data = params[1];
String final_response=””;
try {
URL url = new URL(my_url);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
// setting the Request Method Type
httpURLConnection.setRequestMethod(“POST”);
// adding the headers for request
httpURLConnection.setRequestProperty(“Content-Type”, “application/json”);
try {
//to tell the connection object that we will be wrting some data on the server and then will fetch the output result
httpURLConnection.setDoOutput(true);
// this is used for just in case we don’t know about the data size associated with our request
httpURLConnection.setChunkedStreamingMode(0);
// to write the data in our request
OutputStream outputStream = new BufferedOutputStream(httpURLConnection.getOutputStream());
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(outputStream);
outputStreamWriter.write(my_data);
outputStreamWriter.flush();
outputStreamWriter.close();
// to read the response data from our request
InputStream inputStream;
if (httpURLConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
inputStream = new BufferedInputStream(httpURLConnection.getInputStream());
}else {
inputStream = new BufferedInputStream(httpURLConnection.getErrorStream());
}
BufferedReader reader = new BufferedReader(new InputStreamReader(
inputStream, “UTF-8”), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + “\n”);
}
inputStream.close();
final_response = sb.toString();
// to log the response code of your request
Log.d(ApplicationConstant.TAG, “MyHttpRequestTask doInBackground : ” + httpURLConnection.getResponseCode());
// to log the response message from your server after you have tried the request.
Log.d(ApplicationConstant.TAG, “MyHttpRequestTask doInBackground : ” + httpURLConnection.getResponseMessage());
} catch (Exception e) {
e.printStackTrace();
} finally {
// this is done so that there are no open connections left when this task is going to complete
httpURLConnection.disconnect();
}
} catch (Exception e) {
e.printStackTrace();
}
return final_response;
}
}
NOTE : I have just looked into the explaination provided in the HttpURLConnection.java class, there might be some small glitches that might need some tuning.
The code is not fully tested, please do check once and do let me know as well 🙂
The my_data can hold any amount of data but if you are getting string too long error, then please debug the case properly.
Further, on the server side, you will definitely need to get the data in the request body through python tools, that will be the only way.
Thanks.