android 网络通讯

时间:2023-03-09 01:55:16
android 网络通讯

//get方式请求网络数据
String urlPath="http://192.168.98.112:8080/CloudMusicPlayer/fragment1_1_lv2/json/SongInfo.json";
// String data="SongName=驿动的心&SongAutor=姜育恒";
HttpURLConnection connection=null;
try {
URL url=new URL(urlPath);
connection=(HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setUseCaches(false);
connection.setConnectTimeout(10000);
connection.setReadTimeout(5000);
if(connection.getResponseCode()==200){
InputStream is=connection.getInputStream();
int count=0;
StringBuilder sb=new StringBuilder();
while((count=is.read())!=-1){
sb.append((char)count);
}
if(is!=null){
is.close();
}
try {
JSONObject jsonObject=new JSONObject(sb.toString());
final String songName = jsonObject.getString("SongName");
final String SongAutor = jsonObject.getString("SongAutor");
Log.v("msg",songName);
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
head_tv1.setText(songName);
head_tv2.setText(SongAutor);
}
});
} catch (JSONException e) {
e.printStackTrace();
}
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
if(connection!=null){
connection.disconnect();
}
}