android 网络技术基础学习 (七)

使用httpclient协议访问网络:

public class MainActivity extends Activity implements OnClickListener{
    public void onClick(View v){
        if(v.getId()==R.id.send_request){
        sendRequestWithHttpClients();
        }
    }
    private void sendRequestWithHttpClients(){
        new Thread(new Runnable(){
            public void run(){
            try{
                HttpClient httpClient=new DefaultHttpClient();//创建一个DefaultHttpClient实例,注意httpclient是一个接口不能直接创建实例
                HttpGet httpget=new HttpGet("URL");创建httpget对象
                HttpResponse httpResponse=httpClient.execute(httpGet);
                if(httpResponse.getStatusline().getStatusCode()==200){//首先取出状态码判断是否请求和响应成功
                 HttpEntity entity=httpResponse.getEntity();//调用getEntity获得实例并转化成字符
                 String response=EntityUtils.toString(entity,"utf-8");
                 Message message=new Message();
                 message.what=SHOW_RESPONSE;
                 message.obj=response.toString();
                 handler.sendMessage(message);
                 }
            }catch(Exception e){ e.printStackTrace;}
            }
            }
        }).start();
    }
}

使用jsonobject解析服务器响应的数据:

private void parseJSONWithJSONObject(String jsonData){
    try{
        JSONArray jsonArray=new JSONArray(jsonData);//将返回的数据传入一个数组中
        for(int i=0;i<jsonArray.lenth();i++){
            JSONObject jsonObject=jsonArray.getJSONObject(i);//调用getjsonobject获得实例再用getString取出打印就行
            String id=jsonObject.getString("id");
            String name=jsonObject.getString("name");
            String version=jsonObject.getString("version");
            Log.d("MainActivity","id is"+id);
            ..
            
            }
    }catch(Exception e){
        e.printStackTrace;
        }
}

网络编程的最佳实践:
为了在使用中更方便 所以把通用的操作提取到公共类中,并提供一个静态方法,为了防止请求网络的时候超时而影响主线程被阻塞,直接开启子线程又会无法返回数据,于是就启用java的回调机制

public interface HttpCallbackListener{  //接口中定义两个方法 使用onFinish()返回响应的数据,onError()在网络错误的时候调用
    void onFinish(String response);
    void onError(Exception e);
}
public class HttpUtil{
    public static void sendHttpRequest(final String address,final HttpCallbackListener listener){
        new Thread(new Runnable){
        @Override
          public void run(){
            HttpURLConnection connection=null;
            try{
                URL url=new URL(address);
                connection=(HttpURLConnection)url.openConnection();
                connection.setRequestMethod("GET");
                connection.setConnectTimeout(8000);
                connection.setReadTimeout(8000);
                connecion.setDoInput(true);
                connection.setDoOutput(ture);
                InputStream in=connecion.getInputStream();
                BufferedReader reader=new BufferedReader(new InputStreamReader(in));
                StringBuidler response=new StringBuidler();
                String line;
                while((line=reader.readLine())!=null){
                    response.append(line);
                }
                if(listener!=null){
                    listener.onFinish(response.toString());
                }
            }catch(Exception e){
                if(listener!=null){listener.onError();}
            }finally{
                if(connection!=null){
                    connection.disconnect();
                }
            }
          }
        }.start();
    }
}
特别注意:
如果需要根据返回的结果来更新ui那么也要一定使用异步消息处理机制,onfinish实际也是在子线程中运行的
原文地址:https://www.cnblogs.com/zzy-frisrtblog/p/5349772.html