//请求json方法
public static String getJson(String urlString) {
try {
//封装url接口
URL url = new URL(urlString);
//打开了连接
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
int responseCode = urlConnection.getResponseCode();
if (responseCode == 200) {
InputStream inputStream = urlConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
String t="";
StringBuilder stringBuilder = new StringBuilder();
while ((t =bufferedReader.readLine()) != null){
stringBuilder.append(t);
}
return stringBuilder.toString();
} else {
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return "";
}
//请求网络图片方法
public static Bitmap getBitmpa(String mUrl) {
try {
//封装url接口
URL url = new URL(mUrl);
//打开了连接
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
int responseCode = urlConnection.getResponseCode();
if (responseCode == 200) {
InputStream inputStream = urlConnection.getInputStream();
//得到图片
Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
return bitmap;
} else {
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
HttpClient
-
.grade里
android{
下面 useLibrary ‘org.apache.http.legacy’ -
Activity里 继承AppCompatActivity
开线程try { //发送请求的对象 DefaultHttpClient defaultHttpClient = new DefaultHttpClient(); //请求方式 HttpGet httpGet = new HttpGet(urlString); //发送请求 HttpResponse response = defaultHttpClient.execute(httpGet); int statusCode = response.getStatusLine().getStatusCode(); if (statusCode == 200) { HttpEntity entity = response.getEntity(); String jsonResult = EntityUtils.toString(entity); Log.e("可以自己名","statusCode--请求成功json--->:"+jsonResult); }else { Log.e("可以自己名","statusCode--请求失败:"+statusCode); } } catch (IOException e) { e.printStackTrace(); }