android HttpPost以xml格式向服务器发送数据
我需要将登录名和用户名数据发送到下面提到的服务器android HttpPost以xml格式向服务器发送数据,android,http-post,Android,Http Post,我需要将登录名和用户名数据发送到下面提到的服务器 <req_data><username></username><password></password></req_data> 请建议我如何将此用户名和密码发送到服务器并从服务器获得响应尝试使用HTTPUrlConnection,您可以在下面找到一个示例方法。它接受服务器的URL和字符串内容(XML字符串)。 Post请求将被发送到URL,提供的内容将存储在P
<req_data><username></username><password></password></req_data>
请建议我如何将此用户名和密码发送到服务器并从服务器获得响应尝试使用
HTTPUrlConnection
,您可以在下面找到一个示例方法。它接受服务器的URL和字符串内容(XML字符串)。
Post请求将被发送到URL,提供的内容将存储在Post头中,您可以在服务器端应用程序上检索到它(如果使用PHP try$headerContent=file\u get\u contents('php://input);
)
您将发现服务器的响应是此方法返回的字符串值。您可以使用您喜爱的解析器将其解析为Java对象
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();
}
}
}