HttpClient的用法小结

HttpClient的用法小结

HttpClient的使用步骤:

  • 1、使用DefaultHttpClient类实例化HttpClient对象
  • 2、创建HttpGet或HttpPost对象,将要请求的URL通过构造方法传入HttpGet或HttpPost对象。
  • 3、调用execute方法发送HTTP GET或HTTP POST请求,并返回HttpResponse对象。
  • 4、通过HttpResponse接口的getEntity方法返回响应信息,并对获取的原始数据进行相应的处理。

此处以Get请求为例:

package Test;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import javax.swing.text.Document;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.xml.sax.InputSource;


@SuppressWarnings("deprecation")
public class MsgThread extends Thread {

    @Override
    public void run() {

        String url="http://121.40.137.165/OpenPlatform/OpenApi?action=sendOnce"
                +"&"+"ac="
                +"&"+"authkey="
                +"&"+"cgid="
                +"&"+"csid="
                +"&"+"c="+java.net.URLEncoder.encode("测试短信发送内容")
                +"&"+"m=";
        try {

            @SuppressWarnings({ "resource", "deprecation" })
            HttpClient httpclient = new DefaultHttpClient();//实例化HttpClient对象

            HttpGet httpget = new HttpGet(url); //  get方式创建 HttpGet对象
            HttpResponse response = httpclient.execute(httpget);  // 发送HttpGet请求

            int a = response.getStatusLine().getStatusCode();

            byte[] msgBody = null;

            if (a == 200) {
                HttpEntity entity = response.getEntity(); // 获取响应实体进行处理。 此处获取到的为xml文件,需对此进行解析。

                InputStream is = entity.getContent();
                ;// 获取返回数据

                byte[] temp = new byte[1024];
                int n = 0;
                ByteArrayOutputStream bos = new ByteArrayOutputStream();
                while ((n = is.read(temp)) != -1) {
                    bos.write(temp, 0, n);
                }
                msgBody = bos.toByteArray();
                bos.close();
                is.close();
                String returnXml = new String(msgBody, "UTF-8").trim();

                System.out.println("获取到的xml数据为:"+returnXml);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

}

你可能感兴趣的:(开发技术)