访问HTTP资源

提交HTTP GET 和HTTP POST请求

本节将介绍Android SDK集成的Apache HttpClient模块,要注意的是,这里的Apache HttpClient模块是 HttpClient 4.0( org.apache.http.* ), 而不是Jakarata Commons HttpClient 3.x ( org.apache.commons.httpclient.* )。
在HttpClient模块中涉及到两个重要的类,HttpGet和HttpPost。这两个类分别用来提交HTTP请求(两种方式)。
首先用服务器wamp,query.php
<?php
header("Content-Type: text/html;charset=utf-8");//必须设置这个编码格式,并且文件保存的格式也是utf-8才行...
if($_SERVER['REQUEST_METHOD']=='POST')
{
    echo "post 请求; 查询字符串;开发;JavaEE宝典";
}
else if($_SERVER['REQUEST_METHOD']=='GET')
{
    echo "get 请求; 查询字符串;开发;JavaEE宝典";
}
?>

用的Java代码,布局方式在下面。

package net.blogjava.mobile;

import java.net.HttpURLConnection;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
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 org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class Main extends Activity implements OnClickListener
{

    @Override
    public void onClick(View view)
    {
        String url = "http://172.18.156.227/query.php";
        TextView tvQueryResult = (TextView) findViewById(R.id.tvQueryResult);
        EditText etBookName = (EditText) findViewById(R.id.etBookName);
        HttpResponse httpResponse = null;
        try
        {

            switch (view.getId())
            {
                //提交HTTP GET请求
                case R.id.btnGetQuery:
                //向url添加请求参数
                    url += "?bookname=" + etBookName.getText().toString();
                    //第一步,创建HttpGet请求
                    HttpGet httpGet = new HttpGet(url);
                    //第二步,使用execute方法发送HTTP GET请求,并返回HttpResponse对象
                    httpResponse = new DefaultHttpClient().execute(httpGet);
                    //判断请求响应状态码,状态码为200表示服务端成功响应了客户端的请求
                    if (httpResponse.getStatusLine().getStatusCode() == 200)
                    {
                        //第三步,使用getEntity()方法获得返回结果
                        String result = EntityUtils.toString(httpResponse
                                .getEntity());
                        // 去掉返回结果中的"\r"字符,否则会在结果字符串后面显示一个方格、                        tvQueryResult.setText(result.replaceAll("\r", ""));
                    }
                    break;

                case R.id.btnPostQuery:
                    HttpPost httpPost = new HttpPost(url);
                    List<NameValuePair> params = new ArrayList<NameValuePair>();
                    params.add(new BasicNameValuePair("bookname", etBookName
                            .getText().toString()));
                    httpPost.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));

                    httpResponse = new DefaultHttpClient().execute(httpPost);
                    if (httpResponse.getStatusLine().getStatusCode() == 200)
                    {
                        String result = EntityUtils.toString(httpResponse
                                .getEntity());
                        tvQueryResult.setText(result.replaceAll("\r", ""));
                    }
                    break;
            }
        }
        catch (Exception e)
        {
            tvQueryResult.setText(e.getMessage());
        }

    }

    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        Button btnGetQuery = (Button) findViewById(R.id.btnGetQuery);
        Button btnPostQuery = (Button) findViewById(R.id.btnPostQuery);
        btnGetQuery.setOnClickListener(this);
        btnPostQuery.setOnClickListener(this);

    }
}

main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="fill_parent"
    android:layout_height="fill_parent">
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:orientation="horizontal" android:layout_width="fill_parent"
        android:layout_height="wrap_content" android:layout_marginTop="10dp">
        <TextView android:layout_width="wrap_content"
            android:layout_height="wrap_content" android:text="书名" android:textSize="16dp"
            android:layout_marginRight="10dp" />
        <EditText android:id="@+id/etBookName" android:layout_width="fill_parent"
            android:layout_height="wrap_content" />
    </LinearLayout>
    <Button android:id="@+id/btnGetQuery" android:layout_width="wrap_content"
        android:layout_height="wrap_content" android:text="GET查询" />
    <Button android:id="@+id/btnPostQuery" android:layout_width="wrap_content"
        android:layout_height="wrap_content" android:text="POST查询" />
    <TextView android:id="@+id/tvQueryResult"
        android:layout_width="fill_parent" android:layout_height="wrap_content" />

</LinearLayout>

HttpURLConnection类

java.net.HttpURLConnection类是另外一种HTTP资源访问的方式,具有完全的访问能力,可以取代HttpGet和HttpPost类,使用HttpUrlConnection访问HTTP资源可以使用如下几步:
(1)使用java.net.URL封装HTTP资源的url,使用openConnection方法获得HttpURLConnection对象,代码如下:

URL url = new URL("http://baidu.com");
HttpURLConnection httpURLConnection = (HttpConnection) url.openConnection();

(2)设置请求方法,为get or post

httpURLConnection.setRequestMethod("POST");

(3)设置输入输出及其他权限,如果要下载HTTP资源或向服务端上传数据,需要使用如下代码进行设置:

//下载HTTP资源,需要将setDoInput方法的参数值设为true
httpURLConnection.setDoInput(true);
//上传数据
httpURLConnection.setDoOutput(true);

使用HttpURLConnection类还包含更多的选项,例如使用下面的代码可以禁止HttpURLConnection使用缓存
httpURLConnection.setUseCaches(false);

(4)设置HTTP请求头
httpURLConnection.setRequestProperty("Charset","UTF-8");

(5)输入和输出数据。这一步是对HTTP资源的读写操作,也就是通过InputStream和OutputStream读取和写入数据。下面的代码获得了InputStream OutputStream对象。

InputStream is = httpURLConnection.getInputStream();
OutputStream os = httpURLConnection.getOutputStream();

(6)关闭输入输出流。这是一个好习惯

is.close(); os.close();
下面通过两个自立分别使用HttpURLConnection和HttpGet来完成同一个例子。

上传文件

代码如下:

http://download.csdn.net/detail/chengyangyy/8824475

现在看重要的部分。
首先需要自定义一个fileBrowser来浏览文件,上传哪一个文件。
还要搭建一个可以上传数据的网站。
之后看主要的代码。
当单击列表中的某一个文件时,会调用SD卡浏览控件的onFileItemClick时间方法,在该方法中负责上传当前单击的文件。代码如下:

@Override
    public void onFileItemClick(String filename)
    {
        String uploadUrl = "http://172.18.156.227/uploadsuccess.php";
        String end = "\r\n";
        String twoHyphens = "--";//两个连字符
        String boundary = "******";//分界符的字符串
        try
        {


            URL url = new URL(uploadUrl);
            HttpURLConnection httpURLConnection = (HttpURLConnection) url
                    .openConnection();
                    //后面使用到了InputStream和OutputStream,所以必须设置下面两行的代码
            httpURLConnection.setDoInput(true);
            httpURLConnection.setDoOutput(true);
            httpURLConnection.setUseCaches(false);
            //方法名称,如POST,必须要大写
            httpURLConnection.setRequestMethod("POST");
            httpURLConnection.setRequestProperty("Connection", "Keep-Alive");
            httpURLConnection.setRequestProperty("Charset", "UTF-8");
//必须在Content-Type请求头中指定分界符中的任意字符串           
httpURLConnection.setRequestProperty("Content-Type",
                    "multipart/form-data;boundary=" + boundary);
//获得OutputStream对象,准备上传文件
            DataOutputStream dos = new DataOutputStream(
                    httpURLConnection.getOutputStream());
//设置分界符,加end表示为单独一行
dos.writeBytes(twoHyphens + boundary + end);
//设置与文件相关的信息
dos.writeBytes("Content-Disposition: form-data; name=\"file\"; filename=\""
                    + filename.substring(filename.lastIndexOf("/") + 1)
                    + "\""
                    + end);
//在上传文件信息与文件内容之间必须有一个空行
            dos.writeBytes(end);

            FileInputStream fis = new FileInputStream(filename);
            byte[] buffer = new byte[8192]; // 8k
            int count = 0;
            //读取文件内容,并写入OutputStream对象
            while ((count = fis.read(buffer)) != -1)
            {
                dos.write(buffer, 0, count);

            }
            fis.close();
            //新起一行
            dos.writeBytes(end);
            //设置结束符号(在分界符后面加两个连字符)
            dos.writeBytes(twoHyphens + boundary + twoHyphens + end);
            dos.flush();
            //开始读取从服务器传过来的信息
            InputStream is = httpURLConnection.getInputStream();
            InputStreamReader isr = new InputStreamReader(is, "utf-8");
            BufferedReader br = new BufferedReader(isr);
            String result = br.readLine();

            Toast.makeText(this, result, Toast.LENGTH_LONG).show();
            dos.close();
            is.close();

        }
        catch (Exception e)
        {
            setTitle(e.getMessage());
        }

    }

调用WebService

参考了:http://blog.csdn.net/lyq8479/article/details/6428288
代码如下:

http://download.csdn.net/detail/chengyangyy/8824473

WebService是一种基于SOAP协议的远程调用标准,通过WebService可以将很多技术,操作系统,语言整合在一起,第三方SDK调用WebService,如KSOAP2

读者按如下6步调用WebService

String serviceUrl = "http://192.168.17.156:8080/axis2/services/SearchProductService?wsdl";
        String methodName = "getProduct";
        //1:指定WebService的命名空间和调用方法,第二个参数表示要调用的WebService方法名。
        SoapObject request = new SoapObject("http://service", methodName);
        //2:设置调用方法的参数值,这一步是可选的,如果没有参数,可以忽略
        request.addProperty("productName", etProductName.getText().toString());
        //3:生成调用WebService方法的SOAP请求信息,该信息由SoapSerializationEnvelope对象描述
        SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
                SoapEnvelope.VER11);
        //设置SoapSerializationEnvelope类的bodyOut属性,为第一步创建的SoapObject对象。
        envelope.bodyOut = request;

        //4:通过HttpTransportSE类的构造方法可以指定WebService的WSDL文档的URL。
        HttpTransportSE ht = new HttpTransportSE(serviceUrl);       
        try
        {
            ht.call(null, envelope);//5:使用call方法调用webservice
            if (envelope.getResponse() != null)
            {
                SoapObject soapObject = (SoapObject) envelope.getResponse();//6: 使用getResponse()方法获得WebService方法的返回结果。
                String result = "产品名称:" + soapObject.getProperty("name") + "\n";
                result += "产品数量:" + soapObject.getProperty("productNumber") + "\n";
                result += "产品价格:" + soapObject.getProperty("price");
                tvResult.setText(result);


            }
            else {
                tvResult.setText("无此产品.");
            }
        }
        catch (Exception e)
        {

        }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值