HttpClientUtil发送json格式请求

package http;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;  
import java.util.Map.Entry;

import net.sf.json.JSONObject;
import util.Base64;

import org.apache.commons.httpclient.params.HttpMethodParams;
import org.apache.http.HttpEntity;  
import org.apache.http.HttpResponse;  
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;  
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;  
import org.apache.http.entity.StringEntity;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;



/*
 * 利用HttpClient进行post请求的工具类
 */  
public class HttpClientUtil {  
    
    private static final Logger logger = Logger.getLogger(HttpClientUtil.class);
    
    static{
        try {
            System.setProperty("jsse.enableSNIExtension", "false");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    /**
     * 发送post请求
     * @param url 请求路径
     * @param param 请求json数据
     * @return
     */
    public static String doPost(String url,JSONObject param){  
        HttpPost httpPost = null;  
        String result = null;  
        try{  
            HttpClient client =  new SSLClient();
            httpPost = new HttpPost(url);
            if(param != null){
                StringEntity se = new StringEntity(param.toString(),"utf-8");
//                se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json; charset="));
                httpPost.setEntity(se); //post方法中,加入json数据
                httpPost.setHeader("Content-Type","application/json");
            }
            
            HttpResponse response = client.execute(httpPost);
            if(response != null){  
                HttpEntity resEntity = response.getEntity();  
                if(resEntity != null){  
                    result = EntityUtils.toString(resEntity,"utf-8");  
                }  
            }  
            
        }catch(Exception ex){  
            ex.printStackTrace();  
        }  
        System.out.println("返回结果:\n"+result);
        return result;  
    }  
    
    /**
     * 发送post请求
     * @param url 请求路径
     * @param jsonparam 请求json数据字符串
     * @return
     */
    public static String taikangPost(String url,String jsonparam){  
        HttpPost httpPost = null;  
        String result = null;  
        try{  
            HttpClient client =  new SSLClient();
            httpPost = new HttpPost(url);
            logger.info("请求路径:\n"+url);
            logger.info("请求参数:\n"+jsonparam);
            if(jsonparam != null){
                jsonparam = Base64.encodeGBK(jsonparam.getBytes("GBK"));
                StringEntity se = new StringEntity(jsonparam,"GBK");
                httpPost.setEntity(se); //post方法中,加入json数据
                httpPost.setHeader("Content-Type","application/text");
            }
            
            HttpResponse response = client.execute(httpPost);
            
            if(response != null){  
                HttpEntity resEntity = response.getEntity();  
                if(resEntity != null){  
                    result = EntityUtils.toString(resEntity,"GBK");
                    logger.info("返回结果原始字符串:\n"+result);
                    result = Base64.decode(result,"GBK");
                }  
            }  
            
        }catch(Exception ex){  
            ex.printStackTrace();  
        }  
        logger.info("返回结果:\n"+result);
        return result;  
    }  
    
    
    /**
     * 发送post请求
     * @param url 请求路径
     * @param param 请求参数数据
     * @return
     */
    @SuppressWarnings("unchecked")
    public static String doPostMap(String url,Map<String, String> map){  
        HttpClient httpClient = null;  
        HttpPost httpPost = null;  
        String result = null;  
        try{  
            httpClient = new SSLClient();  
            httpPost = new HttpPost(url);  
            //设置参数  
            List<NameValuePair> list = new ArrayList<NameValuePair>();  
            Iterator iterator = map.entrySet().iterator();  
            while(iterator.hasNext()){  
                Entry<String,String> elem = (Entry<String, String>) iterator.next();  
                list.add(new BasicNameValuePair(elem.getKey(),elem.getValue()));  
            }  
            if(list.size() > 0){  
                UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list,"UTF-8");  
                httpPost.setEntity(entity);  
            }  
            HttpResponse response = httpClient.execute(httpPost);  
            if(response != null){  
                HttpEntity resEntity = response.getEntity();  
                if(resEntity != null){  
                    result = EntityUtils.toString(resEntity,"UTF-8");  
                }  
            }  
        }catch(Exception ex){  
            ex.printStackTrace();  
        }  
        logger.info("返回结果"+result);
        return result;  
    }  
    
    /**
     * 发送get请求
     * @param url 请求路径
     * @param param 请求json数据
     * @return
     */
    public static String doGet(String url){
         String result = null;  
         try{  
            HttpClient client = new SSLClient();
            //用get方法发送http请求
            HttpGet get = new HttpGet(url);
            CloseableHttpResponse httpResponse = null;
            //发送get请求
            httpResponse = (CloseableHttpResponse) client.execute(get);
            try{
                //response实体
                HttpEntity entity = httpResponse.getEntity();
                if (null != entity){
                    result = EntityUtils.toString(entity,"utf-8");
                }
            }
            finally{
                httpResponse.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;  
    }  
    
    public static void main(String[] args) {
        JSONObject obj = new JSONObject();
        obj.element("a", 1);
//        HttpClientUtil.doPost("http://180.168.131.15/cpf/tianan_cpf/access/car/queryCarModel.mvc",obj);
        HttpClientUtil.taikangPost("http://ecuat.tk.cn/tkcoop_zz/service/proposalEntrance/proposalCreateEntrance?sign=ehaitun&comboid=1007A00901&fromId=62667",obj.toString());
    }
    
    
}  

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
### 回答1: Java发送HTTP请求,并且以JSON格式发送POST请求的示例如下: ```java import org.apache.http.HttpEntity; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.ContentType; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.util.EntityUtils; import java.io.IOException; public class HttpRequestExample { public static void main(String[] args) throws IOException { // 创建HttpClient对象 CloseableHttpClient httpClient = HttpClients.createDefault(); // 创建HttpPost对象,设置URL HttpPost httpPost = new HttpPost("http://example.com/api/endpoint"); // 设置请求头 httpPost.setHeader("Content-Type", "application/json"); // 设置请求String jsonBody = "{\"name\":\"John\",\"age\":30}"; StringEntity requestEntity = new StringEntity(jsonBody, ContentType.APPLICATION_JSON); httpPost.setEntity(requestEntity); // 发送请求并获取响应 CloseableHttpResponse response = httpClient.execute(httpPost); try { // 获取响应实体 HttpEntity entity = response.getEntity(); if (entity != null) { // 将响应实体转为字符串,并打印输出 String result = EntityUtils.toString(entity); System.out.println(result); } } finally { // 关闭响应和HttpClient response.close(); httpClient.close(); } } } ``` 以上代码示例中,使用了Apache HttpClient库来发送HTTP请求。首先创建一个 `HttpPost` 对象并设置URL为目标URL。然后设置请求头,这里使用 `application/json` 表示请求体的类型为JSON格式。接下来创建一个 `StringEntity` 对象作为请求体,传入要发送JSON字符串和请求体的类型。然后将请求体设置到 `HttpPost` 对象中。 最后,通过调用 `httpClient.execute(httpPost)` 方法来发送请求并获取响应。如果响应实体不为空,则将其转为字符串并打印输出。最后记得关闭响应和 `HttpClient` 对象。 ### 回答2: Java发送HTTP请求并使用JSON格式进行POST请求的方法如下所示: 首先,我们需要通过URL和URLConnection对象建立HTTP连接。 ```java String url = "http://example.com/api/endpoint"; URL obj = new URL(url); HttpURLConnection con = (HttpURLConnection) obj.openConnection(); ``` 接下来,我们需要设置请求方法为POST,并设置请求头的Content-Type为application/json。 ```java con.setRequestMethod("POST"); con.setRequestProperty("Content-Type", "application/json"); ``` 然后,我们需要构建JSON数据并将其作为请求发送。 ```java String jsonBody = "{\"key1\":\"value1\",\"key2\":\"value2\"}"; con.setDoOutput(true); DataOutputStream wr = new DataOutputStream(con.getOutputStream()); wr.writeBytes(jsonBody); wr.flush(); wr.close(); ``` 最后,我们可以通过读取HTTP响应获取服务器返回的数据。 ```java int responseCode = con.getResponseCode(); BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream())); String inputLine; StringBuilder response = new StringBuilder(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); ``` 以上就是使用Java发送HTTP请求并使用JSON格式进行POST请求的基本过程。您可以根据实际情况进行适当的修改和扩展,例如添加请求头信息、处理错误响应等。 ### 回答3: 在Java中发送HTTP请求并且以JSON格式发送POST请求的步骤如下: 1. 导入相关类库:在代码中导入java.net包下的HttpURLConnection类和相关IO流类,以及org.json包中的JSON对象类。 2. 建立连接:使用URL类创建一个URL对象,将请求的URL作为参数传入。然后使用URL对象的openConnection()方法创建一个HttpURLConnection对象。 3. 设置请求属性:通过调用HttpURLConnection对象的setRequestMethod()方法,设置请求的方法为POST。同时通过setRequestProperty()方法设置请求头的Content-Type属性为application/json。 4. 打开连接:调用HttpURLConnection对象的connect()方法,建立与请求的URL的连接。 5. 创建JSON对象并写入数据:通过创建一个JSONObject对象,并且调用其put()方法向JSON对象中添加需要发送的数据。 6. 发送请求:通过调用HttpURLConnection对象的getOutputStream()方法获取输出流,将JSON对象转换为字符串,然后转换为字节数组,最后通过写入输出流发送请求。 7. 获取响应:通过调用HttpURLConnection对象的getResponseCode()方法获取响应码,判断请求是否成功。若成功,则通过调用getInputStream()方法获取输入流,然后通过IO流读取输入流中的数据。 8. 关闭连接:关闭输入流、输出流和连接。 完整的示例代码如下: ```java import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.URL; import org.json.JSONObject; public class HttpJsonPostExample { public static void main(String[] args) { try { // 创建URL对象 URL url = new URL("http://example.com/api"); // 替换为请求的URL // 创建HttpURLConnection对象 HttpURLConnection connection = (HttpURLConnection) url.openConnection(); // 设置请求属性 connection.setRequestMethod("POST"); connection.setRequestProperty("Content-Type", "application/json"); // 打开连接 connection.connect(); // 创建JSON对象 JSONObject jsonRequest = new JSONObject(); jsonRequest.put("key1", "value1"); jsonRequest.put("key2", "value2"); // 发送请求 OutputStream outputStream = connection.getOutputStream(); outputStream.write(jsonRequest.toString().getBytes()); outputStream.flush(); // 获取响应 int responseCode = connection.getResponseCode(); if (responseCode == HttpURLConnection.HTTP_OK) { BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); String line; StringBuilder response = new StringBuilder(); while ((line = reader.readLine()) != null) { response.append(line); } reader.close(); // 处理响应 JSONObject jsonResponse = new JSONObject(response.toString()); System.out.println(jsonResponse.toString()); } else { System.out.println("请求失败"); } // 关闭连接 connection.disconnect(); } catch (Exception e) { e.printStackTrace(); } } } ``` 这是一个基本的示例,只是通过调用println()方法打印出响应的JSON数据。实际应用中,你可以根据需求来处理响应数据。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

wuyongde0922

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值