java 如何实现HTTP接口

接口地址为:http://services/WMMOAService?sname=?&transid=?&msgbody=?
我应该如何实现,通过servlet 返回一个XML文件,本人刚接触,请赐教!

3个回答

很简单的 直接封装然后读取xml串进行遍历,下边的方法是返回xml串

package com.mdcl.discuz;

import java.io.IOException;
import java.io.OutputStream;

public class GetWebTopGroup {

public static void main(String[] args) throws IOException {
    String sCurrentLine = "";
    java.net.URL l_url = null;
    java.net.HttpURLConnection l_connection = null;
    java.io.BufferedReader l_reader = null;
    java.io.InputStream l_urlStream = null;
    try {
        l_url = new java.net.URL(
                "http://www.bbs.com:8080/DMAdapter/servlet/GetGroupSevlet");
        l_connection = (java.net.HttpURLConnection) l_url.openConnection();
        l_connection.setDoInput(true);
        l_connection.setDoOutput(true);
        l_connection.setUseCaches(false);
        l_connection.setRequestMethod("POST");
        l_connection.setRequestProperty("User-Agent",
                "Mozilla/4.7 (ShowSky)");
        OutputStream os = l_connection.getOutputStream();
        os.write(getString().getBytes("UTF-8"));
        os.close();
        l_connection.connect();
        int res = l_connection.getResponseCode();
        // System.out.println("ResponseCode:200");
        if (res == 200) {
            l_urlStream = l_connection.getInputStream();
            l_reader = new java.io.BufferedReader(
                    new java.io.InputStreamReader(l_urlStream));
            while ((sCurrentLine = l_reader.readLine()) != null) {
                if (!sCurrentLine.trim().equals("")) {
                    System.out.println(sCurrentLine);
                }
            }
        }
    } catch (Exception e) {
        System.out.println(e);
    } finally {
        if (l_reader != null) {
            l_reader.close();
            l_reader = null;
        }
        if (l_urlStream != null) {
            l_urlStream.close();
            l_urlStream = null;
        }
        if (l_connection != null) {
            l_connection.disconnect();
            l_connection = null;
        }
        l_url = null;
    }
}

public static String getString() {

    StringBuffer sb = new StringBuffer();
    sb.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
    sb.append("<results>\n");

    sb.append("<object>\n");
    sb.append("<userid>1</userid>\n");
    sb.append("<roleid>111111</roleid>\n");
    sb.append("<type>add</type>\n");
    sb.append("</object>\n");

    sb.append("<object>\n");
    sb.append("<userid>2</userid>\n");
    sb.append("<roleid>111111</roleid>\n");
    sb.append("<type>delete</type>\n");
    sb.append("</object>\n");

    sb.append("</results>");

    return sb.toString();
}

}

return generateResultMsg("fail");

这个地方用document写一个xml文件
然后利用out,写到输出流就可以了!

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问
相关内容推荐