import java.io.IOException;
import java.io.InputStream;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.json.JSONObject;
public class JSONUtil {
private static final String TAG = "JSONUTIL";
public static JSONObject getJSON(String url) throws Exception {
return new JSONObject(getRequest(url));
}
protected static String getRequest(String url) {
return getRequest(url, new DefaultHttpClient(new BasicHttpParams()));
}
protected static String getRequest(String url, DefaultHttpClient client) {
String result = null;
int statusCode = 0;
HttpGet httpGet = new HttpGet(url);
try {
HttpResponse httpResponse = client.execute(httpGet);
statusCode = httpResponse.getStatusLine().getStatusCode();// statusCode为200时表示请求数据成功
result = parseInputStream(httpResponse.getEntity());
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
httpGet.abort();
}
return result;
}
private static String parseInputStream(HttpEntity entity) {
StringBuilder sb = null;
try {
sb = new StringBuilder("");
InputStream inputStream = entity.getContent();
int length = 0;
byte[] buffer = new byte[1024];
while ((length = inputStream.read(buffer)) > -1) {
sb.append(new String(buffer, 0, length));
}
return sb.toString();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return sb.toString();
}
}
主activity中调用:数据格式{ad_gap_time:1200000, ad_silence_time:1800000,ad_count:3 }
private void Livingstone() {
try {
String URL = "http://192.168.1.123:8080/index2.jsp";
// 获取后台返回的JSON对象 --> {ad_gap_time:1200000, ad_silence_time:1800000,ad_count:3 }
JSONObject jsonObject = JSONUtil.getJSON(URL);
int classname = jsonObject.getInt("ad_count");
long i=jsonObject.getLong("ad_gap_time");
AdParm adParm = new AdParm();
// adParm.setAd_gap_time(jsonObject.getLong("ad_gap_time"));
// adParm.setAd_silence_time(jsonObject
// .getLong("ad_silence_time"));
// adParm.setAd_count(jsonObject.getInt("ad_count"));
sharedPreferences
.edit()
.putLong("ad_gap_time",
jsonObject.getLong("ad_gap_time"))
.putLong("ad_silence_time",
jsonObject.getLong("ad_silence_time"))
.putInt("ad_count", jsonObject.getInt("ad_count"))
.commit();
adParm.setAd_count(jsonObject.getInt("ad_count"));
adParm.setAd_gap_time(jsonObject.getLong("ad_gap_time"));
adParm.setAd_silence_time(jsonObject.getLong("ad_silence_time"));
textView.setText(sharedPreferences.getLong("ad_gap_time", 0)+"");
System.out.println("------->" + classname + classname);
} catch (Exception e) {
e.printStackTrace();
}
}