您的位置:首页 > 理论基础 > 计算机网络

Android网络请求

2016-08-05 18:14 281 查看
简单的HttpURLConnection网络请求数据
private void requestGson() {
progressDialog.show();
new Thread() {
public void run() {
try {
URL url = new URL(address + index);
HttpURLConnection openConnection = (HttpURLConnection) url
.openConnection();
openConnection.setConnectTimeout(5000);
int responseCode = openConnection.getResponseCode();
if (responseCode == 200) {
//
InputStream inputStream = openConnection
.getInputStream();
String json = StreamUtils.parseStream(inputStream);

// 解析json
Gson gson = new Gson();
WeiInfo weiInfo = gson.fromJson(json, WeiInfo.class);

handler.obtainMessage(0, weiInfo).sendToTarget();
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
};
}.start();
}empty

将我们请求的
public class StreamUtils {
public static String parseStream(InputStream inputStream) {
try {
ByteArrayOutputStream arrayOutputStream = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len = 0;
while ((len = inputStream.read(buffer)) != -1) {
arrayOutputStream.write(buffer, 0, len);
}
return arrayOutputStream.toString();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: