package com.example.testhttpurlcon;import android.os.Bundle;import android.app.Activity;import android.view.Menu;public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Thread td = new Thread(new Runnable() { @Override public void run() { // TODO Auto-generated method stub httpUrlConTest huc = new httpUrlConTest(); huc.testHttpUrlCon(); } }); td.start(); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.activity_main, menu); return true; }}
package com.example.testhttpurlcon;import java.io.BufferedReader;import java.io.InputStream;import java.io.InputStreamReader;import java.net.HttpURLConnection;import java.net.URL;import java.util.ArrayList;import java.util.List;import org.apache.http.HttpResponse;import org.apache.http.NameValuePair;import org.apache.http.client.HttpClient;import org.apache.http.client.entity.UrlEncodedFormEntity;import org.apache.http.client.methods.HttpPost;import org.apache.http.impl.client.DefaultHttpClient;import org.apache.http.message.BasicNameValuePair;import org.apache.http.protocol.HTTP;import org.apache.http.util.EntityUtils;import android.util.Log;public class httpUrlConTest { public void testHttpUrlCon() { try { String url ="http://www.xxxx.com:端口号/xxx"; // 创建连接 HttpClient httpClient = new DefaultHttpClient(); HttpPost post = new HttpPost(url); // 设置参数,仿html表单提交 ListparamList = new ArrayList (); BasicNameValuePair param1 = new BasicNameValuePair("name", "xxx"); BasicNameValuePair param2 = new BasicNameValuePair("pass", "xxx"); paramList.add(param1);paramList.add(param2); post.setEntity(new UrlEncodedFormEntity(paramList, HTTP.UTF_8)); // 发送HttpPost请求,并返回HttpResponse对象 HttpResponse httpResponse = httpClient.execute(post); // 判断请求响应状态码,状态码为200表示服务端成功响应了客户端的请求 if (httpResponse.getStatusLine().getStatusCode() == 200) { // 获取返回结果 String result = EntityUtils.toString(httpResponse .getEntity()); System.out.println(result); Log.i("sm", result); } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } }}