import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
/**
* POST发送工具类
*/
public class PostJson {
public static int postJson(String serverUrl,String jsonStr,String userId){
try {
// 创建url资源
URL url = new URL(serverUrl);
// 建立http连接
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
// 设置允许输出
conn.setDoOutput(true);
conn.setDoInput(true);
// 设置不用缓存
conn.setUseCaches(false);
// 设置传递方式
conn.setRequestMethod("POST");
// 设置维持长连接
conn.setRequestProperty("Connection", "Keep-Alive");
// 设置文件字符集:
conn.setRequestProperty("Charset", "UTF-8");
// 转换为字节数组
byte[] data = (jsonStr.toString()).getBytes();
// 设置文件长度
conn.setRequestProperty("Content-Length",
String.valueOf(data.length));
// 设置文件类型:
conn.setRequestProperty("contentType", "application/json");
conn.setRequestProperty("Cookie", "datacenter_userId="+userId);
// 开始连接请求
conn.connect();
OutputStream out = conn.getOutputStream();
// 写入请求的字符串
out.write((jsonStr.toString()).getBytes());
out.flush();
out.close();
// 请求返回的状态
if (conn.getResponseCode() == 200) {
return 1;
} else if(conn.getResponseCode() == 401){
return 2;
}else{
return 0;
}
} catch (Exception e) {
e.printStackTrace();
}
return 0;
}
}
import java.net.HttpURLConnection;
import java.net.URL;
/**
* POST发送工具类
*/
public class PostJson {
public static int postJson(String serverUrl,String jsonStr,String userId){
try {
// 创建url资源
URL url = new URL(serverUrl);
// 建立http连接
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
// 设置允许输出
conn.setDoOutput(true);
conn.setDoInput(true);
// 设置不用缓存
conn.setUseCaches(false);
// 设置传递方式
conn.setRequestMethod("POST");
// 设置维持长连接
conn.setRequestProperty("Connection", "Keep-Alive");
// 设置文件字符集:
conn.setRequestProperty("Charset", "UTF-8");
// 转换为字节数组
byte[] data = (jsonStr.toString()).getBytes();
// 设置文件长度
conn.setRequestProperty("Content-Length",
String.valueOf(data.length));
// 设置文件类型:
conn.setRequestProperty("contentType", "application/json");
conn.setRequestProperty("Cookie", "datacenter_userId="+userId);
// 开始连接请求
conn.connect();
OutputStream out = conn.getOutputStream();
// 写入请求的字符串
out.write((jsonStr.toString()).getBytes());
out.flush();
out.close();
// 请求返回的状态
if (conn.getResponseCode() == 200) {
return 1;
} else if(conn.getResponseCode() == 401){
return 2;
}else{
return 0;
}
} catch (Exception e) {
e.printStackTrace();
}
return 0;
}
}