【Android】Web开发之通过标准Java接口处理Http请求

来源:互联网 发布:一起看软件神器 编辑:程序博客网 时间:2024/06/05 08:04

处理GET请求核心代码

import java.net.*;import java.io.*;URL url = "http://10.0.2.2/android/http_get.jsp?username=tom";// 使用HttpURLConnection打开连接HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();// 得到读取的内容(流)InputStreamReader in = new InputStreamReader(urlConn.getInputStream());// 为输出创建BufferedReaderBufferedReader buffer = new BufferedReader(in);String inputLine = null;// 使用循环来读取获得的数据while (((inputLine = buffer.readLine()) != null)) {resultData += inputLine + "\n";}

处理POST请求核心代码

HttpURLConnection urlConn = (HttpURLConnection) urlConn.setDoOutput(true);urlConn.setDoInput(true);urlConn.setRequestMethod("POST");// 设置以POST方式DataOutputStream out = new DataOutputStream(urlConn.getOutputStream());// 要上传的参数String content = "par=" + URLEncoder.encode("ABCDEFG中文", "UTF-8");out.writeBytes(content);// 将要上传的内容写入流中// 得到读取的内容(流)InputStreamReader in = new InputStreamReader(urlConn.getInputStream());...//和GET等同

处理GET请求方法

发送GET请求并获取服务器端返回值:
public String handleGet(String strUrl) {try {URL url = new URL(strUrl);// 使用HttpURLConnection打开连接HttpURLConnection conn = (HttpURLConnection) url.openConnection();conn.connect();//打开到此 URL 引用的资源的通信链接// 得到读取的内容(流)InputStream stream = conn.getInputStream();byte[] data = new byte[100*1024];int len = stream.read(data);result = new String(data, 0, len);result =  EncodingUtils.getString(result.getBytes(), "UTF-8");//编码工具类解决中文乱码conn.disconnect();//指示服务器近期不太可能有其他请求stream.close();} catch (Exception ee) {System.out.print("ee:" + ee.getMessage());}return result;}


处理POST请求方法

携带一个params数据发送Post请求到指Url:
public String handlePost(String strUrl, String params) {try {URL url = new URL(strUrl);// 使用HttpURLConnection打开连接HttpURLConnection conn = (HttpURLConnection) url.openConnection();conn.setRequestMethod("POST");//设置 URL 请求的方法conn.setDoInput(true);//允许接收输入conn.setDoOutput(true);//允许接收输出//conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");conn.connect();//打开到此 URL 引用的资源的通信链接//用DataOutputStream.writeBytes(content)将请求参数写入进去DataOutputStream dos = new DataOutputStream(conn.getOutputStream());dos.writeBytes(params);dos.close();try {//获取该连接的输入InputStream stream = conn.getInputStream();byte[] data = new byte[100* 1024];int len = stream.read(data);result = new String(data, 0, len);result =  EncodingUtils.getString(result.getBytes(), "UTF-8");conn.disconnect();//指示服务器近期不太可能有其他请求stream.close();} catch (Exception e) {System.out.print("e:" + e.getMessage());}} catch (Exception e) {System.out.print("e:" + e.getMessage());}return result;}

应用实例

为了更加清晰的理解上述两个方法,可通过下述实例进行练习。
【注】服务请求是应该写在Handler中,配合线程一起使用的,在这里为了测试简便而暂不使用。
具体应用可参考:http://blog.csdn.net/jueblog/article/details/12530751

Activity

package com.app.myweb;import java.io.DataOutputStream;import java.io.InputStream;import java.net.HttpURLConnection;import java.net.URL;import org.apache.http.util.EncodingUtils;import android.app.Activity;import android.graphics.drawable.Drawable;import android.os.Bundle;import android.view.View;import android.view.View.OnClickListener;import android.widget.Button;import android.widget.TextView;/** * 范例:通过标准Java接口处理Http请求 */public class JavaHttp_JSP extends Activity implements OnClickListener {private TextView textView1, textView2;private Button button1, button2;private String result;@Overridepublic void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.http_jsp);setUI(); setAction();}public void setUI() {textView1 = (TextView) findViewById(R.id.textView1);/*textView1.setText("利用Java标准接口java.net.*类实现读取指定url内容");*/textView2 = (TextView) findViewById(R.id.textView2);button1 = (Button) findViewById(R.id.button1);button2 = (Button) findViewById(R.id.button2);}public void setAction() {findViewById(R.id.button1).setOnClickListener(this);findViewById(R.id.button2).setOnClickListener(this);}/** 发送GET请求并获取服务器端返回值 */public String handleGet(String strUrl) {try {URL url = new URL(strUrl);// 使用HttpURLConnection打开连接HttpURLConnection conn = (HttpURLConnection) url.openConnection();conn.connect();//打开到此 URL 引用的资源的通信链接// 得到读取的内容(流)InputStream stream = conn.getInputStream();byte[] data = new byte[100*1024];int len = stream.read(data);result = new String(data, 0, len);result =  EncodingUtils.getString(result.getBytes(), "UTF-8");//编码工具类解决中文乱码conn.disconnect();//指示服务器近期不太可能有其他请求stream.close();} catch (Exception ee) {System.out.print("ee:" + ee.getMessage());}return result;}/** 携带一个params数据发送Post请求到指Url */public String handlePost(String strUrl, String params) {try {URL url = new URL(strUrl);// 使用HttpURLConnection打开连接HttpURLConnection conn = (HttpURLConnection) url.openConnection();conn.setRequestMethod("POST");//设置 URL 请求的方法conn.setDoInput(true);//允许接收输入conn.setDoOutput(true);//允许接收输出//conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");conn.connect();//打开到此 URL 引用的资源的通信链接//用DataOutputStream.writeBytes(content)将请求参数写入进去DataOutputStream dos = new DataOutputStream(conn.getOutputStream());dos.writeBytes(params);dos.close();try {//获取该连接的输入InputStream stream = conn.getInputStream();byte[] data = new byte[100* 1024];int len = stream.read(data);result = new String(data, 0, len);result =  EncodingUtils.getString(result.getBytes(), "UTF-8");conn.disconnect();//指示服务器近期不太可能有其他请求stream.close();} catch (Exception e) {System.out.print("e:" + e.getMessage());}} catch (Exception e) {System.out.print("e:" + e.getMessage());}return result;}@Overridepublic void onClick(View view) {switch (view.getId()) {case R.id.button1:textView1.setText(handleGet("http://10.0.2.2:8888/android/1.jsp"));break;case R.id.button2:textView2.setText(handlePost("http://10.0.2.2:8888/android/2.jsp" , "username=tom&password=111"));break;default:break;}}}

XML布局文件

<?xml version="1.0" encoding="utf-8"?><ScrollView xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="fill_parent"    android:layout_height="fill_parent" >   <LinearLayout        android:layout_width="fill_parent"        android:layout_height="wrap_content"        android:orientation="vertical" >        <TextView            android:id="@+id/textView1"            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:singleLine="false"            android:text="接收GET请求" />        <Button            android:id="@+id/button1"            android:layout_width="fill_parent"            android:layout_height="wrap_content"            android:text="标准Java接口:发送GET请求" />        <TextView            android:id="@+id/textView2"            android:layout_width="fill_parent"            android:layout_height="wrap_content"            android:singleLine="false"            android:text="接收Post请求" />        <Button            android:id="@+id/button2"            android:layout_width="fill_parent"            android:layout_height="wrap_content"            android:text="标准Java接口:发送POST请求" />        <TextView            android:id="@+id/textView3"            android:layout_width="fill_parent"            android:layout_height="wrap_content"            android:singleLine="false"            android:text="" />            </LinearLayout></ScrollView>


原创粉丝点击