Android,Java:HTTP POST请求

46

我需要进行一个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&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>

这是我正在做的事情:HttpPost postRequest = new HttpPost(urlString); 如何构造其余参数?

8个回答

86

以下是之前在androidsnippets.com找到的示例(该网站目前已不再维护)。

// 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
}

因此,您可以将参数作为BasicNameValuePair添加。

另一种选择是使用(Http)URLConnection。有关详细信息,请参见使用java.net.URLConnection执行和处理HTTP请求。这实际上是新版Android版本(Gingerbread+)中的首选方法。请参见此博客文章此开发人员文档以及Android的HttpURLConnection javadoc


1
有没有一种简单的方法来添加数组?你需要循环遍历它们并添加BasicNameValuePair("array[]",array[i])对吗? - gsgx
1
它对JSON文件也有效吗,而不是XML? - David Dimalanta
3
谷歌推荐在 Android 2.3 及以上版本中使用 HttpURLConnection。链接地址为:http://developer.android.com/reference/org/apache/http/impl/client/DefaultHttpClient.html。 - Daniel De León
1
@ThisaruGuruge:幸运的是,我将相关摘录复制粘贴到答案中,而不是只保留链接。 - BalusC

6

针对@BalusC的回答,我想补充一下如何将响应转换为字符串:

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);
}

这里有一个convertStramToString的示例


5
请考虑使用HttpPost。请参考此链接:http://www.javaworld.com/javatips/jw-javatip34.html
URLConnection connection = new URL("http://webservice.companyname.com/login/dologin").openConnection();
// Http Method becomes POST
connection.setDoOutput(true);

// Encode according to application/x-www-form-urlencoded specification
String content =
    "id=" + URLEncoder.encode ("username") +
    "&num=" + URLEncoder.encode ("password") +
    "&remember=" + URLEncoder.encode ("on") +
    "&output=" + URLEncoder.encode ("xml");
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); 

// Try this should be the length of you content.
// it is not neccessary equal to 48. 
// content.getBytes().length is not neccessarily equal to content.length() if the String contains non ASCII characters.
connection.setRequestProperty("Content-Length", content.getBytes().length); 

// Write body
OutputStream output = connection.getOutputStream(); 
output.write(content.getBytes());
output.close();

您需要自己捕获异常。


我该如何打印响应? - Tamil

3

我建议您使用Volley来进行GET, PUT, POST...请求。

首先,在您的gradle文件中添加依赖项。

compile '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);

0
我使用以下代码将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
}

我在服务器上处理了来自C#应用程序的请求(类似于一个小型Web服务器应用程序)。 我使用以下代码成功读取了请求发布的数据:

server = new HttpListener();
server.Prefixes.Add("http://*:50000/");
server.Start();

HttpListenerContext context = server.GetContext();
HttpListenerContext context = obj as HttpListenerContext;
HttpListenerRequest request = context.Request;

StreamReader sr = new StreamReader(request.InputStream);
string str = sr.ReadToEnd();

0

2
你是否错过了Android标签?它已经在使用(轻量级版本的)HttpClient了!还可以参考HttpPost javadoc - BalusC

0

-1

Java中的HTTP POST请求未能输出响应?

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);
    }

   }
 }

这是网站: http://www.wmtechnology.org/Consultar-RUC/index.jsp,from 你可以无需验证码查询Ruc。欢迎您的意见!


2
请详细阐述您的答案,以便OP能够从中获得价值 :) - Yuca

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接