我得到了它的工作:)
首先是不允许的,而且在主线程上做 httprequest 也不好!所以你必须在 AsyncTask 中完成!
其次你不需要检查是否有连接......因为你可以连接到本地连接或连接太慢!
您需要做的就是做 http 请求并检查是否在准确的时间有响应。为此,您需要设置超时!但只有超时不起作用 - 你需要检查状态代码......这里是:
class ConnectionTask extends AsyncTask<String, String, String> {
/**
* Before starting background thread set flag to false
* */
@Override
protected void onPreExecute() {
super.onPreExecute();
flag = false;
}
boolean flag;
/**
* getting All products from url
* */
protected String doInBackground(String... args) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
// getting JSON string from URL
Log.v("url",url);
JSONObject json = jParser.makeHttpRequest(url, "GET", params);
/*is json equal to null ?*/
if( json != null )
{
// Check your log cat for JSON response
Log.d("json: ", json.toString());
try {
message = json.getString("message");
flag = true;//we succeded so we make the flag to true
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
else
{//if json is null
message = "not connected to internet connection";
flag = false;
}
return null;
}
/**
* After completing background task check if there is connection or no
* **/
protected void onPostExecute(String file_url) {
// updating UI from Background Thread
if(flag)
{//flag is tro so there is connection
Log.v("connection", "conectioOOOOOoooOooooOoooooOOOOoooOOOOOO");
runOnUiThread(new Runnable() {
public void run() {
/**
* Updating parsed JSON data into textview
* */
TextView tvTest = (TextView) findViewById(R.id.testTextView);
tvTest.setText(message);
}
});
}
else
{////we catched that there is no connection!
Log.v("connection", "nooooooo conectioOOOOOoooOooooOoooooOOOOoooOOOOOO");
runOnUiThread(new Runnable() {
public void run() {
/*update ui thread*/
TextView tvTest = (TextView) findViewById(R.id.testTextView);
tvTest.setText("no connection");
Toast.makeText(getApplicationContext(), "No internet connection", Toast.LENGTH_LONG).show();
}
});
}
}
}
所以现在json解析器:)
public class JSONParser {
private InputStream is = null;
private JSONObject jObj = null;
private String json = "";
static int timeoutConnection = 10000;
static int timeoutSocket = 10000;
// constructor
public JSONParser() {
}
// function get json from url
// by making HTTP POST or GET method
public JSONObject makeHttpRequest(String url, String method,
List<NameValuePair> params) {
// check for request method
if(method == "POST"){
try{
HttpPost request = new HttpPost(url);
HttpParams httpParameters = new BasicHttpParams();
// Set the timeout in milliseconds until a connection is established.
// The default value is zero, that means the timeout is not used.
HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
// Set the default socket timeout (SO_TIMEOUT)
// in milliseconds which is the timeout for waiting for data.
HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
// create object of DefaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters);
request.addHeader("Content-Type", "application/json");
HttpResponse response = httpClient.execute(request);
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
if (statusCode == 200) {
HttpEntity entity = response.getEntity();
is = entity.getContent();
}
// convert entity response to string
}
catch (SocketException e)
{
e.printStackTrace();
return null;
}
catch (Exception e)
{
e.printStackTrace();
return null;
}
}else if(method == "GET"){
try{
HttpGet request = new HttpGet(url);
HttpParams httpParameters = new BasicHttpParams();
// Set the timeout in milliseconds until a connection is established.
// The default value is zero, that means the timeout is not used.
HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
// Set the default socket timeout (SO_TIMEOUT)
// in milliseconds which is the timeout for waiting for data.
HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
// create object of DefaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters);
request.addHeader("Content-Type", "application/json");
HttpResponse response = httpClient.execute(request);
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
if (statusCode == 200) {
HttpEntity entity = response.getEntity();
is = entity.getContent();
}
// convert entity response to string
}
catch (SocketException e)
{
e.printStackTrace();
return null;
}
catch (Exception e)
{
e.printStackTrace();
return null;
}
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
效果很好!