1. 程式人生 > >post方式發送和解析xml

post方式發送和解析xml

httpclient post xml

public void etcauthorize(String authCode, String clientState) {

logger.info("CMCasController- etcauthorize start... ");

View view = new View(SUCCESS);

PostMethod myPost = null;

try {

StringBuffer xmlparam = new StringBuffer();

xmlparam.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>")

.append("<GetAccessTokenReqest xmlns=\"http://www.chinamobile.com.cn/schema/omp/idmp/v1_0\">")

.append("<grantType>authorization_code</grantType>")

.append("<clientId>" + appid + "</clientId>")

.append("<clientSecret>" + clientSecret + "</clientSecret>")

.append("<authCode>" + authCode + "</authCode>")

.append("<redirectUri>" + URLEncoder.encode(PageUtil.parseUrl(redirectUri), "utf-8") + "</redirectUri>")

.append("<display>mobile</display>")

.append("</GetAccessTokenReqest>");

logger.info("CMCasController- etcauthorize 跳轉到中移動授權頁面 請求 ", xmlparam.toString());

HttpClient httpclient = new HttpClient();

myPost = new PostMethod("https://open.mmarket.com/omee-aus/services/GetAccessToken");

myPost.setRequestHeader("Content-Type","text/xml");

myPost.setRequestHeader("charset","utf-8");

myPost.setRequestBody(xmlparam.toString());// 這裏添加字符串

int resultcode = httpclient.executeMethod(myPost);

if (resultcode == 200) {

String res = myPost.getResponseBodyAsString();

logger.info("CMCasController- etcauthorize 跳轉到中移動授權頁面響應", res);

if (res != null) {

StringReader read = new StringReader(res);

InputSource source = new InputSource(read);

DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();

DocumentBuilder db = dbf.newDocumentBuilder();

Document d = db.parse(source);

String accessToken = d.getElementsByTagName("accessToken").item(0).getFirstChild().getNodeValue();

String uniqueId = d.getElementsByTagName("uniqueId").item(0).getFirstChild().getNodeValue();

logger.info("CMCasController-etcauthorize 獲取到用戶授權,accessToken:{}, uniqueId:{}" ,accessToken,uniqueId );

view.bind("show",getUserInfo(accessToken, uniqueId));

}

}

} catch (Exception e) {

logger.error("CMCasController- etcauthorize 跳轉到中移動授權頁面 出現異常 ", e);

} finally {

// 釋放連接

myPost.releaseConnection();

}

this.render(view);

}



post方式發送和解析xml