http post请求

package com.http.https;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class HttpPost {
	public static void main(String[] arg)
	{
	String httpUrl = "http://apis.baidu.com/idl_baidu/faceverifyservice/face_deleteuser";
	String httpArg = "{\"params\": [{\"username\":\"test\",\"cmdid\":\"1000\",\"logid\": \"12345\",\"appid\": \"034da992caf945858883f7ca01017c04\",\"clientip\":\"10.23.34.5\",\"type\":\"st_groupverify\",\"groupid\": \"0\",\"versionnum\": \"1.0.0.1\",}],\"jsonrpc\": \"2.0\",\"method\": \"Delete\",\"id\":12}";
	String jsonResult = request(httpUrl, httpArg);
	System.out.println(jsonResult);
	}

	/**
	 * @param urlAll
	 *            :请求接口
	 * @param httpArg
	 *            :参数
	 * @return 返回结果
	 */
	public static String request(String httpUrl, String httpArg) {
	    BufferedReader reader = null;
	    String result = null;
	    StringBuffer sbf = new StringBuffer();

	    try {
	        URL url = new URL(httpUrl);
	        HttpURLConnection connection = (HttpURLConnection) url
	                .openConnection();
	        //设置请求方式
	        connection.setRequestMethod("POST");
	        connection.setRequestProperty("Content-Type",
	                        "application/x-www-form-urlencoded");
	      //setRequestProperty()往http请求头增加参数(根据接口需要,此处需要增加apikey)
	        connection.setRequestProperty("apikey",  "您自己的apikey");
	        connection.setDoOutput(true);
	        
	        //此处有两个功能:(1)打开connection,相当于connection.connect();(2)建立输出流
	        //connection.connect()后,再设置connection已经没有用了
	        OutputStream op = connection.getOutputStream();
	        ObjectOutputStream oop = new ObjectOutputStream(op);
	        Person person = new Person();
	        person.setage("15");
	        person.setname("xiexie");
	        oop.writeObject(person);
	        //不能再写入数据,但是此时还并没有将请求发送过去
	        oop.flush();
	        connection.getOutputStream().write(httpArg.getBytes("UTF-8"));
	        connection.connect();
	        //此处才是真的将数据传输过去了
	        InputStream is = connection.getInputStream();
	        reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
	        String strRead = null;
	        while ((strRead = reader.readLine()) != null) {
	            sbf.append(strRead);
	            sbf.append("\r\n");
	        }
	        reader.close();
	        result = sbf.toString();
	    } catch (Exception e) {
	        e.printStackTrace();
	    }
	    return result;
	}
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值