java 调用http接口传json
时间: 2024-10-23 22:12:15 浏览: 26
在Java中调用HTTP接口传JSON数据可以使用Apache HttpComponents组件中的HttpClient类,可以通过HttpPost方法发送JSON数据。具体步骤如下:
1. 创建HttpClient对象;
2. 创建HttpPost对象,并设置请求的URL;
3. 设置请求头信息;
4. 创建JSON对象,并转换成字符串;
5. 将JSON字符串设置到请求实体中;
6. 执行请求,并获取响应结果;
7. 解析响应结果并处理。
下面是一个示例代码:
```
import java.io.IOException;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;
public class HttpTest {
public static void main(String[] args) throws Exception {
reqHttpUrl();
}
public static void reqHttpUrl() throws JSONException{
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("http://192.168.1.1");
//设置请求头信息
httpPost.setHeader("Content-Type", "application/json;charset=UTF-8");
//创建JSON对象并转换成字符串
JSONObject json = new JSONObject();
json.put("MOBILENUM", "13444544444");
StringEntity entity = new StringEntity(json.toString(), "UTF-8");
//将JSON字符串设置到请求实体中
httpPost.setEntity(entity);
//执行请求并获取响应结果
HttpResponse response = httpClient.execute(httpPost);
String result = EntityUtils.toString(response.getEntity(), "UTF-8");
//解析响应结果并处理
JSONObject resultJson = new JSONObject(result);
String rtnCode = resultJson.getJSONObject("head").getString("rtnCode");
if("000000".equals(rtnCode)){
System.out.println("请求成功!");
}else{
System.out.println("请求失败!");
}
}
}
```
--相关问题--:
阅读全文