下面是发送代码的方法,目前使用的是jdk1.8测试的
需要jar包:commons-httpclient-3.0.1.jar

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.PostMethod;


public class Http {
	
	 /**
     * 
     * @param u url地址
     * @param param 跟在?后面的参数  格式如下:
     *  String content = "access_token=" + URLEncoder.encode(access_token, "gbk")
		 + "&image=" + URLEncoder.encode(image, "gbk");
     * @return
     */
      public static String sendPost2(String u, String param) {
            StringBuffer sbf = new StringBuffer();
            try {
                URL url = new URL(u);
                HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                connection.setDoInput(true);
                connection.setDoOutput(true);
                connection.setRequestMethod("POST");
                connection.setUseCaches(false);
                connection.setInstanceFollowRedirects(true);
               // connection.addRequestProperty("role", "Admin");
                connection.addRequestProperty("Content-Type", "application/x-www-form-urlencoded");
                connection.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
                connection.connect();
                DataOutputStream out = new DataOutputStream(connection.getOutputStream());
                if (!"".equals(param)) {
                     // 正文,正文内容其实跟get的URL中 '? '后的参数字符串一致
                  //  String content = "字段名=" + URLEncoder.encode("字符串值", "编码");
                	
                    out.writeBytes(param);
                }
                out.flush();
                out.close();

                BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                String lines;
                while ((lines = reader.readLine()) != null) {
                    lines = new String(lines.getBytes(), "utf-8");
                    sbf.append(lines);
                }
                System.out.println(sbf);
                reader.close();
                // 断开连接
                connection.disconnect();
            } catch (MalformedURLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            return sbf.toString();
        }
     /**
     * 发送http POST请求
     *
     * @param
     * @return 远程响应结果
     */
    public static String sendPost(String u, String json) {
        StringBuffer sbf = new StringBuffer();
        try {
            URL url = new URL(u);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setDoInput(true);
            connection.setDoOutput(true);
            connection.setRequestMethod("POST");
            connection.setUseCaches(false);
            connection.setInstanceFollowRedirects(true);
            connection.addRequestProperty("role", "Admin");
            connection.addRequestProperty("Content-Type", "application/json");
            connection.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
            connection.connect();
            DataOutputStream out = new DataOutputStream(connection.getOutputStream());
            if (!"".equals(json)) {
                out.writeBytes(json);
            }
            out.flush();
            out.close();

            BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String lines;
            while ((lines = reader.readLine()) != null) {
                lines = new String(lines.getBytes(), "utf-8");
                sbf.append(lines);
            }
            System.out.println(sbf);
            reader.close();
            // 断开连接
            connection.disconnect();
        } catch (MalformedURLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return sbf.toString();
    }

    public static String sendPostjason(String url, String xml) {

        // File input = new File("test.xml");//如果是xml文件,可以这样写
        PostMethod post = new PostMethod(url);// 请求地址

        // 设置请求的内容直接从文件中读取
        // post.setRequestBody( new FileInputStream(input));
        // if (input.length() < Integer.MAX_VALUE)
        // post.setRequestContentLength(input.length());
        // else
        // post.setRequestContentLength(EntityEnclosingMethod.CONTENT_LENGTH_CHUNKED);

        post.setRequestBody(xml);// 这里添加xml字符串

        // 指定请求内容的类型
        post.setRequestHeader("Content-type", "application/json; charset=UTF-8");
        post.setRequestHeader("role", "Admin");

        HttpClient httpclient = new HttpClient();// 创建 HttpClient 的实例
        int result;
        try {
            result = httpclient.executeMethod(post);
            System.out.println("Response status code: " + result);// 返回200为成功
            System.out.println("Response body: ");
            return post.getResponseBodyAsString();// 返回的内容
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }

    public static String sendGet(String u, String json) {
        StringBuffer sbf = new StringBuffer();
        try {
            URL url = new URL(u);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.addRequestProperty("role", "Admin");
            connection.addRequestProperty("Content-Type", "application/json");

            BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String lines;
            while ((lines = reader.readLine()) != null) {
                lines = new String(lines.getBytes(), "utf-8");
                sbf.append(lines);
            }
            System.out.println(sbf);
            reader.close();
            // 断开连接
            connection.disconnect();
        } catch (MalformedURLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return sbf.toString();
    }

  /**
     * 能解决中文编码问题
     * @param uri
     * @param data
     * @return
     */
    public static String sendPost(String uri,Map<String, Object> data) {
        try {
            URL url = new URL(uri);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();

            connection.setDoInput(true); // 设置可输入
            connection.setDoOutput(true); // 设置该连接是可以输出的
            connection.setRequestMethod("POST"); // 设置请求方式
            connection.setRequestProperty("Content-Type", "application/json;charset=UTF-8");

            ObjectMapper objectMapper = new ObjectMapper();

            PrintWriter pw = new PrintWriter(new BufferedOutputStream(connection.getOutputStream()));
            pw.write(objectMapper.writeValueAsString(data));
            pw.flush();
            pw.close();

            BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream(), "utf-8"));
            String line = null;
            StringBuilder result = new StringBuilder();
            while ((line = br.readLine()) != null) { // 读取数据
                result.append(line + "\n");
            }
            connection.disconnect();

           return  result.toString();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 解决编码问题
     * @param uri
     * @param data
     */
    public void sendGet2(String uri,String data) {
        try {
            URL url = new URL(uri);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();

            connection.setDoInput(true); // 设置可输入
            connection.setDoOutput(true); // 设置该连接是可以输出的
            connection.setRequestMethod("POST"); // 设置请求方式
            connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");

            PrintWriter pw = new PrintWriter(new BufferedOutputStream(connection.getOutputStream()));
            pw.write(data);
            pw.flush();
            pw.close();

            BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream(), "utf-8"));
            String line = null;
            StringBuilder result = new StringBuilder();
            while ((line = br.readLine()) != null) { // 读取数据
                result.append(line + "\n");
            }
            connection.disconnect();

            System.out.println(result.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}

GitHub 加速计划 / js / json
41.72 K
6.61 K
下载
适用于现代 C++ 的 JSON。
最近提交(Master分支:1 个月前 )
960b763e 4 个月前
8c391e04 6 个月前
Logo

旨在为数千万中国开发者提供一个无缝且高效的云端环境,以支持学习、使用和贡献开源项目。

更多推荐