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");
    }
    }

  • 相关阅读:
    Vim直接打开Tampermonkey网址的方法。
    利用 Tampermonkey 和 Surfingkeys 效率操作网页
    tampermonkey利用@require调用本地脚本的方法
    用AutoHotkey一键完成Xmind插入图片等功能
    用AutoHotkey调整Windows音量
    用AutoHotkey重置Excel的Ctrl+Alt+方向键选择的范围
    远程终端协议TELNET
    文件传送协议
    域名系统DNS
    计算机网络运输层习题5-38
  • 原文地址:https://www.cnblogs.com/dalianmao890710/p/7412846.html
Copyright © 2011-2022 走看看