android HttpPost以xml格式向服务器发送数据

时间:2016-02-07 11:38:11

标签: android http-post

我需要将登录名和用户名数据发送到服务器,如下所述

     <req_data><username></username><password></password></req_data>

请建议我如何将此用户名和密码发送到服务器并从服务器获取响应

1 个答案:

答案 0 :(得分:0)

尝试使用HTTPUrlConnection,您可以在下面找到示例方法。它接受您的服务器的URL和字符串内容(您的XML字符串)。 将对URL进行发布请求,并且提供的内容将存储在POST标头中,您可以在服务器端应用程序中检索该标头(如果使用PHP,请尝试$headerContent = file_get_contents('php://input');

public static String excutePost(String targetURL, String content){
URL url;
HttpURLConnection connection = null;  
try {
  //Create connection
  url = new URL(targetURL);
  connection = (HttpURLConnection)url.openConnection();
  connection.setRequestMethod("POST");
  connection.setRequestProperty("Content-Type", 
       "application/x-www-form-urlencoded");

  connection.setRequestProperty("Content-Length", "" + 
           Integer.toString(urlParameters.getBytes().length));
  connection.setRequestProperty("Content-Language", "en-US");  

  connection.setUseCaches (false);
  connection.setDoInput(true);
  connection.setDoOutput(true);

  //Send request
  DataOutputStream wr = new DataOutputStream (
              connection.getOutputStream ());
  wr.writeBytes (content);
  wr.flush ();
  wr.close ();

  //Get Response    
  InputStream is = connection.getInputStream();
  BufferedReader rd = new BufferedReader(new InputStreamReader(is));
  String line;
  StringBuffer response = new StringBuffer(); 
  while((line = rd.readLine()) != null) {
    response.append(line);
    response.append('\r');
  }
  rd.close();
  return response.toString();

} catch (Exception e) {

  e.printStackTrace();
  return null;

} finally {

  if(connection != null) {
    connection.disconnect(); 
  }
} 
}

您将找到服务器的响应作为此方法的返回String值。您可以使用自己喜欢的解析器将其解析为Java对象。