http发送get、post请求

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/eff666/article/details/53324457

发送get、post请求简单举例,代码如下:

import com.google.common.base.Stopwatch;
import com.google.common.base.Strings;
import org.apache.commons.httpclient.*;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.mortbay.util.UrlEncoded;

import java.io.*;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

public class HttpClientTest {

    //*根据url得到数据
    public static void httpClientTest() throws IOException {
        final Stopwatch stopwatch = Stopwatch.createUnstarted().start();
        String responseMsg = "";

        HttpClient httpClient = new HttpClient();
        String id = "~IgOMOo15IUf1NfENGQV+Gw==~1~_116476553_6";
        String url = "http://xxxxxx/" + UrlEncoded.encodeString(id);

        GetMethod getMethod = new GetMethod(url);
        getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler());

        //3.执行getMethod,调用http接口
        httpClient.executeMethod(getMethod);
        //4.读取内容
        byte[] responseBody = getMethod.getResponseBody();
        //5.处理返回的内容
        responseMsg = new String(responseBody);
        System.out.println(responseMsg);
        System.out.println("query cost 1: " + stopwatch.elapsed(TimeUnit.MILLISECONDS));
    }

    //根据url得到数据
    public static void httpGet(){
        final Stopwatch stopwatch = Stopwatch.createUnstarted().start();
        try {
            String id = "~IgOMOo15IUf1NfENGQV+Gw==~1~_116476553_6";
            //String url = "https://uland.taobao.com/coupon/edetail?e=huuWrBr87UIN%2BoQUE6FNzLHOv%2FKoJ4LsM%2FOCBWMCflrRpLchICCDoqC1%2FGlh90mJfFEjLtoHpPCLQAGMzNbHRBpywujSvOp2nUIklpPPqYL9BYNf2%2FonKY57aXDe3JrR2pd4uaXWR8D1g9gleiedVtDvjgqDLA1q&pid=mm_115940806_14998982_61982315&af=1";
            String url = "https://shop.m.taobao.com/shop/coupon.htm?sellerId=696902416&activityId=4aee3e6538d94b518e19b53d3b04f30c";

            // 创建HttpClient对象
            org.apache.http.client.HttpClient client = HttpClients.createDefault();
            // 创建GET请求(在构造器中传入URL字符串即可)
            HttpGet get = new HttpGet(url);
            // 调用HttpClient对象的execute方法获得响应
            HttpResponse response = client.execute(get);
            response.setHeader("content-type", "application/json");

            ///response.setEntity(new StringEntity(query, "utf-8"));
            // 调用HttpResponse对象的getEntity方法得到响应实体
            HttpEntity httpEntity = response.getEntity();
            // 使用EntityUtils工具类得到响应的字符串表示

            String result = EntityUtils.toString(httpEntity,"utf-8");
            System.out.println(result);
        }catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }catch (IOException e) {
            e.printStackTrace();
        }
        System.out.println("query cost 2:" + stopwatch.elapsed(TimeUnit.MILLISECONDS));
    }

    //可以根据实际的query得到数据
    public static void httpPost(){
        final Stopwatch stopwatch = Stopwatch.createUnstarted().start();
        try {
            String query = "{\"from\":0,\"size\":10,\"query\":{\"bool\":{\"must\":[{\"match\":{\"buyer_nick\":{\"query\":\"11杨柳絮语言\",\"type\":\"phrase\"}}}]}}}";
            // String url = "http://xxxxx:9200/index_address/address/_search";

            String url = "https://shop.m.taobao.com/shop/coupon.htm?sellerId=696902416&activityId=4aee3e6538d94b518e19b53d3b04f30c";

            // 创建HttpClient对象
            org.apache.http.client.HttpClient client = HttpClients.createDefault();

            // 创建POST请求
            HttpPost post = new HttpPost(url);

            // 向POST请求中添加消息实体
            //post.setHeader("content-type", "application/json");
            //post.setEntity(new StringEntity(query, "utf-8"));

            // 得到响应并转化成字符串
            String responseMsg = "";
            HttpResponse response = client.execute(post);
            if(response.getStatusLine().getStatusCode() == 302){
                String locationUrl = response.getLastHeader("Location").getValue();
                System.out.println(locationUrl);
            } else {
                HttpEntity httpEntity = response.getEntity();
                String result = EntityUtils.toString(httpEntity, "UTF-8");
                System.out.println(result);
            }

        }catch (Exception e){

        } finally {

        }
        System.out.println("query cost 3:" + stopwatch.elapsed(TimeUnit.MILLISECONDS));
    }

    /**
     * 执行一个HTTP GET请求,返回请求响应的HTML
     *
     * @return 返回请求响应的HTML
     */
    public static String doGet() {
        String url = "https://shop.m.taobao.com/shop/coupon.htm?sellerId=696902416&activityId=4aee3e6538d94b518e19b53d3b04f30c";
        String response = null;
        HttpClient client = new HttpClient();
        HttpMethod method = new GetMethod(url);
        try {

            client.executeMethod(method);
            if (method.getStatusCode() == HttpStatus.SC_OK) {
                response = method.getResponseBodyAsString();
            }
        } catch (URIException e) {
            System.out.println("执行HTTP Get请求时,编码查询字符串");
        } catch (IOException e) {
            System.out.println("执行HTTP Get请求" + url + "时,发生异常!");
        } finally {
            method.releaseConnection();
        }
        return response;
    }
}
展开阅读全文

没有更多推荐了,返回首页