这里有一个非常棒的http通讯的总结,我看了以后茅塞顿开。
以下代码特别需要注意:在android 4.0后的系统不适用,会报错的,不能直接在UI线程中使用网络访问。
先贴代码:
public class Activity1 extends Activity { private final String DEBUG_TAG = "System.out"; private TextView mTextView; private Button mButton; protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); mTextView = (TextView) findViewById(R.id.TextView01); mButton = (Button) findViewById(R.id.Button01); mButton.setOnClickListener(new httpListener()); } // 设置按钮监听器 class httpListener implements OnClickListener { public void onClick(View v) { refresh(); } } private void refresh() { String httpUrl = "http://192.168.0.101:8080/Test/test.jsp"; // URL可以加参数 // String httpUrl = // "http://192.168.0.101:8080/Test/test.jsp?par=abcdefg"; String resultData = ""; URL url = null; try { // 创建一个URL对象 url = new URL(httpUrl); } catch (MalformedURLException e) { Log.d(DEBUG_TAG, "create URL Exception"); } // 声明HttpURLConnection对象 HttpURLConnection urlConn = null; // 声明InputStreamReader对象 InputStreamReader in = null; // 声明BufferedReader对象 BufferedReader buffer = null; String inputLine = null; if (url != null) { try { // 使用HttpURLConnection打开连接 urlConn = (HttpURLConnection) url.openConnection(); // 得到读取的内容(流) in = new InputStreamReader(urlConn.getInputStream()); // 创建BufferReader对象,输出时候用到 buffer = new BufferedReader(in); // 使用循环来读取数据 while ((inputLine = buffer.readLine()) != null) { // 在每一行后面加上换行 resultData += inputLine + "\n"; } // 设置显示取的的内容 if (resultData != null && !resultData.equals("")) { mTextView.setText(resultData); } else { mTextView.setText("读取的内容为空"); } } catch (IOException e) { e.printStackTrace(); } finally { try { // 关闭InputStreamReader in.close(); // 关闭URL连接 urlConn.disconnect(); } catch (IOException e) { e.printStackTrace(); } } } else { Log.d(DEBUG_TAG, "URL is NULL"); } } }
public class Activity2 extends Activity { private final String DEBUG_TAG = "System.out"; private TextView mTextView; private Button mButton; protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); mTextView = (TextView) findViewById(R.id.TextView01); mButton = (Button) findViewById(R.id.Button01); mButton.setOnClickListener(new httpListener()); } // 设置按钮监听器 class httpListener implements OnClickListener { public void onClick(View v) { refresh(); } } private void refresh() { String httpUrl = "http://192.168.0.101:8080/Test/test.jsp"; String resultData = ""; URL url = null; try { // 创建一个URL对象 url = new URL(httpUrl); } catch (MalformedURLException e) { Log.d(DEBUG_TAG, "create URL Exception"); } // 声明HttpURLConnection对象 HttpURLConnection urlConn = null; // 声明InputStreamReader对象 InputStreamReader in = null; // 声明BufferedReader对象 BufferedReader buffer = null; String inputLine = null; // 声明DataOutputStream流 DataOutputStream out = null; if (url != null) { try { // 使用HttpURLConnection打开连接 urlConn = (HttpURLConnection) url.openConnection(); // 因为这个是POST请求所以要设置为true urlConn.setDoInput(true); urlConn.setDoOutput(true); // 设置POST方式 urlConn.setRequestMethod("POST"); // POST请求不能设置缓存 urlConn.setUseCaches(false); urlConn.setInstanceFollowRedirects(false); // 配置本次连接的Content-type,配置为application/x-www-form-urlencoded的 urlConn.setRequestProperty("Content-Type","application/x-www-form-urlencoded"); // 连接,从postUrl.openConnection()至此的配置必须要在connect之前完成 // 要注意的是connectio.getOutputStream会隐含的进行connect urlConn.connect(); // DataOutputStream流 out = new DataOutputStream(urlConn.getOutputStream()); String content = "par=" + URLEncoder.encode("abcdefg", "gb2312"); // 将要上传的内容写入流中 out.writeBytes(content); // 得到读取的内容(流) in = new InputStreamReader(urlConn.getInputStream()); // 创建BufferReader对象,输出时候用到 buffer = new BufferedReader(in); // 使用循环来读取数据 while ((inputLine = buffer.readLine()) != null) { // 在每一行后面加上换行 resultData += inputLine + "\n"; } // 设置显示取的的内容 if (resultData != null && !resultData.equals("")) { mTextView.setText(resultData); } else { mTextView.setText("读取的内容为空"); } } catch (IOException e) { e.printStackTrace(); } finally { try { // 刷新DataOutputStream流 out.flush(); // 关闭DataOutputStream流 out.close(); // 关闭InputStreamReader in.close(); // 关闭URL连接 urlConn.disconnect(); } catch (IOException e) { e.printStackTrace(); } } } else { Log.d(DEBUG_TAG, "URL is NULL"); } } }
public class Activity3 extends Activity{ private TextView mTextView; private Button mButton; protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); mTextView = (TextView) findViewById(R.id.TextView01); mButton = (Button) findViewById(R.id.Button01); mButton.setOnClickListener(new httpListener()); } // 设置按钮监听器 class httpListener implements OnClickListener { public void onClick(View v) { String httpUrl = "http://192.168.0.101:8080/Test/test.jsp?par=HttpClient_android_Get"; // HttpGet连接对象 HttpGet httpRequest = new HttpGet(httpUrl); try { // 取的HttpClient对象 HttpClient httpclient = new DefaultHttpClient(); // 请求HttpClient,取的HttpResponse HttpResponse httpResponse = httpclient.execute(httpRequest); // 请求成功 if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { // 取的返回的字符串 String strResult = EntityUtils.toString(httpResponse.getEntity()); // 这个返回值可能会在行尾出现小方格 // 在TextView要显示的文字过滤掉回车符("\r")就可以正常显示了。 String strsResult = strResult.replace("\r", ""); mTextView.setText(strsResult); } else { mTextView.setText("请求错误"); } } catch (ClientProtocolException e) { mTextView.setText(e.getMessage().toString()); } catch (IOException e) { mTextView.setText(e.getMessage().toString()); } catch (Exception e) { mTextView.setText(e.getMessage().toString()); } } } }
public class Activity4 extends Activity{ private TextView mTextView; private Button mButton; protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); mTextView = (TextView) findViewById(R.id.TextView01); mButton = (Button) findViewById(R.id.Button01); mButton.setOnClickListener(new httpListener()); } // 设置按钮监听器 class httpListener implements OnClickListener { public void onClick(View arg0) { String httpUrl = "http://192.168.0.101:8080/Test/test.jsp"; // 创建HttpPost连接对象 HttpPost httpRequest = new HttpPost(httpUrl); // 使用NameValuePair来保存要传递的Post参数 List params = new ArrayList(); // 添加要传递的参数 params.add(new BasicNameValuePair("par","HttpClient_android_Post")); try { // 设置字符集 HttpEntity httpentity = new UrlEncodedFormEntity(params,"gb2312"); // 请求httpRequest httpRequest.setEntity(httpentity); // 取的默认的HttpClient HttpClient httpclient = new DefaultHttpClient(); // 取的HttpResponse HttpResponse httpResponse = httpclient.execute(httpRequest); // HttpStatus.SC_OK表示连接成功 if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { // 取的返回的字符串 String strResult = EntityUtils.toString(httpResponse.getEntity()); // 这个返回值可能会在行尾出现小方格 // 在TextView要显示的文字过滤掉回车符("\r")就可以正常显示了。 String strsResult = strResult.replace("\r", ""); mTextView.setText(strsResult); } else { mTextView.setText("请求错误"); } } catch (ClientProtocolException e) { mTextView.setText(e.getMessage().toString()); } catch (IOException e) { mTextView.setText(e.getMessage().toString()); } catch (Exception e) { mTextView.setText(e.getMessage().toString()); } } } }