Java发送HTTP请求(GET和POST)

来源:互联网 发布:学建筑软件 编辑:程序博客网 时间:2024/03/29 13:02

HTTP请求工具类

import net.sf.json.JSONObject;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.entity.StringEntity;import org.apache.http.impl.client.DefaultHttpClient;import org.apache.http.util.EntityUtils;import java.io.IOException;public class HttpClientUtil {    /**     * 发送get请求     * @param url(get请求的url)     * @return     */    public static JSONObject doGetStr(String accessTokenUrl) {        DefaultHttpClient httpClient = new DefaultHttpClient();        HttpGet httpGet = new HttpGet(accessTokenUrl);        JSONObject jsonObject = null;        try {            HttpResponse response = httpClient.execute(httpGet);            HttpEntity entity = response.getEntity();            if (entity != null) {                String result = EntityUtils.toString(entity, "UTF-8");                jsonObject = JSONObject.fromObject(result);            }            httpGet.releaseConnection();        } catch (IOException e) {            e.printStackTrace();        }        return jsonObject;    }     /**     * 发送post请求     * @param url     * @param param     * @return     */    public static JSONObject doPostStr(String url,String param){        DefaultHttpClient httpClient = new DefaultHttpClient();        HttpPost httpPost = new HttpPost(url);        JSONObject jsonObject = null;        try {            httpPost.setEntity(new StringEntity(param, "UTF-8"));            HttpResponse response = httpClient.execute(httpPost);            String result = EntityUtils.toString(response.getEntity(),"UTF-8");            jsonObject = JSONObject.fromObject(result);        } catch (IOException e) {            e.printStackTrace();        }        return jsonObject;    }}

主要介绍一下post的param格式

        JSONObject params = new JSONObject();        params.put("param1",param1);        params.put("param2",param2);        String param = params.toString();
原创粉丝点击