• Java 通过HttpClient Post方式提交json请求


    package com.sinosoft.ap.harmfullibrary.util;

    /**
    * 发送post请求
    */
    import net.sf.json.JSONObject;

    import java.io.IOException;

    import org.apache.http.HttpEntity;
    import org.apache.http.HttpResponse;
    import org.apache.http.client.ClientProtocolException;
    import org.apache.http.client.ResponseHandler;
    import org.apache.http.client.methods.HttpPost;
    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;

    public class HttpClientUtil {


    public static void post(JSONObject json, String url) {
    try {
    CloseableHttpClient httpclient = HttpClients.createDefault();
    System.out.println(json.toString());

    HttpPost httpPost = new HttpPost(url);
    httpPost.addHeader("Content-Type", "application/json;charset=UTF-8");

    // 解决中文乱码问题
    StringEntity stringEntity = new StringEntity(json.toString(), "UTF-8");
    stringEntity.setContentEncoding("UTF-8");

    httpPost.setEntity(stringEntity);

    System.out.println("Executing request " + httpPost.getRequestLine());

    ResponseHandler<String> responseHandler = new ResponseHandler<String>() {
    @Override
    public String handleResponse(final HttpResponse response)
    throws ClientProtocolException, IOException {//
    int status = response.getStatusLine().getStatusCode();
    if (status >= 200 && status < 300) {

    HttpEntity entity = response.getEntity();

    return entity != null ? EntityUtils.toString(entity) : null;
    } else {
    throw new ClientProtocolException(
    "Unexpected response status: " + status);
    }
    }
    };
    String responseBody = httpclient.execute(httpPost, responseHandler);
    System.out.println("----------------------------------------");
    System.out.println(responseBody);

    } catch (Exception e) {
    System.out.println(e);
    }


    }

    public static void main(String[] args) {
    JSONObject obj = new JSONObject();
    obj.put("UpdateCode", "update");
    obj.put("harmful_info_id", "014e79cb198579840a504c89cb17c10f");
    obj.put("harmful_info_desc", "新疆&暴");
    post(obj, "http://10.10.40.3:5002/updateKeywordRules");
    }
    }

  • 相关阅读:
    YII框架学习(二)
    YII框架学习(一)
    valid number 判断字符串是否为有效数字
    leetcode Add Binary
    leetcode Minimum Path Sum
    leetcode Unique Paths II
    leetcode[61] Unique Paths
    leetcode[60] Rotate List
    leetcode Permutation Sequence
    leetcode Spiral Matrix II
  • 原文地址:https://www.cnblogs.com/dalianmao890710/p/7412846.html
Copyright © 2020-2023  润新知