- 转自:http://zheyiw.iteye.com/blog/1571222
- import java.io.IOException;
- import java.io.InputStream;
- import java.io.OutputStreamWriter;
- import java.net.HttpURLConnection;
- import java.net.URL;
-
- public class Copy_2_of_PostDemo {
-
- final static String url = "";
- final static String params = "{\"id\":\"12345\"}";
-
-
-
-
-
-
-
-
-
-
- public static String post(String strURL, String params) {
- System.out.println(strURL);
- System.out.println(params);
- try {
- URL url = new URL(strURL);
- HttpURLConnection connection = (HttpURLConnection) url
- .openConnection();
- connection.setDoOutput(true);
- connection.setDoInput(true);
- connection.setUseCaches(false);
- connection.setInstanceFollowRedirects(true);
- connection.setRequestMethod("POST");
- connection.setRequestProperty("Accept", "application/json");
- connection.setRequestProperty("Content-Type", "application/json");
- connection.connect();
- OutputStreamWriter out = new OutputStreamWriter(
- connection.getOutputStream(), "UTF-8");
- out.append(params);
- out.flush();
- out.close();
-
- int length = (int) connection.getContentLength();
- InputStream is = connection.getInputStream();
- if (length != -1) {
- byte[] data = new byte[length];
- byte[] temp = new byte[512];
- int readLen = 0;
- int destPos = 0;
- while ((readLen = is.read(temp)) > 0) {
- System.arraycopy(temp, 0, data, destPos, readLen);
- destPos += readLen;
- }
- String result = new String(data, "UTF-8");
- System.out.println(result);
- return result;
- }
- } catch (IOException e) {
-
- e.printStackTrace();
- }
- return "error";
- }
-
- public static void main(String[] args) {
- post(url, params);
- }
-
- }