Android,Java:HTTP POST请求
我必须向web服务发出http post请求,以便使用用户名和密码对用户进行身份验证。Web服务人员给了我以下信息来构造HTTP Post请求Android,Java:HTTP POST请求,java,android,http-post,Java,Android,Http Post,我必须向web服务发出http post请求,以便使用用户名和密码对用户进行身份验证。Web服务人员给了我以下信息来构造HTTP Post请求 POST /login/dologin HTTP/1.1 Host: webservice.companyname.com Content-Type: application/x-www-form-urlencoded Content-Length: 48 id=username&num=password&remember=on&
POST /login/dologin HTTP/1.1
Host: webservice.companyname.com
Content-Type: application/x-www-form-urlencoded
Content-Length: 48
id=username&num=password&remember=on&output=xml
我将得到的XML响应是
<?xml version="1.0" encoding="ISO-8859-1"?>
<login>
<message><![CDATA[]]></message>
<status><![CDATA[true]]></status>
<Rlo><![CDATA[Username]]></Rlo>
<Rsc><![CDATA[9L99PK1KGKSkfMbcsxvkF0S0UoldJ0SU]]></Rsc>
<Rm><![CDATA[b59031b85bb127661105765722cd3531==AO1YjN5QDM5ITM]]></Rm>
<Rl><![CDATA[username@company.com]]></Rl>
<uid><![CDATA[3539145]]></uid>
<Rmu><![CDATA[f8e8917f7964d4cc7c4c4226f060e3ea]]></Rmu>
</login>
这就是我正在做的HttpPostRequest=newHttpPost(urlString);如何构造其余参数?试试HttpClient for Java:
请考虑使用HTTPSPOST。从中采纳:
您需要自己捕获异常。这里有一个以前在中找到的示例(该站点目前不再维护)
//创建新的HttpClient和Post头
HttpClient HttpClient=新的DefaultHttpClient();
HttpPost HttpPost=新的HttpPost(“http://www.yoursite.com/script.php");
试一试{
//添加您的数据
List nameValuePairs=新的ArrayList(2);
添加(新的BasicNameValuePair(“id”,“12345”);
添加(新的BasicNameValuePair(“stringdata”,“AndDev很酷!”);
setEntity(新的UrlEncodedFormEntity(nameValuePairs));
//执行HTTP Post请求
HttpResponse response=httpclient.execute(httppost);
}捕获(客户端协议例外e){
//TODO自动生成的捕捉块
}捕获(IOE异常){
//TODO自动生成的捕捉块
}
因此,您可以将参数添加为
另一种方法是使用
(Http)URLConnection
。另见。这实际上是较新的Android版本(姜饼+)的首选方法。另请参见和Android。您可以重用我添加到ACRA的实现:
(请参阅doPost(Map,Url)方法,即使使用自签名证书也可以通过http和https工作)对于@BalusC answer,我将添加如何将响应转换为字符串:
HttpResponse response = client.execute(request);
HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream instream = entity.getContent();
String result = RestClient.convertStreamToString(instream);
Log.i("Read from server", result);
}
.我使用以下代码将HTTP POST从我的android客户端应用程序发送到我服务器上的C#桌面应用程序:
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.yoursite.com/script.php");
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("id", "12345"));
nameValuePairs.add(new BasicNameValuePair("stringdata", "AndDev is Cool!"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
我建议您使用截击发出获取、放置、发布…请求
RequestQueue queue = Volley.newRequestQueue(getApplicationContext());
StringRequest postRequest = new StringRequest( com.android.volley.Request.Method.POST, mURL,
new Response.Listener<String>()
{
@Override
public void onResponse(String response) {
// response
Log.d("Response", response);
}
},
new Response.ErrorListener()
{
@Override
public void onErrorResponse(VolleyError error) {
// error
Log.d("Error.Response", error.toString());
}
}
) {
@Override
protected Map<String, String> getParams()
{
Map<String, String> params = new HashMap<String, String>();
//add your parameters here as key-value pairs
params.put("username", username);
params.put("password", password);
return params;
}
};
queue.add(postRequest);
首先,在gradle文件中添加依赖项
编译'com.he5ed.lib:volley:android-cts-5.1_r4'
现在,使用此代码段发出请求
RequestQueue queue = Volley.newRequestQueue(getApplicationContext());
StringRequest postRequest = new StringRequest( com.android.volley.Request.Method.POST, mURL,
new Response.Listener<String>()
{
@Override
public void onResponse(String response) {
// response
Log.d("Response", response);
}
},
new Response.ErrorListener()
{
@Override
public void onErrorResponse(VolleyError error) {
// error
Log.d("Error.Response", error.toString());
}
}
) {
@Override
protected Map<String, String> getParams()
{
Map<String, String> params = new HashMap<String, String>();
//add your parameters here as key-value pairs
params.put("username", username);
params.put("password", password);
return params;
}
};
queue.add(postRequest);
RequestQueue queue=Volley.newRequestQueue(getApplicationContext());
StringRequest postRequest=新的StringRequest(com.android.volley.Request.Method.POST,mURL,
新的Response.Listener()
{
@凌驾
公共void onResponse(字符串响应){
//回应
Log.d(“响应”,响应);
}
},
新的Response.ErrorListener()
{
@凌驾
公共无效onErrorResponse(截击错误){
//错误
Log.d(“Error.Response”,Error.toString());
}
}
) {
@凌驾
受保护的映射getParams()
{
Map params=新的HashMap();
//将参数作为键值对添加到此处
参数put(“用户名”,用户名);
参数put(“密码”,密码);
返回参数;
}
};
添加(postRequest);
java中的HTTP请求帖子不会转储答案?
public class HttpClientExample
{
private final String USER_AGENT = "Mozilla/5.0";
public static void main(String[] args) throws Exception
{
HttpClientExample http = new HttpClientExample();
System.out.println("\nTesting 1 - Send Http POST request");
http.sendPost();
}
// HTTP POST request
private void sendPost() throws Exception {
String url = "http://www.wmtechnology.org/Consultar-RUC/index.jsp";
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(url);
// add header
post.setHeader("User-Agent", USER_AGENT);
List<NameValuePair> urlParameters = new ArrayList<>();
urlParameters.add(new BasicNameValuePair("accion", "busqueda"));
urlParameters.add(new BasicNameValuePair("modo", "1"));
urlParameters.add(new BasicNameValuePair("nruc", "10469415177"));
post.setEntity(new UrlEncodedFormEntity(urlParameters));
HttpResponse response = client.execute(post);
System.out.println("\nSending 'POST' request to URL : " + url);
System.out.println("Post parameters : " + post.getEntity());
System.out.println("Response Code : " +response.getStatusLine().getStatusCode());
BufferedReader rd = new BufferedReader(new
InputStreamReader(response.getEntity().getContent()));
StringBuilder result = new StringBuilder();
String line = "";
while ((line = rd.readLine()) != null)
{
result.append(line);
System.out.println(line);
}
}
}
公共类HttpClientExample
{
私有最终字符串用户_AGENT=“Mozilla/5.0”;
公共静态void main(字符串[]args)引发异常
{
HttpClientExample http=新的HttpClientExample();
System.out.println(“\n测试1-发送Http POST请求”);
http.sendPost();
}
//HTTP POST请求
私有void sendPost()引发异常{
字符串url=”http://www.wmtechnology.org/Consultar-RUC/index.jsp";
HttpClient=new DefaultHttpClient();
HttpPost=新的HttpPost(url);
//添加标题
post.setHeader(“用户代理”,用户代理);
List urlParameters=new ArrayList();
添加(新的BasicNameValuePair(“accion”、“busqueda”);
添加(新的BasicNameValuePair(“modo”,“1”);
添加(新的BasicNameValuePair(“nruc”,“10469415177”);
setEntity(新的UrlEncodedFormEntity(urlParameters));
HttpResponse response=client.execute(post);
System.out.println(“\n向URL发送'POST'请求:“+URL”);
System.out.println(“Post参数:+Post.getEntity());
System.out.println(“响应代码:+Response.getStatusLine().getStatusCode());
BufferedReader rd=新的BufferedReader(新的
InputStreamReader(response.getEntity().getContent());
StringBuilder结果=新建StringBuilder();
字符串行=”;
而((line=rd.readLine())!=null)
{
结果。追加(行);
系统输出打印项次(行);
}
}
}
这是网络:您可以咨询Ruc而无需验证码。欢迎您的意见您是否错过了
Android
标签?它已经在幕后使用(精简版的)HttpClient了!另请参见。是否有添加数组的简单方法?您是否需要在它们之间循环并添加对BasicNameValuePair(“array[]”,array[i])?它对JSON文件而不是XML文件是否也有效?对于Android 2.3和更高版本,Google建议使用HttpURLConnection@幸运的是,我在答案中复制粘贴了相关性摘录,而不是将其保留在仅链接的答案中。我如何打印响应?请详细说明您的答案,以便OP可以从中提取价值:)
RequestQueue queue = Volley.newRequestQueue(getApplicationContext());
StringRequest postRequest = new StringRequest( com.android.volley.Request.Method.POST, mURL,
new Response.Listener<String>()
{
@Override
public void onResponse(String response) {
// response
Log.d("Response", response);
}
},
new Response.ErrorListener()
{
@Override
public void onErrorResponse(VolleyError error) {
// error
Log.d("Error.Response", error.toString());
}
}
) {
@Override
protected Map<String, String> getParams()
{
Map<String, String> params = new HashMap<String, String>();
//add your parameters here as key-value pairs
params.put("username", username);
params.put("password", password);
return params;
}
};
queue.add(postRequest);
public class HttpClientExample
{
private final String USER_AGENT = "Mozilla/5.0";
public static void main(String[] args) throws Exception
{
HttpClientExample http = new HttpClientExample();
System.out.println("\nTesting 1 - Send Http POST request");
http.sendPost();
}
// HTTP POST request
private void sendPost() throws Exception {
String url = "http://www.wmtechnology.org/Consultar-RUC/index.jsp";
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(url);
// add header
post.setHeader("User-Agent", USER_AGENT);
List<NameValuePair> urlParameters = new ArrayList<>();
urlParameters.add(new BasicNameValuePair("accion", "busqueda"));
urlParameters.add(new BasicNameValuePair("modo", "1"));
urlParameters.add(new BasicNameValuePair("nruc", "10469415177"));
post.setEntity(new UrlEncodedFormEntity(urlParameters));
HttpResponse response = client.execute(post);
System.out.println("\nSending 'POST' request to URL : " + url);
System.out.println("Post parameters : " + post.getEntity());
System.out.println("Response Code : " +response.getStatusLine().getStatusCode());
BufferedReader rd = new BufferedReader(new
InputStreamReader(response.getEntity().getContent()));
StringBuilder result = new StringBuilder();
String line = "";
while ((line = rd.readLine()) != null)
{
result.append(line);
System.out.println(line);
}
}
}