Use Apache HttpClient to Post json data

Posted tomcat and jerry

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Use Apache HttpClient to Post json data相关的知识,希望对你有一定的参考价值。

import org.apache.commons.io.IOUtils;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicHeader;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;

import com.alibaba.fastjson.JSONObject;


InputStream is = null; ByteArrayOutputStream bout = null; try { URIBuilder uriBuilder = new URIBuilder(envTO.getSocketApiURL()); HttpPost httpPost = new HttpPost(uriBuilder.build()); //httpPost.setHeader("Accept", "application/json");//经测,该参数可有可无 httpPost.setHeader("Content-type", "application/json");//必须要制定该参数 HttpClient httpClient = HttpClientBuilder.create().build(); JSONObject json = new JSONObject(); json.put("channel", channel); json.put("action", action); json.put("data", dataParm==null?new JSONObject():dataParm); StringEntity s = new StringEntity(json.toString(),HTTP.UTF_8); //s.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));//经测,该参数可有可无 httpPost.setEntity(s); HttpResponse httpResponse = httpClient.execute(httpPost); is = httpResponse.getEntity().getContent(); byte[] data = new byte[1024]; int length = 0; bout = new ByteArrayOutputStream(); while((length=is.read(data))!=-1){ bout.write(data,0,length); } String result = new String(bout.toByteArray(),"UTF-8"); logger.info("sendNotice2SocketServer(): result is "+result); } catch (URISyntaxException e1) { logger.error("getAllMembers4Lucky(): IOException e1", e1); } catch (UnsupportedOperationException e) { logger.error("getAllMembers4Lucky(): UnsupportedOperationException e", e); } catch (IOException e) { logger.error("getAllMembers4Lucky(): IOException e", e); } finally{ if(bout!=null){ IOUtils.closeQuietly(bout); } if(is!=null){ IOUtils.closeQuietly(is); } }

后台可以用SpringMVC做一个restful的api(自行bing搜索如何构建一个restful API. PS:推荐一个异常简单的框架: Spark

---------------------------------------------------------------

另外发现一个以上代码无法正确提交到node.js的服务(一直404-Bad request,不知是哪里的问题,求解)

于是找了另一个提交的方法:

public static String postJson2Socket(String url, String jsonString, boolean isGet, boolean isJson){
    HttpURLConnection conn = null;
    OutputStream os = null;
    InputStream is = null;
    BufferedReader br = null;
    try{
        if (isGet) {
            if (jsonString == null) {
                conn = (HttpURLConnection) new URL(url).openConnection();
            } else {
                conn = (HttpURLConnection) new URL(url + "?" + jsonString).openConnection();
            }
            conn.setDoOutput(false);
            conn.setConnectTimeout(20000);
            conn.setReadTimeout(20000);
            // conn.setUseCaches(true);
            conn.setRequestProperty("Accept", "application/json,text/html");
            conn.setRequestProperty("Content-Type", "application/json");
        } else {
            conn = (HttpURLConnection) new URL(url).openConnection();
            conn.setDoOutput(true);
            conn.setReadTimeout(10000);
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Content-Type", isJson ? "application/json" : "application/x-www-form-urlencoded");
            os = conn.getOutputStream();
            os.write(jsonString.getBytes("UTF-8"));
            os.flush();
        }
        is = conn.getInputStream();
        br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
        StringBuffer sb = new StringBuffer();
        String line;
        while ((line = br.readLine()) != null) {
            sb.append(line).append("\n");
        }
        br.close();
        is.close();
        conn.disconnect();
        return sb.toString();
    }
    catch(Exception e){
        logger.error(e);
        return "";
    }
    finally{
        IOUtils.closeQuietly(os);
        IOUtils.closeQuietly(br);
        IOUtils.closeQuietly(is);
        if(conn!=null){
            conn.disconnect();
        }
    }
}

该方法是可以成功提交给nodejs的

 

以上是关于Use Apache HttpClient to Post json data的主要内容,如果未能解决你的问题,请参考以下文章

Linux 启动 Apache 时报错:(98)Address already in use: make_sock: could not bind to address [::]:80

apache启动报错(98)Address already in use: make_sock: could not bind to address [::]:80

(98)Address already in use: make_sock: could not bind to address 0.0.0.0:80

httpclient请求返回响应体,报警告"Going to buffer response body of large or unknown size"的解决方案

Xampp error:Port 80 in use by "Unable to open process" with PID 4

异常:Unsupported major.minor version 52.0 (Use --stacktrace to see the full trace)