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的

时间: 2024-12-30 00:25:01

Use Apache HttpClient to Post json data的相关文章

使用Apache HttpClient 4.x发送Json数据

Apache HttpClient是Apache提供的一个开源组件,使用HttpClient可以很方便地进行Http请求的调用.自4.1版本开始,HttpClient的API发生了较大的改变,很多方法的调用方式已经和3.x版本不同.本文使用的是当前最新的4.5.3版本. 首先在pom文件中引入httpcomponents依赖包: 1 <dependency> 2 <groupId>org.apache.httpcomponents</groupId> 3 <art

android通过HttpClient与服务器JSON交互

通过昨天对HttpClient的学习,今天封装了HttpClient类 代码如下: package com.tp.soft.util; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.List; import java.util.Map; import org.apach

Apache HttpClient : Http Cookies

前言 HttpClient已经被集成到Android的SDK里,但在JDK里面仍然需要HttpURLConnectionn发起HTTP请求.HttpClient可以看做是一个加强版的HttpURLConnection,但它的侧重点是如何发送请求.接受相应和管理Http连接. 在介绍Http Cookies之前,笔者给出一个应用场景:你需要一个根据地理信息(城市名或者经纬度)获取天气的应用.可选的API很多,不幸的是,网上提到的Google天气API已经停止服务了(不是被墙):雅虎是英文的,且需要

android使用apache httpclient发送post请求

package com.liuc; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.List; import java.util.Map; import org.apache.ht

Apache HttpClient访问网络工具类

1 package com.ztravel.utils; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Map; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; import org

Android 6.0 使用 Apache HttpClient

Android 6.0版本已经已经基本将Apahce Http Client 移除出SDK. 那么问题来了,如果我在以前的项目中使用了Apache HttpClient相关类,怎么办呢? 请看官网给出的答案 Apache HTTP Client Removal Android 6.0 release removes support for the Apache HTTP client. If your app is using this client and targets Android 2.

JSON进阶第三篇 apache多域名及JSON的跨域问题(JSONP)

本文先介绍如何为apache配置多域名,然后再用JSONP(JSON with Padding)来解决JSON的跨域问题. 阅读本文之前,推荐先参阅<JSON进阶第二篇AJAX方式传递JSON数据>. 一.apache配置多域名 在apache的conf目录下找到httpd.conf,然后在该文件最后增加如下内容: # 声明使用虚拟主机过滤规则 NameVirtualHost*:80 #虚拟主机localhost <VirtualHost*:80> ServerName  loca

android通过httpClient请求获取JSON数据并且解析

android通过httpClient请求获取JSON数据并且解析:http://www.cnblogs.com/gzggyy/archive/2013/05/08/3066288.html Android--使用Http向服务器发送请求并取得返回结果,下载图片:http://www.2cto.com/kf/201307/229489.html Android系列之网络(一)----使用HttpClient发送HTTP请求(通过get方法获取数据):http://blog.csdn.net/he

Google Volley: How to send a POST request with Json data?

sonObjectRequest actuallyaccepts JSONObject as body. From http://arnab.ch/blog/2013/08/asynchronous-http-requests-in-android-using-volley/ final String url = "some/url"; final JSONObject jsonBody = /* ... */; new JsonObjectRequest(url, jsonBody,