Java实现get或post请求

来源:互联网 发布:淘宝网大毛衣外套 编辑:程序博客网 时间:2024/06/06 08:34

添加 jar 包支持

httpclient-4.3.1.jarhttpcore-4.3.jarcommons-logging-1.0.4.jar

编写工具类

import java.io.IOException;import java.net.URLEncoder;import java.util.ArrayList;import java.util.List;import java.util.Map;import org.apache.http.HttpResponse;import org.apache.http.client.ClientProtocolException;import org.apache.http.client.HttpClient;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.HttpClients;import org.apache.http.message.BasicNameValuePair;import org.apache.http.util.EntityUtils;public class HttpUtils {    private static final String UTF_8 = "UTF-8";    public static String post(String url, Map<String, Object> params)            throws Exception {        String result = "";        HttpClient client = HttpClients.createDefault();        HttpPost httpPost = new HttpPost(url);        if (params != null && !params.isEmpty()) {            List<BasicNameValuePair> parameters = new ArrayList<BasicNameValuePair>();            for (Map.Entry<String, Object> entry : params.entrySet()) {                String name = entry.getKey();                String value = entry.getValue().toString();                BasicNameValuePair pair = new BasicNameValuePair(name, value);                parameters.add(pair);            }            httpPost.setEntity(new UrlEncodedFormEntity(parameters, UTF_8));        }        try {            HttpResponse response = client.execute(httpPost);            if (response.getStatusLine().getStatusCode() == 200) {                result = EntityUtils.toString(response.getEntity(), UTF_8);            } else {                throw new Exception(response.toString());            }        } catch (ClientProtocolException e) {            e.printStackTrace();        } catch (IOException e) {            e.printStackTrace();        }        return result;    }    public static String get(String url, Map<String, Object> params) throws Exception {        String result = "";        HttpClient client = HttpClients.createDefault();        if (params != null && !params.isEmpty()) {            StringBuffer buffer = new StringBuffer();            buffer.append("?");            for (Map.Entry<String, Object> entry : params.entrySet()) {                String name = entry.getKey();                String value = URLEncoder.encode(entry.getValue().toString(), UTF_8);                buffer.append(name).append("=").append(value).append("&");            }            url += buffer.substring(0, buffer.length()-1).toString();        }        HttpGet get = new HttpGet(url);        get.setHeader("charset", UTF_8);        try {            HttpResponse response = client.execute(get);            if (response.getStatusLine().getStatusCode() == 200) {                result = EntityUtils.toString(response.getEntity(), UTF_8);            } else {                throw new Exception(response.toString());            }        } catch (ClientProtocolException e) {            e.printStackTrace();        } catch (IOException e) {            e.printStackTrace();        }        return result;    }}

编写测试代码

import java.util.HashMap;import java.util.Map;public class HttpTest {    public static void main(String[] args) {        String url = "http://ws.webxml.com.cn/WebServices/MobileCodeWS.asmx/getMobileCodeInfo";        try {            Map<String, Object> params = new HashMap<String, Object>();            params.put("mobileCode", "1888888");            params.put("userID", "");            String result = HttpUtils.get(url, params);            System.out.println("GET请求:\n" + result);            result = HttpUtils.post(url, params);            System.out.println("POST请求:\n" + result);        } catch (Exception e) {            e.printStackTrace();        }    }}

测试结果

GET请求:<?xml version="1.0" encoding="utf-8"?><string xmlns="http://WebXml.com.cn/">1888888:北京 北京 北京移动全球通卡</string>POST请求:<?xml version="1.0" encoding="utf-8"?><string xmlns="http://WebXml.com.cn/">1888888:北京 北京 北京移动全球通卡</string>
原创粉丝点击