首先要获取网络连接的状态
添加权限
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
GET方法
ConnectivityManager manager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
NetworkInfo info = manager.getActiveNetworkInfo();
if (info.isAvailable()) {
try {
(
String
value =
"menu=" + URLEncoder.encode(
"牛肉",
"utf-8") +
"&key=13af589c334ec80c037688e927407966&rn=1";
String path =
"http://apis.juhe.cn/cook/query.php?" +
value;)
URL url =
new URL(path);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
int code = connection.getResponseCode();
if (code ==
200) {
System.
out.println(
"访问网络成功");
InputStream
is = connection.getInputStream();
String result =
"";
String str =
"";
BufferedReader reader =
new BufferedReader(
new InputStreamReader(
is));
while ((str = reader.readLine()) !=
null) {
result += str;
}
System.
out.println(result);
}
}
catch (Exception e) {
e.printStackTrace();
}
}
POST方法
try {
String path =
"http://apis.juhe.cn/cook/query.php";
String
value =
"menu=" + URLEncoder.encode(
"韭菜",
"utf-8") +
"&key=13af589c334ec80c037688e927407966&rn=1";
URL url =
new URL(path);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod(
"POST");
connection.setDoOutput(
true);
OutputStream stream = connection.getOutputStream();
stream.write(
value.getBytes());
int code = connection.getResponseCode();
if (code ==
200) {
InputStream inputStream = connection.getInputStream();
BufferedReader reader =
new BufferedReader(
new InputStreamReader(inputStream));
String result =
"";
String str =
null;
while ((str = reader.readLine()) !=
null) {
result += str;
}
System.
out.println(
"result"+result);
return result;
}
}
catch (Exception e) {
e.printStackTrace();
}
**这里还可以用另一种post方法来实现 POST答大致方法都差不多最终实现最后的目的就可以**
String path=”http://apis.juhe.cn/cook/query?menu=”+”红烧肉”+”&key=3dbfbb17a76e634a16349d723ea81a31&pn=1&rn=1”;
try { URL url=new URL(path); HttpURLConnection connection= (HttpURLConnection) url.openConnection();
connection.setRequestMethod(“GET”); connection.setConnectTimeout(3000); connection.setReadTimeout(3000); connection.setDoInput(true); int i=connection.getResponseCode(); ByteArrayOutputStream baos=new ByteArrayOutputStream(); if(i==200){ InputStream is=connection.getInputStream(); byte[] buffer=new byte[1024]; int len=-1; while((len=is.read(buffer))!=-1){ baos.write(buffer,0,len); } str=baos.toString(); }
} catch (Exception e) { e.printStackTrace(); }