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;
}
}
http post请求
最新推荐文章于 2023-06-09 15:27:42 发布