http发送post请求带json参数

自己改一下url,这里没有main,创建这个类使用post方法而已,需要导入httpclient相关jar包

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import org.apache.http.util.TextUtils;
import sun.rmi.runtime.Log;
import com.google.gson.Gson;
import ceb.gz.BaoGuanDan.Baoguangdan;
import ceb.gz.BaoGuanDan.Data;
public class BGDrequest{
  String url = "***";
 
    public static String post(String strURL, String params) { 
        System.out.println(strURL); 
        System.out.println(params);
        String result = "";
        BufferedReader reader = null;
        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(); 
            if (params != null && !TextUtils.isEmpty(params)) {
                byte[] writebytes = params.getBytes();
                // 设置文件长度
             //   connection.setRequestProperty("Content-Length", String.valueOf(writebytes.length));
                OutputStream outwritestream = connection.getOutputStream();
                outwritestream.write(params.getBytes());
                outwritestream.flush();
                outwritestream.close();
               // Log.d("hlhupload", "doJsonPost: conn"+connection.getResponseCode());
            }
            if (connection.getResponseCode() == 200) {
                reader = new BufferedReader(
                        new InputStreamReader(connection.getInputStream()));
                result = reader.readLine();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return result;
    } 
 
}
  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值