Android Http通信

Android 当中涉及到网络编程的部分经常会用到http通信,同时android也为我么您提供了HttpUrlConnection接口和HttpClient接口,大大的方便了开发。Http通信又分为两种方式:get和post,get可以uoqu静态页面,传入参数可以放在url当中,而post方法的传入参数则是放在httprequest(请求)当中。前面提到的HttpUrlConnection接口是Java当中的通信接口,而HttpClient则是java当中自带的通信接口。

android解析一个图片:

public class MainActivity extends AppCompatActivity {

private WebView webView;
private ImageView imageView;
private Handler handler = new Handler();

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    webView = (WebView) findViewById(R.id.webview);
    imageView = (ImageView) findViewById(R.id.imageview);
    new HttpThread("http://h.hiphotos.baidu.com/image/pic/item/6c224f4a20a446239e8d311c9b22720e0cf3d70d.jpg", imageView, handler).start();
}
}

public class HttpThread extends Thread {

private String url;
private WebView webView;
private ImageView imageView;
private Handler handler;

/*public HttpThread(String url, WebView webView, Handler handler) {
    this.url = url;
    this.webView = webView;
    this.handler = handler;
}*/

public HttpThread(String url, ImageView imageView, Handler handler) {
    this.url = url;
    this.imageView = imageView;
    this.handler = handler;
}

@Override
public void run() {
    try {
         URL httpUrl = new URL(url);
        try {
            HttpURLConnection conn = (HttpURLConnection) httpUrl.openConnection();
            conn.setConnectTimeout(5000);
            conn.setRequestMethod("GET");
            conn.setDoInput(true);
            /*final StringBuffer sb = new StringBuffer();
            BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String str;
            while ((str = reader.readLine()) != null) {
                sb.append(str);
            }
            handler.post(new Runnable() {
                @Override
                public void run() {
                    webView.loadData(sb.toString(), "text/html;charset=utf-8", null);
                }
            });*/
            InputStream is = conn.getInputStream();
            FileOutputStream out = null;
            File downloadFile = null;
            String fileName = String.valueOf(System.currentTimeMillis());
            if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
                File parent = Environment.getExternalStorageDirectory();
                downloadFile = new File(parent,fileName);
                out = new FileOutputStream(downloadFile);
            }
            byte[] b = new byte[2*1024];
            int len;
            if (out != null){
                while ((len = is.read(b))!=-1){
                    out.write(b,0,len);
                }
            }
            final Bitmap bitmap = BitmapFactory.decodeFile(downloadFile.getAbsolutePath());
            handler.post(new Runnable() {
                @Override
                public void run() {
                   imageView.setImageBitmap(bitmap);
                }
            });
       } catch (IOException e) {
            e.printStackTrace();
        }
        } catch (MalformedURLException e) {
        e.printStackTrace();
    }
 }
}

与服务器之间的交互:

public class RegistActivity extends AppCompatActivity {

private EditText  nameET,ageET;
private Button    submitBT;

@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.layout_regist);
    nameET = (EditText)findViewById(R.id.name_edit);
    ageET = (EditText)findViewById(R.id.age_edit);
    submitBT = (Button)findViewById(R.id.button);
    submitBT.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            String url = "http://192.168.16.126:8080/HelloWorld/MyServlet";
            String name = nameET.getText().toString();
            String age = ageET.getText().toString();
           new HttpThread1(url, name, age).start();             
        }
    });
}
 }

public class HttpThread1 extends Thread {

private String url;
private String name;
private String age;

public HttpThread1(String url, String name, String age) {
    this.url = url;
    this.name = name;
    this.age = age;
}

@Override
public void run() {
   // doGet();
    doPost();
 }

private void doPost() {
    try {
        Properties properties = System.getProperties();
        properties.list(System.out);

        URL httpUrl = new URL(url);
        HttpURLConnection conn = (HttpURLConnection) httpUrl.openConnection();
        conn.setRequestMethod("POST");
        conn.setReadTimeout(5000);
        OutputStream out = conn.getOutputStream();
        String content = "name="+name+"&age="+age;
        out.write(content.getBytes());
        BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        StringBuffer sb = new StringBuffer();
        String str;
        while ((str=reader.readLine())!=null){
            sb.append(str);
        }
        System.out.println(sb.toString());
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

public void doGet(){
    try {
        url = url + "?name=" + URLEncoder.encode(name,"utf-8") + "&age=" + age;
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    }
    try {
        URL httpUrl = new URL(url);
        HttpURLConnection conn = (HttpURLConnection) httpUrl.openConnection();
        conn.setRequestMethod("GET");
        conn.setReadTimeout(5000);
        BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        String  str = null;
        StringBuffer sb = new StringBuffer();
        while ((str = reader.readLine())!=null){
            sb.append(str);
        }
        System.out.println("result:" + sb.toString());
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}
 }

使用HttpClient的方式交互:

public class RegistActivity extends AppCompatActivity {

private EditText  nameET,ageET;
private Button    submitBT;

@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.layout_regist);
    nameET = (EditText)findViewById(R.id.name_edit);
    ageET = (EditText)findViewById(R.id.age_edit);
    submitBT = (Button)findViewById(R.id.button);
    submitBT.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            String url = "http://192.168.16.126:8080/HelloWorld/MyServlet";
            String name = nameET.getText().toString();
            String age = ageET.getText().toString();
           // url = url + "?name=" + name + "&age=" + age;
            new HttpClientThread(url,name,age).start();
        }
    });
}
}

public class HttpClientThread extends Thread {

private String url;
private String name;
private String age;

/*public HttpClientThread(String url){
    this.url = url;
}*/

public HttpClientThread(String url, String name, String age) {
    this.url = url;
    this.name = name;
    this.age = age;
}

@Override
public void run() {
   // doHttpClientGet();
    doHttpClientPost();
 }

private void doHttpClientPost() {
    HttpClient client = new DefaultHttpClient();
    HttpPost post = new HttpPost(url);
    ArrayList<NameValuePair> list = new ArrayList<>();
    list.add(new BasicNameValuePair("name",name));
    list.add(new BasicNameValuePair("age",age));
    try {
        post.setEntity(new UrlEncodedFormEntity(list));
        HttpResponse response = client.execute(post);
        if (response.getStatusLine().getStatusCode()==HttpStatus.SC_OK){
            String content = EntityUtils.toString(response.getEntity());
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}

public void doHttpClientGet(){
    try {
        HttpGet httpget = new HttpGet(url);
        HttpClient client = new DefaultHttpClient();
        HttpResponse response = client.execute(httpget);
        if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK){
            String content = EntityUtils.toString(response.getEntity());

            System.out.println("content---------->" + content);
        }
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}
}

由此可以得出结论: get与post的区别?

1.get通常是从服务器上获取数据,post通常是向服务器传送数据。
2.get是把参数数据队列加到表单的 ACTION属性所指的URL中,值和表单内各个字段一一对应,在URL中可以看到,实际上就是URL拼接方式。post是通过HTTPpost机制,将表单内各个字段与其内容放置在HTML HEADER内一起传送到ACTION属性所指的URL地址。
3.对于get方式,服务器端用 Request.QueryString获取变量的值,对于post方式,服务器端用Request.Form获取提交的数据。
4.get 传送的数据量较小,不能大于1KB[IE,Oher:4]。post传送的数据量较大,一般被默认为不受限制。但理论上,IIS4中最大量为80KB,IIS5中为100KB。
5.get安全性非常低,post安全性较高。

  • 3
    点赞
  • 32
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值