Android HTTP Communication:

2019-06-09 09:52发布

I have created an android application for sending messages to a server for interpretation before the server returns an appropriate answer. I am really trying to demonstrate wireless connections.

So from the Android phone I simply want to send the message, what would be the appropriate way.... httppost? (I have done this with sockets using buffer/print)

In the server class should I use httpget to recieve the message?

Then having digested the message and decided on an appropriate result how would I send it back to the android application? httppost again?

From the android app to read it would I need to once again use httpget?

Examples would really be appreciated. Please bare in mind I am looking to use the http protocol!

Kind regards

Simon

2条回答
爷的心禁止访问
2楼-- · 2019-06-09 10:36

HTTP POST is appropriate in both cases. You can use java.net.HttpURLConnection to perform the POST.

Here is a good example: http://www.rgagnon.com/javadetails/java-0084.html linked to by this answer: Java: how to use UrlConnection to post request with authorization?

查看更多
可以哭但决不认输i
3楼-- · 2019-06-09 10:52

I've had good results using HttpClient.

(Didn't run this and omitted try/catches but it should get you started).

// setup the client
HttpContext httpContext = new BasicHttpContext();
DefaultHttpClient httpClient = new DefaultHttpClient();

// setup the request
HttpPost post = new HttpPost("http://someurl.com/");
List<BasicNameValuePair> pairs = new ArrayList<BasicNameValuePair>();
pairs.add(new BasicNameValuePair("name" , "value"));
post.setEntity(new UrlEncodedFormEntity(pairs));

// execute the request
BasicHttpResponse response =
        (BasicHttpResponse)httpClient.execute(post, httpContext);

// do something with the response
InputStream is = response.getEntity().getContent();
BufferedReader br = new BufferedReader(new InputStreamReader(is));

String content;
StringBuilder contentBuilder = new StringBuilder();

String line = null;
while((line = br.readLine()) != null)
    contentBuilder.append(line);

br.close();
is.close();

content = contentBuilder.toString();

// done!
查看更多
登录 后发表回答