import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.entity.StringEntity;
import java.nio.charset.Charset;
public class APITest {
private static HttpClient httpClient = null;
private static HttpPost method = null;
private static String url = "http://localhost:80/api/do";
public APITest() {
httpClient = new DefaultHttpClient();
method = new HttpPost(url);
}
public static void main(String[] args) {
try {
JSONObject jsonObjectSend = new JSONObject();
JSONObject bodyJsonObject = new JSONObject();
JSONArray jsonArray = new JSONArray();
httpClient = new DefaultHttpClient();
method = new HttpPost(url);
String[] devices = {"123","234"};
bodyJsonObject.put("message", "test");
bodyJsonObject.put("devices", devices);
jsonArray.put(0,bodyJsonObject);
jsonObjectSend.put("body", jsonArray);
String sendstr = jsonObjectSend.toString();
method.addHeader("Content-type","application/json; charset=utf-8");
method.setEntity(new StringEntity(sendstr, Charset.forName("UTF-8")));
httpClient.execute(method);
return;
} catch (Exception e) {
System.out.println("error....");
System.out.println(e.toString());
System.out.println("--------------------");
System.out.println(e.getMessage());
System.out.println("--------------------");
e.printStackTrace();
return;
}
}
}
java发送json请求
最新推荐文章于 2023-06-15 18:04:44 发布