java 发送数据请求数据_java 发送http get/post请求,并利用解析返回的数据

形容一下业务需求,然后记录方法。

业务需求:

需要向某个固定的URL发送一个带参数的HTTP请求。并解析返回的XML数据,取到有用数据。

例如:

我要向http://111.12.1.2/MWBusinessModel/xmlrpc发送一个含有参数user=test的请求后,会返回如下xml,

class="xml" name="code"><?xml version="1.0" encoding="UTF-8"?>

?

想获取"F13D6E31-6687-49F1-9695-A582775B199A"的值。

?

代码:

/**

* 取得Content

*

* @param param 需要向请求中传的参数

* @return

*/

public String getContent(String param) {

private static final String XML_RPC_URL = "http://111.2.35.5/MWBusinessModel/xmlrpc";

String xmlResp = null;

try {

xmlResp = hc.doPost(XML_RPC_URL, param);

} catch (ClientProtocolException e) {

logger.error("", e);

} catch (IOException e) {

logger.error("", e);

}

Document doc = null;

try {

//获得document

doc = DocumentHelper.parseText(xmlResp);

} catch (DocumentException e) {

logger.error("", e);

}

Element methodResponseNode = doc.getRootElement();

Element faultNode = methodResponseNode.element("fault");

if (faultNode != null) {

return null;

}

//获取params节点下param节点下的value的值(这种方法自动去掉

Element paramsNode = methodResponseNode.element("params");

Element paramNode = paramsNode.element("param");

Element valueNode = paramNode.element("value");

return valueNode.getText();

}

?

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Java发送post请求到CSDN的过程需要先引入所需的类库和完成相关配置,然后通过Java代码实现发送数据的过程。 第一步,引入相关类库。需要引入JavaHttpURLConnection类和URL类等相关的类库。 第二步,设置连接并发送请求,这里以通过API接口发表评论为例: URL url = new URL("http://write.blog.csdn.net/comment/addComment"); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("POST"); conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); conn.setDoOutput(true); conn.setDoInput(true); 第三步,设置请求参数并发送请求: Map<String, String> params = new HashMap<>(); params.put("article_id", "123456"); params.put("content", "这是一条评论"); StringBuilder stringBuilder = new StringBuilder(); for (Map.Entry<String, String> entry : params.entrySet()) { stringBuilder.append(entry.getKey()); stringBuilder.append("="); stringBuilder.append(entry.getValue()); stringBuilder.append("&"); } byte[] postDataBytes = stringBuilder.toString().getBytes("UTF-8"); OutputStream outputStream = conn.getOutputStream(); outputStream.write(postDataBytes); outputStream.flush(); outputStream.close(); 第四步,处理请求结果。这里需要根据API文档解析返回数据。 BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream())); String inputLine; StringBuilder response = new StringBuilder(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); System.out.println("Response: " + response.toString()); 以上就是使用Java实现向CSDN发送POST请求的过程,在实际使用过程中,需要注意一些细节问题,如API地址和请求参数等。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值