Use Apache HttpClient to Post json data

时间:2023-03-08 19:14:20
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的