开发者

Android, Java: HTTP POST Request

开发者 https://www.devze.com 2023-02-01 04:15 出处:网络
I have to do a http post request to a web-service for authenticating the user with username and password. The Web-service guy gave me following information to construct HTTP Post request.

I have to do a http post request to a web-service for authenticating the user with username and password. The Web-service guy gave me following information to construct HTTP Post request.

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

The XML Response that i will be getting is

<?xml version="1.0" encoding="ISO-8859-1"?>
<login>
 <message><![CDATA[]]></message>
 <status><![CDATA[true]]><开发者_如何学Python/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>

This is what i am doing HttpPost postRequest = new HttpPost(urlString); How do i construct the rest of the parameters?


Here's an example previously found at androidsnippets.com (the site is currently not maintained anymore).

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

So, you can add your parameters as BasicNameValuePair.

An alternative is to use (Http)URLConnection. See also Using java.net.URLConnection to fire and handle HTTP requests. This is actually the preferred method in newer Android versions (Gingerbread+). See also this blog, this developer doc and Android's HttpURLConnection javadoc.


to @BalusC answer I would add how to convert the response in a String:

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

Here is an example of convertStramToString.


Please consider using HttpPost. Adopt from this: 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();

You will need to catch the exception yourself.


I'd rather recommend you to use Volley to make GET, PUT, POST... requests.

First, add dependency in your gradle file.

compile 'com.he5ed.lib:volley:android-cts-5.1_r4'

Now, use this code snippet to make requests.

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


Try HttpClient for Java:

http://hc.apache.org/httpclient-3.x/


You can reuse the implementation I added to ACRA: http://code.google.com/p/acra/source/browse/tags/REL-3_1_0/CrashReport/src/org/acra/HttpUtils.java?r=236

(See the doPost(Map, Url) method, working over http and https even with self signed certs)


I used the following code to send HTTP POST from my android client app to C# desktop app on my server:

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

I worked on reading the request from a C# app on my server (something like a web server little application). I managed to read request posted data using the following code:

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


HTTP request POST in java does not dump the answer?

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

   }
 }

This is the web: http://www.wmtechnology.org/Consultar-RUC/index.jsp,from you can consult Ruc without captcha. Your opinions are welcome!

0

精彩评论

暂无评论...
验证码 换一张
取 消