private void setThread() {
mThread=new Thread(){
@Override
public void run() {
super.run();
if (Ntil.isNetworkAvailable(CS2Activity.this)){
mResponse=Ntil.sendData("http://192.168.1.118:8080/classserver/readPartInfo");
Log.i("调试",mResponse);
parseData();
mHandler.sendEmptyMessage(UP_DATA);
}else {
mHandler.sendEmptyMessage(NET);
}
}
};
}
package com.example.rachel.ytceshi;
import android.content.Context;
import android.net.ConnectivityManager;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
/**
* Created by Rachel on 2017/3/6.
*/
public class Ntil {
private static HttpURLConnection con;
private static BufferedReader buff;
public static boolean isNetworkAvailable(Context context) {
boolean is=false;
ConnectivityManager conManager= (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (null==conManager||null==conManager.getActiveNetworkInfo()){
is=false;
}else {
is=true;
}
return is;
}
public static String sendData(String s) {
String mResult="";
try {
createConnectiom(s);
setParams();
mResult=readData(mResult);
return mResult;
}catch (Exception e){
e.printStackTrace();
}finally {
if (buff!=null){
try {
buff.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return mResult;
}
private static String readData(String mResult) {
try {
buff=new BufferedReader(new InputStreamReader(con.getInputStream()));
String line;
if ((line=buff.readLine())!=null){
if (mResult.equals("")){
mResult+=line;
}else {
mResult+="
"+line;
}
}
} catch (IOException e) {
e.printStackTrace();
}
return mResult;
}
private static void createConnectiom(String s) {
try {
URL murl=new URL(s);
con = (HttpURLConnection) murl.openConnection();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
private static void setParams() {
con.setConnectTimeout(20*1000);
con.setReadTimeout(20*1000);
con.setDoInput(true);
con.setDoOutput(true);
}
}