//创建一个HTttpClient工具,方便以后任意调用
public class HttpClienTools {
static String resultString;public static String getJson(String path) {
try {
HttpClient client = new DefaultHttpClient();
HttpGet get = new HttpGet(path);
HttpResponse response;
response = client.execute(get);
if (response.getStatusLine().getStatusCode() == 200) {
HttpEntity entity = response.getEntity();// 返回实体对象
InputStream inputStream = entity.getContent();// 读取实体中的内容
resultString = StreamTools.strTool(inputStream);//调用输出工具
}
} catch (ClientProtocolException e) {e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return resultString;
}
}
//字节流输出转化工具
public class StreamTools {
public static String strTool(InputStream inputStream) {
// TODO Auto-generated method stub
try {
ByteArrayOutputStream stream = new ByteArrayOutputStream();// 定义字符节数组输出对象
byte[] buffer = new byte[1024];// 定义读取的缓冲区
int len = 0;
while ((len = inputStream.read(buffer)) != -1) {
stream.write(buffer, 0, len);
}
inputStream.close();
stream.close();
byte[] data = stream.toByteArray();// 把读取的字节数组输出流转化为字节数组
return new String(data, "UTF-8");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
}
//调用实例
@Override
public void onClick(View view) {
// TODO Auto-generated method stub
final String uString = user.getText().toString();
final String pString = psw.getText().toString();
if (TextUtils.isEmpty(uString.trim())|| TextUtils.isEmpty(pString.trim())) {
Toast.makeText(MainActivity.this, "用户名或者密码不能为空",Toast.LENGTH_LONG).show();
} else {
new Thread(new Runnable() {
@Override
public void run() {
String resultString = HttpClienTools
.getJson("http://etac.yindatech.com:8822/eTAC/user/phone/login.do?account="
+ uString
+ "&password="
+ pString
+ "&pt=?");
JSONObject jsonObject;
try {
jsonObject = new JSONObject(resultString);
String key = jsonObject.getString("key");// 解析得到Key
String pathString = HttpClienTools
.getJson("http://etac.yindatech.com:8822/eTAC/case/phone/hot.do?key="+key+"");
JSONArray array = new JSONArray(pathString);//解析Json
String[] titles = new String[array.length()];//定义数组
for (int i = 0; i < array.length(); i++) {
JSONObject jsonObject3 = array.getJSONObject(i);
String title = jsonObject3.getString("name");
// Log.i("info", title);
titles[i] = title;
}
Intent intent = new Intent(MainActivity.this, SearchMain.class);
intent.putExtra("titles", titles);
intent.putExtra("key", key);
startActivity(intent);
finish();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}).start();
}
}
});