import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import net.sf.json.JSONObject;
public class HttpUtils {
public static void appadd(String ADD_URL,JSONObject josnObj) {
try {
URL url = new URL(ADD_URL);
HttpURLConnection connection = (HttpURLConnection) url
.openConnection();
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setRequestMethod("POST");
connection.setUseCaches(false);
connection.setInstanceFollowRedirects(true);
connection.setRequestProperty("connection", "Keep-Alive");
connection.setRequestProperty("Content-Type", "text/plain; charset=utf-8");
connection.setRequestProperty("Accept-Charset", "utf-8");
connection.setRequestProperty("contentType", "utf-8");
connection.connect();
//POST请求
DataOutputStream out = new DataOutputStream(
connection.getOutputStream());
out.write(josnObj.toString().getBytes("UTF-8"));
System.out.println("data=="+josnObj.toString());
out.flush();
out.close();
//读取响应
BufferedReader reader = new BufferedReader(new InputStreamReader(
connection.getInputStream()));
String lines;
StringBuffer sb = new StringBuffer("");
while ((lines = reader.readLine()) != null) {
lines = new String(lines.getBytes(), "utf-8");
sb.append(lines);
}
System.out.println(sb.toString());
reader.close();
connection.disconnect();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
测试代码
import net.sf.json.JSONObject;
public class Test(){
public static void main(String[] args) {
JSONObject josnObj = new JSONObject();
josnObj.put("type", "bb");
josnObj.put("name", "aa");
HttpUtils.appadd("http://127.0.0.1:8080/test", josnObj);
}
}