//請求網絡(耗時操作)在子線程中進行
更新UI 用Handler runOnUiThread view.post(new RUnnable(){ "更新UI" })等
在API 23中,Google已經移除了移除了Apache HttpClient相關的類 。谷歌推薦使用HttpUrlConnection,如果要繼續使用需要Apache HttpClient,有兩種方法。
1.Eclipse下libs裏添加org.apache.http.legacy.jar
2.studio中的build.gradle
android {
useLibrary 'org.apache.http.legacy'
}
//get請求**************
public void doGet(){
StringBuffer result=new String Buffer();
//創建HttpClient對象,打開一個瀏覽器
HttpClient httpClient=new DefaultHttpClient();
//創建HttpGet對象 ,get請求的對象
HttpGet httpGet=new HttpGet(URL);
try{
//發起請求 走起! 拿到responseduixaing 也是服務器響應的對象
HttpResponse httpResponse= httpClient.execute(httpGet);
//還要根據相應行,拿到響應碼 /**
int responseCode=httpResponse.getStatusLine().getStatusCode(); //響應碼
if(200==responseCode){
//請求成功
HttpEntity entity=httpResponse.getEntity(); //拿到實體對象
InputStream in=entity.getContent();//返回的數據就是字符流
//緩衝流 包含轉換流 字節轉成字符
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
String line = null;
while ((line = reader.readLine()) != null) {
result.append(line);
}
}
}catch(){}
}
//post請求 ****************
putblic void dopost(){
String result = null;
HttpClient client=new DefaultHttpClient();//先拿到對象
HttpPost httpPost=new HttpPost(POSTURL);
try{
//封裝參數的集合
List<NameValuePair> parameters=new ArrayList<NameValuePair>();
//這個集合就是添加要傳遞的參數
parameters.add(new BasicNameValuePair("key",key)); //集合存放對象
parameters.add(new BasicNameValuePair("type",type));
//創建傳遞參數封裝實體對象
UrlEncodedFormEntity encodeEntity=new UrlEncodeFormEntity(parameters,"UTF-8");//設置傳遞參數
///把實體對象存入到httpPost對象中 這一步很重要 post請求需要把集合實體對象添加進去 UrlEncodeFromEntity
httpPost.setEntity(encodeEntity);
//調用第一步中創建好的實例的 execute方法 這一步操作是和get一樣 發起請求了 瀏覽器
HttpResponse response=client.execute(httpPost);
//發送 走~
//然後一樣的操作 拿到響應碼
int responseCode response=response.getStatusLine().getStatusCode();//響應碼
response_msg = response.getStatusLine().getReasonPhrase();//返回內容
if(200==responseCode){
//得到返回的實體對象
HttpEntity entity=response.getEntity();
//返回的實體ENtity對象
InputStream in= entity.getContent();//拿到輸入流
//接收消息
ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
int length = 0;
byte[] buffer = new byte[1024];
while ((length = in.read(buffer)) != -1) {
byteOut.write(buffer, 0, length);
}
}
}
}
//更新UI線程
ImageView.post(new Runnable() {
@Override
public void run() {
ImageView.setImageBitmap(bitmap);
}
});