zoukankan      html  css  js  c++  java
  • 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");
    }
    }

  • 相关阅读:
    Java反射
    安装python
    查看网页加载速度,并优化
    模型按一个圈摆放(10等分)
    y = n*x 匀速,变速运动
    物体绕圆形做圆周运动
    three.js 相机跟随鼠标移动
    three.js 物体随鼠标移动
    three.js 画正多边形-线性
    ES6的JavaScript数据结构实现之队列
  • 原文地址:https://www.cnblogs.com/dalianmao890710/p/7412846.html
Copyright © 2011-2022 走看看