0.请自行识别代码里的辅助性的提示信息代码,因时间关系不修改了。
有联网功能,要在项目的AndroidManifest.xml文件增加一行
<uses-permission android:name="android.permission.INTERNET" />
同时需要在request的地方先写权限代码
//如果要连接外网,必须在这里配置权限
if (ContextCompat.checkSelfPermission(activity, Manifest.permission.INTERNET)
!= PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(activity, new String[]{Manifest.permission.INTERNET}, 1);
}
1.android的设计:一个APP如果在主线程中请求网络操作,将会抛出此异常。Android这个设计是为了防止网络请求时间过长而导致界面假死的情况发生。如果想在主线成操作,需要在activty的onCreate源码加上如下代码:
//解决主线程不能连接网络的问题 https://blog.csdn.net/llixiangjian/article/details/72910557
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
2. 在任何一个地方写http json request。注意,这里使用apache.http包,参考 http://hmkcode.com/android-send-json-data-to-server/ 添加依赖,file->project structure->选中app->dependencies-->右侧加号-->library-->输入 org.apache.http-->点击搜索-->搜到后添加。不一定是org.apche.http的原包,可能是封装包。
{
//测试http json request
InputStream is = null;
String result = "";
try{
// 1. create HttpClient
HttpClient httpclient = new DefaultHttpClient();
//1
// 2. make POST request to the given URL
HttpPost httpPost = new HttpPost("http://120.27.130.101:8000/android/");
String json = "";
// 3. build jsonObject
JSONObject jsonObject = new JSONObject();
jsonObject.accumulate("name", "tz");
jsonObject.accumulate("country", "china");
jsonObject.accumulate("twitter", "tzc");
// 4. convert JSONObject to JSON to String
// ** Alternative way to convert Person object to JSON string usin Jackson Lib
// ObjectMapper mapper = new ObjectMapper();
// json = mapper.writeValueAsString(person);
json = jsonObject.toString();
// 5. set json to StringEntity
StringEntity se = new StringEntity(json);
// 6. set httpPost Entity
httpPost.setEntity(se);
// 7. Set some headers to inform server about the type of the content
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Content-type", "application/json");
// 8. Execute POST request to the given URL
HttpResponse httpResponse = httpclient.execute(httpPost);
// 9. receive response as inputStream
is = httpResponse.getEntity().getContent();
// 10. convert inputstream to string
if(is != null) {
// 创建字节输出流对象
ByteArrayOutputStream message = new ByteArrayOutputStream();
// 定义读取的长度
int len = 0;
// 定义缓冲区
byte buffer[] = new byte[1024];
// 按照缓冲区的大小,循环读取
while ((len = is.read(buffer)) != -1) {
// 根据读取的长度写入到os对象中
message.write(buffer, 0, len);
}
// 释放资源
is.close();
message.close();
// 返回字符串
String msg = new String(message.toByteArray());
result = msg;
SmsInfo smsinfo = new SmsInfo();
smsinfo.setSms("http-post:"+msg);
infos.add(smsinfo);
}
else{
}
}catch (Exception e){
}finally {
SmsInfo smsinfo = new SmsInfo();
smsinfo.setSms("http-post:fin");
infos.add(smsinfo);
}
}
3.常规http post request
{
String step = "1";
//测试post请求,非json request
try {
String LOGIN_URL = "http://120.27.130.101:8000/android/";
HttpURLConnection conn = (HttpURLConnection) new URL(LOGIN_URL).openConnection();
//设置请求方式,请求超时信息
conn.setRequestMethod("POST");
conn.setReadTimeout(5000);
conn.setConnectTimeout(5000);
//设置运行输入,输出:
conn.setDoOutput(true);
conn.setDoInput(true);
//Post方式不能缓存,需手动设置为false
conn.setUseCaches(false);
//我们请求的数据:
String data = "time_range="+ URLEncoder.encode("300", "UTF-8");
//这里可以写一些请求头的东东...
//获取输出流
OutputStream out = conn.getOutputStream();
out.write(data.getBytes());
out.flush();
if (conn.getResponseCode() == 200) {
// 获取响应的输入流对象
InputStream is = conn.getInputStream();
// 创建字节输出流对象
ByteArrayOutputStream message = new ByteArrayOutputStream();
// 定义读取的长度
int len = 0;
// 定义缓冲区
byte buffer[] = new byte[1024];
// 按照缓冲区的大小,循环读取
while ((len = is.read(buffer)) != -1) {
// 根据读取的长度写入到os对象中
message.write(buffer, 0, len);
}
// 释放资源
is.close();
message.close();
// 返回字符串
String msg = new String(message.toByteArray());
step ="respnose 200:"+conn.getResponseCode()+";message="+message;
SmsInfo smsinfo = new SmsInfo();
smsinfo.setSms("http-post:"+step);
infos.add(smsinfo);
}else{
step ="respnose not 200:"+conn.getResponseCode();
SmsInfo smsinfo = new SmsInfo();
smsinfo.setSms("http-post:"+step);
infos.add(smsinfo);
}
}catch (Exception e){
SmsInfo smsinfo = new SmsInfo();
smsinfo.setSms("http-post error"+e.toString());
infos.add(smsinfo);
}finally {
SmsInfo smsinfo = new SmsInfo();
smsinfo.setSms("http-post fin");
infos.add(smsinfo);
}
}
4. 常规 http get request
{
//测试get请求 成功
String step = "0";
HttpURLConnection connection=null;
InputStreamReader in = null;
try {
step = "1";
URL url = new URL("http://120.27.130.101:8000/android/");
step = "2";
connection = (HttpURLConnection) url.openConnection();
connection.setConnectTimeout(5000);
connection.setRequestMethod("GET");
step = "3";
in = new InputStreamReader(connection.getInputStream());
step = "4";
BufferedReader bufferedReader = new BufferedReader(in);
step = "5";
StringBuffer strBuffer = new StringBuffer();
step = "6";
String line = null;
while ((line = bufferedReader.readLine()) != null) {
strBuffer.append(line);
}
step = "7";
String result = strBuffer.toString();
step = "8";
SmsInfo smsinfo = new SmsInfo();
step = "9";
smsinfo.setSms("http-json:"+step+":"+result);
step = "10";
infos.add(smsinfo);
step = "11";
} catch (Exception e) {
e.printStackTrace();
SmsInfo smsinfo = new SmsInfo();
smsinfo.setSms("http-json error:"+step+":"+e.toString());
infos.add(smsinfo);
} finally {
SmsInfo smsinfo = new SmsInfo();
smsinfo.setSms("http-json fin");
infos.add(smsinfo);
if (connection != null) {
connection.disconnect();
}
if (in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}