Java发送HTTP请求(GET和POST)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/lw_zj_ywn/article/details/78782067

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();

猜你喜欢

转载自blog.csdn.net/lw_zj_ywn/article/details/78782067