13:31:08.016 [main] DEBUG o.a.h.c.protocol.RequestAddCookies - CookieSpec selected: best-match
13:31:08.027 [main] DEBUG o.a.h.c.protocol.RequestAuthCache - Auth cache not set in the context
13:31:08.034 [main] DEBUG o.a.h.i.c.PoolingHttpClientConnectionManager - Connection request: [route: {}->http://192.168.0.234:8080][total kept alive: 0; route allocated: 0 of 2; total allocated: 0 of 20]
13:31:08.047 [main] DEBUG o.a.h.i.c.PoolingHttpClientConnectionManager - Connection leased: [id: 0][route: {}->http://192.168.0.234:8080][total kept alive: 0; route allocated: 1 of 2; total allocated: 1 of 20]
13:31:08.052 [main] DEBUG o.a.h.impl.execchain.MainClientExec - Opening connection {}->http://192.168.0.234:8080
13:31:08.059 [main] DEBUG o.a.h.c.HttpClientConnectionManager - Connecting to /192.168.0.234:8080
13:31:08.061 [main] DEBUG o.a.h.impl.execchain.MainClientExec - Executing request POST /kaaAdmin/rest/api/sendNotification HTTP/1.1
13:31:08.061 [main] DEBUG o.a.h.impl.execchain.MainClientExec - Proxy auth state: UNCHALLENGED
13:31:08.063 [main] DEBUG org.apache.http.headers - http-outgoing-0 >> POST /kaaAdmin/rest/api/sendNotification HTTP/1.1
13:31:08.063 [main] DEBUG org.apache.http.headers - http-outgoing-0 >> Authorization: Basic U1AxMjY6MTIzNDU2
13:31:08.063 [main] DEBUG org.apache.http.headers - http-outgoing-0 >> Transfer-Encoding: chunked
13:31:08.063 [main] DEBUG org.apache.http.headers - http-outgoing-0 >> Content-Type: multipart/form-data; boundary=9ecNOzGYLogd2jWAkOgbw5GFboMpDvBxcr3
13:31:08.063 [main] DEBUG org.apache.http.headers - http-outgoing-0 >> Host: 192.168.0.234:8080
13:31:08.063 [main] DEBUG org.apache.http.headers - http-outgoing-0 >> Connection: Keep-Alive
13:31:08.063 [main] DEBUG org.apache.http.headers - http-outgoing-0 >> User-Agent: Apache-HttpClient/4.3.2 (java 1.5)
13:31:08.063 [main] DEBUG org.apache.http.headers - http-outgoing-0 >> Accept-Encoding: gzip,deflate
13:31:08.063 [main] DEBUG org.apache.http.wire - http-outgoing-0 >> "POST /kaaAdmin/rest/api/sendNotification HTTP/1.1[\r][\n]"
13:31:08.064 [main] DEBUG org.apache.http.wire - http-outgoing-0 >> "Authorization: Basic U1AxMjY6MTIzNDU2[\r][\n]"
13:31:08.064 [main] DEBUG org.apache.http.wire - http-outgoing-0 >> "Transfer-Encoding: chunked[\r][\n]"
13:31:08.064 [main] DEBUG org.apache.http.wire - http-outgoing-0 >> "Content-Type: multipart/form-data; boundary=9ecNOzGYLogd2jWAkOgbw5GFboMpDvBxcr3[\r][\n]"
13:31:08.064 [main] DEBUG org.apache.http.wire - http-outgoing-0 >> "Host: 192.168.0.234:8080[\r][\n]"
13:31:08.064 [main] DEBUG org.apache.http.wire - http-outgoing-0 >> "Connection: Keep-Alive[\r][\n]"
13:31:08.064 [main] DEBUG org.apache.http.wire - http-outgoing-0 >> "User-Agent: Apache-HttpClient/4.3.2 (java 1.5)[\r][\n]"
13:31:08.064 [main] DEBUG org.apache.http.wire - http-outgoing-0 >> "Accept-Encoding: gzip,deflate[\r][\n]"
13:31:08.064 [main] DEBUG org.apache.http.wire - http-outgoing-0 >> "[\r][\n]"
13:31:08.064 [main] DEBUG org.apache.http.wire - http-outgoing-0 >> "e6[\r][\n]"
13:31:08.064 [main] DEBUG org.apache.http.wire - http-outgoing-0 >> "--9ecNOzGYLogd2jWAkOgbw5GFboMpDvBxcr3[\r][\n]"
13:31:08.064 [main] DEBUG org.apache.http.wire - http-outgoing-0 >> "Content-Disposition: form-data; name="file"; filename="file"[\r][\n]"
13:31:08.064 [main] DEBUG org.apache.http.wire - http-outgoing-0 >> "Content-Type: application/json; charset=UTF-8[\r][\n]"
13:31:08.064 [main] DEBUG org.apache.http.wire - http-outgoing-0 >> "Content-Transfer-Encoding: binary[\r][\n]"
13:31:08.064 [main] DEBUG org.apache.http.wire - http-outgoing-0 >> "[\r][\n]"
13:31:08.064 [main] DEBUG org.apache.http.wire - http-outgoing-0 >> "{"message": "[0xe6][0xb5][0x8b][0xe8][0xaf][0x95][0xe4][0xb8][0x80][0xe4][0xb8][0x8b][0xe8][0xaf][0xb7][0xe6][0xb1][0x82][0xe5][0xa4][0xb4]?20190403"}[\r][\n]"
13:31:08.064 [main] DEBUG org.apache.http.wire - http-outgoing-0 >> "119[\r][\n]"
13:31:08.064 [main] DEBUG org.apache.http.wire - http-outgoing-0 >> "[\r][\n]"
13:31:08.064 [main] DEBUG org.apache.http.wire - http-outgoing-0 >> "--9ecNOzGYLogd2jWAkOgbw5GFboMpDvBxcr3[\r][\n]"
13:31:08.064 [main] DEBUG org.apache.http.wire - http-outgoing-0 >> "Content-Disposition: form-data; name="notification"; filename="notification"[\r][\n]"
13:31:08.064 [main] DEBUG org.apache.http.wire - http-outgoing-0 >> "Content-Type: application/json; charset=UTF-8[\r][\n]"
13:31:08.064 [main] DEBUG org.apache.http.wire - http-outgoing-0 >> "Content-Transfer-Encoding: binary[\r][\n]"
13:31:08.064 [main] DEBUG org.apache.http.wire - http-outgoing-0 >> "[\r][\n]"
13:31:08.064 [main] DEBUG org.apache.http.wire - http-outgoing-0 >> "{"applicationId":"196608","schemaId":"196615","topicId":"65536","type":"USER"}[\r][\n]"
13:31:08.064 [main] DEBUG org.apache.http.wire - http-outgoing-0 >> "2b[\r][\n]"
13:31:08.065 [main] DEBUG org.apache.http.wire - http-outgoing-0 >> "[\r][\n]"
13:31:08.065 [main] DEBUG org.apache.http.wire - http-outgoing-0 >> "--9ecNOzGYLogd2jWAkOgbw5GFboMpDvBxcr3--[\r][\n]"
13:31:08.065 [main] DEBUG org.apache.http.wire - http-outgoing-0 >> "[\r][\n]"
13:31:08.065 [main] DEBUG org.apache.http.wire - http-outgoing-0 >> "0[\r][\n]"
13:31:08.069 [main] DEBUG org.apache.http.wire - http-outgoing-0 >> "[\r][\n]"
13:31:08.191 [main] DEBUG org.apache.http.wire - http-outgoing-0 << "HTTP/1.1 200 OK[\r][\n]"
13:31:08.191 [main] DEBUG org.apache.http.wire - http-outgoing-0 << "Date: Wed, 03 Apr 2019 05:31:08 GMT[\r][\n]"
13:31:08.191 [main] DEBUG org.apache.http.wire - http-outgoing-0 << "Set-Cookie: JSESSIONID=yrpjuknz13hy18vjawn5fnm34;Path=/[\r][\n]"
13:31:08.191 [main] DEBUG org.apache.http.wire - http-outgoing-0 << "Expires: Thu, 01 Jan 1970 00:00:00 GMT[\r][\n]"
13:31:08.191 [main] DEBUG org.apache.http.wire - http-outgoing-0 << "Content-Type: application/json;charset=UTF-8[\r][\n]"
13:31:08.191 [main] DEBUG org.apache.http.wire - http-outgoing-0 << "Transfer-Encoding: chunked[\r][\n]"
13:31:08.191 [main] DEBUG org.apache.http.wire - http-outgoing-0 << "Server: Jetty(9.2.2.v20140723)[\r][\n]"
13:31:08.191 [main] DEBUG org.apache.http.wire - http-outgoing-0 << "[\r][\n]"
13:31:08.191 [main] DEBUG org.apache.http.wire - http-outgoing-0 << "12A[\r][\n]"
13:31:08.191 [main] DEBUG org.apache.http.wire - http-outgoing-0 << "{[\n]"
13:31:08.191 [main] DEBUG org.apache.http.wire - http-outgoing-0 << " "id" : "5ca4451c2bb8380a3e9d7dd7",[\n]"
13:31:08.191 [main] DEBUG org.apache.http.wire - http-outgoing-0 << " "applicationId" : "196608",[\n]"
13:31:08.191 [main] DEBUG org.apache.http.wire - http-outgoing-0 << " "schemaId" : "196615",[\n]"
13:31:08.191 [main] DEBUG org.apache.http.wire - http-outgoing-0 << " "topicId" : "65536",[\n]"
13:31:08.191 [main] DEBUG org.apache.http.wire - http-outgoing-0 << " "nfVersion" : 2,[\n]"
13:31:08.191 [main] DEBUG org.apache.http.wire - http-outgoing-0 << " "lastTimeModify" : 1554269468663,[\n]"
13:31:08.191 [main] DEBUG org.apache.http.wire - http-outgoing-0 << " "type" : "USER",[\n]"
13:31:08.191 [main] DEBUG org.apache.http.wire - http-outgoing-0 << " "body" : "POa1i+ivleS4gOS4i+ivt+axguWktD8yMDE5MDQwMw==",[\n]"
13:31:08.191 [main] DEBUG org.apache.http.wire - http-outgoing-0 << " "expiredAt" : 1554874268661,[\n]"
13:31:08.191 [main] DEBUG org.apache.http.wire - http-outgoing-0 << " "secNum" : 37[\n]"
13:31:08.191 [main] DEBUG org.apache.http.wire - http-outgoing-0 << "}"
13:31:08.194 [main] DEBUG org.apache.http.headers - http-outgoing-0 << HTTP/1.1 200 OK
13:31:08.194 [main] DEBUG org.apache.http.headers - http-outgoing-0 << Date: Wed, 03 Apr 2019 05:31:08 GMT
13:31:08.194 [main] DEBUG org.apache.http.headers - http-outgoing-0 << Set-Cookie: JSESSIONID=yrpjuknz13hy18vjawn5fnm34;Path=/
13:31:08.194 [main] DEBUG org.apache.http.headers - http-outgoing-0 << Expires: Thu, 01 Jan 1970 00:00:00 GMT
13:31:08.194 [main] DEBUG org.apache.http.headers - http-outgoing-0 << Content-Type: application/json;charset=UTF-8
13:31:08.194 [main] DEBUG org.apache.http.headers - http-outgoing-0 << Transfer-Encoding: chunked
13:31:08.194 [main] DEBUG org.apache.http.headers - http-outgoing-0 << Server: Jetty(9.2.2.v20140723)
13:31:08.198 [main] DEBUG o.a.h.impl.execchain.MainClientExec - Connection can be kept alive indefinitely
13:31:08.207 [main] DEBUG o.a.h.c.p.ResponseProcessCookies - Cookie accepted [JSESSIONID="yrpjuknz13hy18vjawn5fnm34", version:0, domain:192.168.0.234, path:/, expiry:null]
13:31:08.208 [main] DEBUG org.apache.http.wire - http-outgoing-0 << "[\r][\n]"
13:31:08.209 [main] DEBUG org.apache.http.wire - http-outgoing-0 << "0[\r][\n]"
13:31:08.211 [main] DEBUG org.apache.http.wire - http-outgoing-0 << "[\r][\n]"
13:31:08.212 [main] DEBUG o.a.h.i.c.PoolingHttpClientConnectionManager - Connection [id: 0][route: {}->http://192.168.0.234:8080] can be kept alive indefinitely
13:31:08.212 [main] DEBUG o.a.h.i.c.PoolingHttpClientConnectionManager - Connection released: [id: 0][route: {}->http://192.168.0.234:8080][total kept alive: 1; route allocated: 1 of 2; total allocated: 1 of 20]
{
"id" : "5ca4451c2bb8380a3e9d7dd7",
"applicationId" : "196608",
"schemaId" : "196615",
"topicId" : "65536",
"nfVersion" : 2,
"lastTimeModify" : 1554269468663,
"type" : "USER",
"body" : "POa1i+ivleS4gOS4i+ivt+axguWktD8yMDE5MDQwMw==",
"expiredAt" : 1554874268661,
"secNum" : 37
}
Process finished with exit code 0
字符串转文件流POST提交
package com.xx;
import org.apache.commons.codec.binary.Base64;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
/**
* request请求工具类
*/
public class HttpUtil {
private static HttpClient httpClient = HttpClients.createDefault();
@SuppressWarnings({"unchecked", "rawtypes"})
public synchronized static String doPost(String url,String authorization,String fileMessage,String notificationConfig) {
HttpPost httpPost;
String result = null;
try {
httpPost = new HttpPost(url);
// 设置参数
//httpPost.addHeader("Accept-Encoding", "application/json;charset=UTF-8");
//httpPost.setHeader("Content-Type","application/json;charset=UTF-8");
//"Basic U1AxMjY6MTIzNDU2"
httpPost.setHeader("Authorization","Basic "+authorization);
//上传file内容
InputStream file = new ByteArrayInputStream(fileMessage.getBytes("UTF-8"));
//上传notification内容
InputStream notification = new ByteArrayInputStream(notificationConfig.getBytes("UTF-8"));
MultipartEntityBuilder multipartBuilder = MultipartEntityBuilder
.create()
.addBinaryBody("file",file,ContentType.APPLICATION_JSON.withCharset("UTF-8"),"file")
.addBinaryBody("notification",notification,ContentType.APPLICATION_JSON.withCharset("UTF-8"),"notification");
httpPost.setEntity(multipartBuilder.build());
HttpResponse response = httpClient.execute(httpPost);
response.addHeader("Content-Type","application/json;charset=UTF-8");
if (response != null) {
HttpEntity resEntity = response.getEntity();
if (resEntity != null) {
result = EntityUtils.toString(resEntity, "utf-8");
}
}
} catch (Exception ex) {
ex.printStackTrace();
}
return result;
}
public static void main(String[] args) {
try {
String authString = "SP126:123456";
byte[] authEncBytes = Base64.encodeBase64(authString.getBytes("utf-8"));
String authorization = new String(authEncBytes);
System.out.println(authorization);
String url ="http://192.168.0.234:8080/kaaAdmin/rest/api/sendNotification";
String fileMessage="{\"message\": \"测试一下请求头?20190403\"}";
String notificationConfig = "{\"applicationId\":\"196608\",\"schemaId\":\"196615\",\"topicId\":\"65536\",\"type\":\"USER\"}";
String result =doPost(url,authorization,fileMessage,notificationConfig);
System.err.println(result);
} catch (Exception e) {
e.printStackTrace();
}
}
}
感兴趣的可以研究一下:
package com.xx;
import org.apache.commons.codec.binary.Base64;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.SocketTimeoutException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.UUID;
/**
* Created by crab on 2019/4/3.
*/
public class HttpPostUtil {
URL url;
HttpURLConnection conn;
String boundary = "-----"+ UUID.randomUUID().toString().replace("-","")+"--";
OutputStream ds;
private static final String urlStr = "http://192.168.0.234:8080/kaaAdmin/rest/api/sendNotification";
public HttpPostUtil(String url) throws Exception {
this.url = new URL(url);
}
/**
* 文件上传的connection的一些必须设置
*/
private void initConnection(String authorization) throws Exception {
conn = (HttpURLConnection) this.url.openConnection();
conn.setDoOutput(true);
conn.setUseCaches(false);
//连接超时为10秒
conn.setConnectTimeout(10000);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestProperty("Charsert", "UTF-8");
conn.setRequestProperty("Accept-Charset", "UTF-8");
conn.setRequestProperty("Authorization","Basic "+authorization);
}
/**
* 重新设置要请求的服务器地址,即上传文件的地址。
*/
public void setUrl(String url) throws Exception {
this.url = new URL(url);
}
/**
* 发送数据到服务器,返回一个字节包含服务器的返回结果的数组
*/
public String send(String authorization,String fileMessage,String notificationConfig) throws Exception {
initConnection(authorization);
try {
conn.connect();
} catch (SocketTimeoutException e) {
// something
throw new RuntimeException();
}
System.err.println("conn success!!");
ds = conn.getOutputStream();
System.err.println("writeFileParams success!!");
writeFileParams(fileMessage,notificationConfig);
paramsEnd();
System.err.println("write success!!");
String result ="";
try {
//System.err.println(ds.toString());
InputStream in = conn.getInputStream();
BufferedReader buf = new BufferedReader(new InputStreamReader(in));
for(String line = buf.readLine(); null != line;line = buf.readLine()){
result+=line;
}
conn.disconnect();
}catch (Exception ex){
ex.printStackTrace();
}
System.err.println("disconnect success!!");
return result;
}
/**
* 添加结尾数据
*/
private void paramsEnd() throws Exception {
ds.write(("--" + boundary + "--" + "\r\n").getBytes());
ds.write("\r\n".getBytes());
}
/**
* 对包含中文的字符串进行转码,此为UTF-8。服务器那边要进行一次解码
*/
private String encode(String value) throws Exception{
return URLEncoder.encode(value, "UTF-8");
}
//文件数据
private void writeFileParams(String fileMessage,String notificationConfig) throws Exception {
//写入文件流file
InputStream file = new ByteArrayInputStream(fileMessage.getBytes("UTF-8"));
//上传notification内容
InputStream notification = new ByteArrayInputStream(notificationConfig.getBytes("UTF-8"));
ds.write(("--" + boundary + "\r\n").getBytes());
ds.write("Content-Disposition: form-data; name=\"file\"; filename=\"file\"\r\n".getBytes());
ds.write("Content-Type: application/json; charset=UTF-8\r\n".getBytes());
ds.write("\r\n".getBytes());
byte[] b = new byte[200];
int len;
while(-1 != (len = file.read(b))){
ds.write(b,0,len);
}
ds.write("\r\n".getBytes());
ds.write("\r\n".getBytes());
//写入文件流file
ds.write(("--" + boundary + "\r\n").getBytes());
ds.write("Content-Disposition: form-data; name=\"notification\"; filename=\"notification\"\r\n".getBytes());
ds.write("Content-Type: application/json; charset=UTF-8\r\n".getBytes());
ds.write("\r\n".getBytes());
byte[] bytes = new byte[200];
int length;
while(-1 != (length = notification.read(bytes))){
ds.write(bytes,0,length);
}
ds.write("\r\n".getBytes());
}
public static void main(String[] args)throws Exception {
HttpPostUtil httpPostUtil = new HttpPostUtil(urlStr);
String authString = "SP126:123456";
byte[] authEncBytes = Base64.encodeBase64(authString.getBytes("utf-8"));
String authorization = new String(authEncBytes);
String fileMessage="{\"message\": \"最新一条消息201904031434\"}";
String notificationConfig = "{\"applicationId\":\"196608\",\"schemaId\":\"196615\",\"topicId\":\"65536\",\"type\":\"USER\"}";
String result = httpPostUtil.send(authorization,fileMessage,notificationConfig);
System.out.println(result);
}
}