httpUrlConnection
2017-08-06 19:35
113 查看
public class MainActivity extends AppCompatActivity {
private ListView listView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView) findViewById(R.id.mylist);
findViewById(R.id.mybtn).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
ConnectivityManager manager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
NetworkInfo info = manager.getActiveNetworkInfo();
if (info != null && info.isAvailable()) {//网络可用
MyTask task = new MyTask();
try {
String path = "http://apis.juhe.cn/cook/query.php";
String value = "menu=" + URLEncoder.encode("土豆", "utf-8") + "&key=13af589c334ec80c037688e927407966&rn=1";
//开启异步任务,传入一个string数组,第一个是网络地址,第二个是参数;
task.execute(new String[]{path, value});
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
} else {
//弹出提醒网络未开启,跳转开启网络界面
showDialog();
}
}
});
}
//重写异步任务
class MyTask extends AsyncTask<String, Integer, DataBean> {
@Override
protected DataBean doInBackground(String... params) {
//网络请求
String json = getNetData(params[0], params[1]);
DataBean bean = new Gson().fromJson(json, DataBean.class);
return bean;
}
@Override
protected void onPostExecute(DataBean dataBean) {
super.onPostExecute(dataBean);
//UI操作,给listview赋值,显示第一个菜单里的步骤
MyAdapter adapter = new MyAdapter(MainActivity.this, dataBean.result.data.get(0).steps);
listView.setAdapter(adapter);
}
}
//post网络请求
private String getNetData(String path, String value) {
//获取URL的对象
try {
URL url = new URL(path);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setDoOutput(true);
//写入参数
OutputStream outputStream = connection.getOutputStream();
outputStream.write(value.getBytes());
//获取网络请求状态码
int code = connection.getResponseCode();
//200,连接成功
System.out.println(code+" code");
if (code == HttpURLConnection.HTTP_OK) {
//获取网络请求返回的输入流
InputStream is = connection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
String str = "";
StringBuilder builder = new StringBuilder();
while ((str = reader.readLine()) != null) {
builder.append(str);
}
return builder.toString();
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
//显示网络提醒对话框
private void showDialog() {
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle("网络状态提醒");
builder.setMessage("您的网络未开启,是否开启网络?");
builder.setPositiveButton("开启网络", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//开启网络界面,使用隐示意图
//根据版本号做不同操作
if (Build.VERSION.SDK_INT > 10) {
Intent intent = new Intent(Settings.ACTION_WIRELESS_SETTINGS);
startActivity(intent);
} else {
//SDK<10
Intent intent = new Intent();
ComponentName name = new ComponentName("com.android.settings", "com.android.settings.WIRELESS_SETTINGS");
// Settings.ACTION_WIRELESS_SETTINGS;
intent.setComponent(name);
intent.setAction(Intent.ACTION_VIEW);
startActivity(intent);
}
dialog.dismiss();
}
});
builder.setNegativeButton("不开启", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
builder.create().show();
}
}
private ListView listView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView) findViewById(R.id.mylist);
findViewById(R.id.mybtn).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
ConnectivityManager manager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
NetworkInfo info = manager.getActiveNetworkInfo();
if (info != null && info.isAvailable()) {//网络可用
MyTask task = new MyTask();
try {
String path = "http://apis.juhe.cn/cook/query.php";
String value = "menu=" + URLEncoder.encode("土豆", "utf-8") + "&key=13af589c334ec80c037688e927407966&rn=1";
//开启异步任务,传入一个string数组,第一个是网络地址,第二个是参数;
task.execute(new String[]{path, value});
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
} else {
//弹出提醒网络未开启,跳转开启网络界面
showDialog();
}
}
});
}
//重写异步任务
class MyTask extends AsyncTask<String, Integer, DataBean> {
@Override
protected DataBean doInBackground(String... params) {
//网络请求
String json = getNetData(params[0], params[1]);
DataBean bean = new Gson().fromJson(json, DataBean.class);
return bean;
}
@Override
protected void onPostExecute(DataBean dataBean) {
super.onPostExecute(dataBean);
//UI操作,给listview赋值,显示第一个菜单里的步骤
MyAdapter adapter = new MyAdapter(MainActivity.this, dataBean.result.data.get(0).steps);
listView.setAdapter(adapter);
}
}
//post网络请求
private String getNetData(String path, String value) {
//获取URL的对象
try {
URL url = new URL(path);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setDoOutput(true);
//写入参数
OutputStream outputStream = connection.getOutputStream();
outputStream.write(value.getBytes());
//获取网络请求状态码
int code = connection.getResponseCode();
//200,连接成功
System.out.println(code+" code");
if (code == HttpURLConnection.HTTP_OK) {
//获取网络请求返回的输入流
InputStream is = connection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
String str = "";
StringBuilder builder = new StringBuilder();
while ((str = reader.readLine()) != null) {
builder.append(str);
}
return builder.toString();
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
//显示网络提醒对话框
private void showDialog() {
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle("网络状态提醒");
builder.setMessage("您的网络未开启,是否开启网络?");
builder.setPositiveButton("开启网络", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//开启网络界面,使用隐示意图
//根据版本号做不同操作
if (Build.VERSION.SDK_INT > 10) {
Intent intent = new Intent(Settings.ACTION_WIRELESS_SETTINGS);
startActivity(intent);
} else {
//SDK<10
Intent intent = new Intent();
ComponentName name = new ComponentName("com.android.settings", "com.android.settings.WIRELESS_SETTINGS");
// Settings.ACTION_WIRELESS_SETTINGS;
intent.setComponent(name);
intent.setAction(Intent.ACTION_VIEW);
startActivity(intent);
}
dialog.dismiss();
}
});
builder.setNegativeButton("不开启", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
builder.create().show();
}
}
相关文章推荐
- HttpUrlConnection网络连接
- HttpURLConnection实现文件下载
- Android通过HttpURLConnection与HttpClient联网代理网关设置
- java.net.HttpURLConnection——2014年10月27日20:13:39
- 最终版宝宝取名程序,java版,我家宝宝名字已经确定。 HttpURLConnection
- HttpURLConnection学习
- httpUrlConnection的参数详解
- 转载:HttpURLConnection用法详解
- Android HTTP请求用HttpUrlConnection与HttpClient比较
- HttpUrlConnection请求
- HttpURLConnection和HttpClient分别以GET和POST获取Json数据
- Android网络请求详解,从HTTP协议到httpUrlConnection
- Java Http网络请求HttpURLConnection应用之【Android网络请求框架底层剖析】
- HttpUrlConnection的setDoOutput与setDoInput的区别
- Android网络框架volley学习(四)网络请求HttpURLConnection与HttpClient浅析
- 开源一个网络库ARHttpRequest,iOS适配NSURLSession/ASIHTTPRequest等,Android适配HttpURLConnection等
- HttpURLConnection和HttpClient区别
- httpURLConnection 报错 java.net.ConnectException: localhost/127.0.0.1:8080 - Connection refused
- 使用HttpURLConnection进行POST方式提交
- HttpURLConnection的使用