If you think the Android project WarDroid listed in this page is inappropriate, such as containing malicious code/tools or violating the copyright, please email info at java2s dot com, thanks.
Java Source Code
package com.deathsnacks.wardroid.utils;
//www.java2s.comimport android.content.SharedPreferences;
import android.util.Log;
import com.squareup.okhttp.OkHttpClient;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
/**
* Created by Deathmax on 10/20/13.
*/publicclass Http {
privatestaticfinal String TAG = "Http";
privatestatic OkHttpClient client = new OkHttpClient();
publicstatic String get(String Url) throws IOException {
URL url = new URL(Url);
HttpURLConnection connection = client.open(url);
System.setProperty("http.agent", "");
connection.setRequestProperty("User-Agent", "WarDroid/Android/");
InputStream in = null;
try {
if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
in = connection.getErrorStream();
} else {
in = connection.getInputStream();
}
byte[] response = readAll(in);
returnnew String(response, "UTF-8");
} finally {
if (in != null) in.close();
}
}
publicstatic String get(String Url, SharedPreferences preferences, String key) throws IOException {
URL url = new URL(Url);
HttpURLConnection connection = client.open(url);
System.setProperty("http.agent", "");
connection.setRequestProperty("User-Agent", "WarDroid/Android/");
long lastModified = preferences.getLong(key + "_modified", 0);
String cache = preferences.getString(key + "_cache", "_ded");
if (lastModified != 0) {
connection.setIfModifiedSince(lastModified);
}
InputStream in = null;
try {
if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
in = connection.getInputStream();
byte[] response = readAll(in);
String txt = new String(response, "UTF-8");
SharedPreferences.Editor editor = preferences.edit();
editor.putLong(key + "_modified", connection.getLastModified());
editor.putString(key + "_cache", txt);
editor.commit();
return txt;
} elseif (connection.getResponseCode() == HttpURLConnection.HTTP_NOT_MODIFIED) {
Log.d(TAG, "Cache hit on " + key + " cache: " + cache);
return cache;
} else {
thrownew IOException("Http get returned " + connection.getResponseCode());
}
} finally {
if (in != null) in.close();
}
}
privatestaticbyte[] readAll(InputStream in) throws IOException {
ByteArrayOutputStream out = new ByteArrayOutputStream();
byte[] buffer = newbyte[1024];
for (int count; (count = in.read(buffer)) != -1; ) {
out.write(buffer, 0, count);
}
return out.toByteArray();
}
}