Android Internet Connection Using HTTP Client(GET) - Android Tutorial
In most of the android applications it is essential that app may need to connect to internet and make some HTTP requests. In this article i’ll be demonstrating about making simple HTTP Requests in android.
Objectives:
- How to send HTTP GET request to a web server and display the response?
- How to check network connection?
- How to use AsyncTask to perform network operations on a separate thread?
Below are the code snippets to handle HTTP requests.
How to add HTTP Client?
Open build.gradle located under your app module and add below dependencies. After adding the dependencies,
Open build.gradle located under your app module and add below dependencies. After adding the dependencies,
compile 'org.apache.httpcomponents:httpcore:4.4.1'
compile 'org.apache.httpcomponents:httpclient:4.5'
and in the same add the following
android {
compileSdkVersion 23
buildToolsVersion "23.0.2"
useLibrary 'org.apache.http.legacy' - this is to use this library within your application
and this is due to the support stopped by and Android(due to update).
and Sync the project.
Now let’s see this in action by creating a new project.
1. Add dependencies
In this example, we gave request via HTTP Client and got Images and Texts as a response.
To display Images in RecyclerView and CardView we have to add required dependencies, now it looks as,
build.gradle
dependencies {compile fileTree(dir: 'libs', include: ['*.jar']
compile 'com.android.support:appcompat-v7:23.1.0'
compile 'org.apache.httpcomponents:httpcore:4.4.1'
compile 'org.apache.httpcomponents:httpclient:4.5'
compile 'com.android.support:recyclerview-v7:23.1.1'
compile 'com.android.support:cardview-v7:23.1.1'
compile 'com.github.bumptech.glide:glide:3.7.0'
}
2. Open activity_main.xml and replace with the following
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.mrbrown.httpclient_sample.MainActivity">
<android.support.v7.widget.RecyclerView
android:id="@+id/idRecycler"
android:layout_width="match_parent"
android:layout_height="match_parent">
</android.support.v7.widget.RecyclerView>
</RelativeLayout>
3. Now create the new xml file to implement CardView, here used as card_view.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="1dp">
<android.support.v7.widget.CardView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/card_view">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="5dp">
<ImageView
android:layout_width="100dp"
android:layout_height="100dp"
android:id="@+id/person_photo"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginRight="16dp" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/person_name"
android:layout_toRightOf="@+id/person_photo"
android:layout_alignParentTop="true"/>
</RelativeLayout>
</android.support.v7.widget.CardView>
</LinearLayout>
4. Open the MainActivity.java
public class MainActivity extends AppCompatActivity {
boolean progressenabled = true;
static ProgressDialog progressDialog;
String jsonStr;
String response = "error";
private static RecyclerView recyclerView;
private RecyclerView.LayoutManager m_LayoutManager;
TextView nodata;
String strTesti;
String strUrl;
public static String TAG_IMAGE_URL = "Image";
public static String TAG_CONTENT = "content";
ArrayList<HashMap<String, String>> arraySend = new ArrayList<>();
CustomAdapter customAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView = (RecyclerView)findViewById(R.id.idRecycler);
recyclerView.setHasFixedSize(true);
m_LayoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(m_LayoutManager);
if(isConnectingToInternet(MainActivity.this)){
progressenabled = true;
new httpAsync(MainActivity.this).execute((Void[]) null);
}else {
alertbox(MainActivity.this,
getString(R.string.str_networkmessage),
getString(R.string.str_networktitlemessage));
}
}
//interner_check
private boolean isConnectingToInternet(MainActivity _context) {
ConnectivityManager connectivity = (ConnectivityManager) _context
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo info = connectivity.getActiveNetworkInfo();
if (info == null) {
return false;
} else
return true;
}
private void alertbox(MainActivity _context, String title, String message) {
android.support.v7.app.AlertDialog.Builder builder1 = new android.support.v7.app.AlertDialog.Builder(_context);
builder1.setTitle(title);
builder1.setMessage(message);
builder1.setCancelable(true);
builder1.setPositiveButton("ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
android.support.v7.app.AlertDialog alert11 = builder1.create();
alert11.show();
}
private class httpAsync extends AsyncTask<Void, Void, String>{
private ProgressDialog progressDialog;
private final Context context;
public httpAsync(MainActivity context) {
this.context = context;
}
@Override
protected void onPreExecute() {
if (progressenabled == true) {
progressDialog = ProgressDialog.show(MainActivity.this, "Loading", "please wait ...");
}
}
@Override
protected String doInBackground(Void... params) {
String url = null;
url = "ENTER YOUR URL HERE";
try {
jsonStr = getJSONUrl(url);
response = String.valueOf("true");
} catch (Exception e) {
}
return response;
}
@Override
protected void onPostExecute(String message) {
if (progressenabled == true) {
if(progressDialog!=null){
progressDialog.dismiss();
}
}
if (!message.equals("error")) {
if (message.equals("true")) {
try{
JSONArray resultarray = new JSONArray(jsonStr);
for (int i = 0; i < resultarray.length(); i++) {
JSONObject nmcdata = resultarray.getJSONObject(i);
strUrl = nmcdata.getString(TAG_IMAGE_URL);
strTesti = nmcdata.getString(TAG_CONTENT);
HashMap<String, String> objMap = new HashMap<>();
objMap.put(TAG_IMAGE_URL, strUrl);
objMap.put(TAG_CONTENT, strTesti);
arraySend.add(objMap);
}
dismissDialog();
}catch (JSONException e) {
e.printStackTrace();
}
if (arraySend.size() > 0) {
customAdapter = new CustomAdapter(MainActivity.this, arraySend, recyclerView);
recyclerView.setAdapter(customAdapter);
}
}
}else {
recyclerView.setAdapter(null );
nodata.setText("No Records");
}
}
}
public static String getJSONUrl(String url) {
StringBuilder str = new StringBuilder();
HttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
try {
HttpResponse response = client.execute(httpGet);
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
if (statusCode == 200) {
// Download OK
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(content));
String line;
while ((line = reader.readLine()) != null) {
str.append(line);
}
} else {
Log.e("Log", "Failed to download file..");
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return str.toString();
}
//dismiss_Dialog
public void dismissDialog() {
try {
if (progressDialog.isShowing())
progressDialog.dismiss();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
URL response like this
5. Create a new class CustomAdapter.java to set the images using Recycler View
public class CustomAdapter extends RecyclerView.Adapter{
RecyclerView mrecyclerview;
static Context context;
ArrayList<HashMap<String, String>> Items = new ArrayList<>();
public CustomAdapter(MainActivity context, ArrayList<HashMap<String, String>> arraySend, RecyclerView recyclerView) {
this.context = context;
mrecyclerview = recyclerView;
Items = arraySend;
}
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
RecyclerView.ViewHolder vh;
View itemLayoutView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.card_view, null);
vh = new ViewHolder(itemLayoutView);
return vh;
}
@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
try {
final HashMap<String, String> tempMap = Items.get(position);
((ViewHolder) holder).txtConten.setText(tempMap
.get(MainActivity.TAG_CONTENT));
String urlImg = tempMap
.get(MainActivity.TAG_IMAGE_URL);
Glide.with(context)
.load(urlImg)
.into(((ViewHolder) holder).imgUrl);
}catch (NullPointerException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public int getItemCount() {
return Items.size();
}
private class ViewHolder extends RecyclerView.ViewHolder {
public TextView txtConten;
ImageView imgUrl;
CardView cardview;
public ViewHolder(View itemLayoutView) {
super(itemLayoutView);
cardview = (CardView) itemLayoutView.findViewById(R.id.card_view);
imgUrl = (ImageView) itemLayoutView.findViewById(R.id.person_photo);
txtConten = (TextView) itemLayoutView.findViewById(R.id.person_name);
}
}
}
Uses these strings,
<string name="str_networkmessage">Check your internet connection.</string>
<string name="str_networktitlemessage">Network Issue</string>
6. Give permissions in Manifest.xml
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
Now run the application and get the response output as,
_________________________________________________________________
Source code for HttpClient.zip
Happy Coding...
Comments
Post a Comment