httpURLConnection、URL、httpClient、httpPost、httpGet
参考:http://blog.csdn.net/qxs965266509/article/details/9072483
package com.example.lesson09_login; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.UnsupportedEncodingException; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.ProtocolException; import java.net.URL; import java.net.URLEncoder; import java.util.ArrayList; import java.util.List; import org.apache.http.HttpResponse; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.HttpClient; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.message.BasicNameValuePair; import android.annotation.SuppressLint; import android.app.Activity; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.text.TextUtils; import android.util.Log; import android.view.Menu; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; @SuppressLint("HandlerLeak") public class MainActivity extends Activity { public Button btn_get, btn_post; public EditText et_name, et_pass; public NetWorkUtil netWorkUtil; public Handler handler; public static final int GET = 1; public static final int POST = 2; public String name, pass, content; public String path = "http://172.22.64.18:8080/lesson09_login/csdn/UserAction_login.action"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); btn_get = (Button) findViewById(R.id.btn_get); btn_post = (Button) findViewById(R.id.btn_post); et_name = (EditText) findViewById(R.id.et_name); et_pass = (EditText) findViewById(R.id.et_pass); netWorkUtil = new NetWorkUtil(this); handler = new Handler() { @Override public void handleMessage(Message msg) { super.handleMessage(msg); switch (msg.what) { case GET: Toast.makeText(MainActivity.this, "GET请求成功++++++++++", Toast.LENGTH_LONG).show(); Log.v("MainActity", content); break; case POST: Toast.makeText(MainActivity.this, "POST请求成功----------", Toast.LENGTH_LONG).show(); Log.v("MainActity", content); break; default: break; } } }; } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } public void sendGet(View v) { if (!isEmpty()) { Toast.makeText(MainActivity.this, "用户名或密码不能为空...", Toast.LENGTH_LONG).show(); } else { boolean flag = netWorkUtil.setNetWork(); if (flag) { new Thread(new Runnable() { @Override public void run() { name = et_name.getText().toString(); pass = et_pass.getText().toString(); // sendGetRequest(path, name, pass); sendGetClient(path, name, pass); handler.sendEmptyMessage(GET); } }).start(); } } } public void sendPost(View v) { if (!isEmpty()) { Toast.makeText(MainActivity.this, "用户名或密码不能为空...", Toast.LENGTH_LONG).show(); } else { boolean flag = netWorkUtil.setNetWork(); if (flag) { new Thread(new Runnable() { @Override public void run() { name = et_name.getText().toString(); pass = et_pass.getText().toString(); // sendPostRequest(path, name, pass); sendPostClient(path, name, pass); handler.sendEmptyMessage(POST); } }).start(); } } } public boolean isEmpty() { boolean flag = false; if (TextUtils.isEmpty(et_name.getText().toString()) || TextUtils.isEmpty(et_pass.getText().toString())) { flag = false; } else { flag = true; } return flag; } @SuppressWarnings("unused") private void sendGetRequest(String path, String name, String pass) { String str = path + "?user.name=" + name + "&user.pass=" + pass; try { URL url = new URL(str); HttpURLConnection httpURLConnection = (HttpURLConnection) url .openConnection(); httpURLConnection.setConnectTimeout(5000); httpURLConnection.setRequestMethod("GET"); if (httpURLConnection.getResponseCode() == 200) { InputStream is = httpURLConnection.getInputStream(); ByteArrayOutputStream bos = new ByteArrayOutputStream(); byte[] buf = new byte[1024]; int len = 0; while ((len = is.read(buf)) != -1) { bos.write(buf, 0, len); } byte[] data = bos.toByteArray(); bos.flush(); bos.close(); is.close(); content = new String(data); if (content.contains("gb2312")) { content = new String(data, "gb2312"); } } httpURLConnection.disconnect(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (ProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } @SuppressWarnings("unused") private void sendPostRequest(String path, String name, String pass) { try { String data = "user.name=" + name + "&user.pass=" + pass; URL url = new URL(path); HttpURLConnection httpURLConnection = (HttpURLConnection) url .openConnection(); httpURLConnection.setConnectTimeout(5000); httpURLConnection.setRequestMethod("POST"); httpURLConnection.setDoOutput(true); httpURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); httpURLConnection.setRequestProperty("Content-Length", data.length() + ""); OutputStream os = httpURLConnection.getOutputStream(); byte[] buf = data.getBytes(); os.write(buf); os.flush(); os.close(); if (httpURLConnection.getResponseCode() == 200) { InputStream is = httpURLConnection.getInputStream(); ByteArrayOutputStream bos = new ByteArrayOutputStream(); byte[] buf1 = new byte[1024]; int len = 0; while ((len = is.read(buf1)) != -1) { bos.write(buf1, 0, len); } byte[] data1 = bos.toByteArray(); bos.flush(); bos.close(); is.close(); content = new String(data1); } httpURLConnection.disconnect(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } public void sendGetClient(String path, String name, String pass) { try { String uri = path + "?user.name=" + URLEncoder.encode(name, "UTF-8") + "&user.pass=" + URLEncoder.encode(pass, "UTF-8"); HttpClient httpClient = new DefaultHttpClient(); HttpGet httpGet = new HttpGet(uri); HttpResponse httpResponse = httpClient.execute(httpGet); if (httpResponse.getStatusLine().getStatusCode() == 200) { InputStream is = httpResponse.getEntity().getContent(); content = StringTool.isContent(is); } } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } @SuppressWarnings("unused") public void sendPostClient(String path, String name, String pass) { HttpClient httpClient = new DefaultHttpClient(); HttpPost httpPost = new HttpPost(path); List<BasicNameValuePair> parameters = new ArrayList<BasicNameValuePair>(); parameters.add(new BasicNameValuePair("user.name", name)); parameters.add(new BasicNameValuePair("user.pass", pass)); UrlEncodedFormEntity entity = null; try { entity = new UrlEncodedFormEntity(parameters, "UTF-8");
httpPost.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8)); HttpResponse httpResponse = httpClient.execute(httpPost); if (httpResponse.getStatusLine().getStatusCode() == 200) { InputStream is = httpResponse.getEntity().getContent(); content = StringTool.isContent(is); } } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }
httpClient建立过程
- 创建HttpClient对象。
- 如果需要发送GET请求,创建HttpGet对象;如果需要发送POST请求,创建HttpPost对象。
- 如果需要发送请求参数,可调用HttpGet、HttpPost共同的setParams(HetpParams params)方法来添加请求参数;对于HttpPost对象而言,也可调用setEntity(HttpEntity entity)方法来设置请求参数。
- 调用HttpClient对象的execute(HttpUriRequest request)发送请求,执行该方法返回一个HttpResponse。
- 调用HttpResponse的getAllHeaders()、getHeaders(String name)等方法可获取服务器的响应头;调用HttpResponse的getEntity()方法可获取HttpEntity对象,该对象包装了服务器的响应内容。程序可通过该对象获取服务器的响应内容。
httpClient 与 httpUrlConnect区别
在一般情况下,如果只是需要Web站点的某个简单页面提交请求并获取服务器响应,HttpURLConnection完全可以胜任。但在绝大部分情况下,Web站点的网页可能没这么简单,这些页面并不是通过一个简单的URL就可访问的,可能需要用户登录而且具有相应的权限才可访问该页面。在这种情况下,就需要涉及Session、Cookie的处理了,如果打算使用HttpURLConnection来处理这些细节,当然也是可能实现的,只是处理起来难度就大了。
为了更好地处理向Web站点请求,包括处理Session、Cookie等细节问题,Apache开源组织提供了一个HttpClient项目,看它的名称就知道,它是一个简单的HTTP客户端(并不是浏览器),可以用于发送HTTP请求,接收HTTP响应。但不会缓存服务器的响应,不能执行HTML页面中嵌入的Javascript代码;也不会对页面内容进行任何解析、处理。
简单来说,HttpClient就是一个增强版的HttpURLConnection,HttpURLConnection可以做的事情HttpClient全部可以做;HttpURLConnection没有提供的有些功能,HttpClient也提供了,但它只是关注于如何发送请求、接收
响应,以及管理HTTP连接。