码迷,mamicode.com
首页 > Web开发 > 详细

Use Apache HttpClient to Post json data

时间:2016-06-23 11:01:38      阅读:189      评论:0      收藏:0      [点我收藏+]

标签:

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

标签:

原文地址:http://www.cnblogs.com/tomcatandjerry/p/5609876.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!