Android连接服务器的方法

2019-10-04  本文已影响0人  无尘粉笔

1.使用url连接

public class MyURLActivityextends Activity {

@Override

    protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

Thread thread =new Thread(new Runnable() {

@Override

            public void run() {

URL url;

String temp;

StringBuffer sb =new StringBuffer();

try {

url =new URL("http://192.168.18.157?name=allen");// 根据自己的服务器地址填写

                    BufferedReader in =new BufferedReader(new InputStreamReader(url.openStream()));// 获取输入流

                    while ((temp = in.readLine()) !=null) {

sb.append(temp);

}

System.out.println(sb.toString());

in.close();

}catch (MalformedURLException me) {

System.err.println("你输入的URL格式有问题!");

me.printStackTrace();

}catch (IOException e) {

e.printStackTrace();

}

}

});

thread.start();

}

}

2.使用httpclient

public class MyHttpClientActivityextends Activity {

@Override

    protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

Thread thread =new Thread(new Runnable() {

@Override

            public void run() {

HttpClient client =new DefaultHttpClient();

HttpGet httpGet =new HttpGet("http://192.168.18.157?name=allen");// 根据自己的服务器地址填写

                try {

HttpResponse response = client.execute(httpGet);

String temp;

StringBuffer sb =new StringBuffer();

BufferedReader in =new BufferedReader(new InputStreamReader(response.getEntity().getContent()));// 获取输入流

                    while ((temp = in.readLine()) !=null) {

sb.append(temp);

}

System.out.println(sb.toString());

in.close();

}catch (ClientProtocolException e) {

e.printStackTrace();

}catch (IOException e) {

e.printStackTrace();

}

}

});

thread.start();

}

}

3. HttpURLConnection连接

public class MyHttpURLConnectionActivityextends Activity {

@Override

    protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

Thread thread =new Thread(new Runnable() {

@Override

            public void run() {

BufferedReader bufferedReader =null;

try {

URL url =new URL("http://192.168.18.157");// 根据自己的服务器地址填写

                    HttpURLConnection conn = (HttpURLConnection) url.openConnection();

conn.setConnectTimeout(10000);

conn.setDoOutput(true);// 允许输出

                    conn.setRequestMethod("POST");

conn.setRequestProperty("Connection","Keep-Alive");

conn.setRequestProperty("Charset","GBK");

OutputStream os = conn.getOutputStream();

os.write("name=allen".getBytes());

if (conn.getResponseCode() ==200) {

System.out.println(conn.toString());

InputStream is = conn.getInputStream();

InputStreamReader isr =new InputStreamReader(is,"GBK");

bufferedReader =new BufferedReader(isr);

}

String result ="";

String line ="";

if (bufferedReader !=null) {

try {

while ((line = bufferedReader.readLine()) !=null) {

result += line;

}

}catch (IOException e) {

e.printStackTrace();

}

}

System.out.println(result);

}catch (MalformedURLException e) {

// URL格式错误

                    e.printStackTrace();

}catch (UnsupportedEncodingException e) {

// 不支持你设置的编码

                    e.printStackTrace();

}catch (ProtocolException e) {

// 请求方式不支持

                    e.printStackTrace();

}catch (IOException e) {

// 输入输出通讯出错

                    e.printStackTrace();

}

}

});

thread.start();

}

}

4. ksoap2连接

public class MyKsoap2Activityextends Activity {

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

Thread thread =new Thread(new Runnable() {

@Override

public void run() {

String URL ="http://cjf780426.xicp.net:803/Demo/DEMO1/GBSvr.dll/soap/IGBSvr";

String NAMESPACE ="http://tempuri.org/";

SoapSerializationEnvelope envelope =new SoapSerializationEnvelope(SoapEnvelope.VER11);

envelope.dotNet =true;

HttpTransportSE ht =new HttpTransportSE(URL);

ht.debug =true;

String METHOD_NAME ="GBlogin";

String SOAP_ACTION ="urn:GBSvrIntf-IGBSvr#GBlogin";

SoapObject rpc =new SoapObject(NAMESPACE, METHOD_NAME);

rpc.addProperty("UserName","AllenSTU");

rpc.addProperty("UserPWD","AllenSTU");

envelope.bodyOut = rpc;

envelope.setOutputSoapObject(rpc);

try {

ht.call(SOAP_ACTION, envelope);

System.out.println((String) envelope.getResponse());

}catch (SoapFault e) {

// TODO Auto-generated catch block

                    e.printStackTrace();

}catch (IOException e) {

// TODO Auto-generated catch block

                    e.printStackTrace();

}catch (XmlPullParserException e) {

// TODO Auto-generated catch block

                    e.printStackTrace();

}

}

});

thread.start();

}

}

5. Apache接口

public class MainActivityextends Activity {

private TextView textView;

private Button get,post;

/** Called when the activity is first created. */

    @Override

public void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.main);

textView = (TextView)findViewById(R.id.textView);

get = (Button)findViewById(R.id.get);

post = (Button)findViewById(R.id.post);

//绑定按钮监听器

        get.setOnClickListener(new OnClickListener() {

@Override

            public void onClick(View v) {

//注意:此处ip不能用127.0.0.1或localhost,Android模拟器已将它自己作为了localhost

                String uri ="http://192.168.22.28:8080/myapp/http.jsp?parameter=以Get方式发送请求";

textView.setText(get(uri));

}

});

//绑定按钮监听器

        post.setOnClickListener(new OnClickListener() {

@Override

public void onClick(View v) {

String uri ="http://192.168.22.28:8080/myapp/http.jsp";

textView.setText(post(uri));

}

});

}

/**

* 以get方式发送请求,访问web

    * @param uri web地址

    * @return 响应数据

*/

    private static String get(String uri){

BufferedReader reader =null;

StringBuffer sb =null;

String result ="";

HttpClient client =new DefaultHttpClient();

HttpGet request =new HttpGet(uri);

try {

//发送请求,得到响应

            HttpResponse response = client.execute(request);

//请求成功

            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK){

reader =new BufferedReader(new InputStreamReader(response.getEntity().getContent()));

sb =new StringBuffer();

String line ="";

String NL = System.getProperty("line.separator");

while((line = reader.readLine()) !=null){

sb.append(line);

}

}

}catch (ClientProtocolException e) {

e.printStackTrace();

}catch (IOException e) {

e.printStackTrace();

}

finally{

try {

if (null != reader){

reader.close();

reader =null;

}

}catch (IOException e) {

e.printStackTrace();

}

}

if (null != sb){

result =  sb.toString();

}

return result;

}

/**

* 以post方式发送请求,访问web

    * @param uri web地址

    * @return 响应数据

*/

    private static String post(String uri){

BufferedReader reader =null;

StringBuffer sb =null;

String result ="";

HttpClient client =new DefaultHttpClient();

HttpPost request =new HttpPost(uri);

//保存要传递的参数

        List params =new ArrayList();

//添加参数

        params.add(new BasicNameValuePair("parameter","以Post方式发送请求"));

try {

//设置字符集

            HttpEntity entity =new UrlEncodedFormEntity(params,"utf-8");

//请求对象

            request.setEntity(entity);

//发送请求

            HttpResponse response = client.execute(request);

//请求成功

            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK){

System.out.println("post success");

reader =new BufferedReader(new InputStreamReader(response.getEntity().getContent()));

sb =new StringBuffer();

String line ="";

String NL = System.getProperty("line.separator");

while((line = reader.readLine()) !=null){

sb.append(line);

}

}

}catch (ClientProtocolException e) {

e.printStackTrace();

}catch (IOException e) {

e.printStackTrace();

}

finally{

try {

//关闭流

                if (null != reader){

reader.close();

reader =null;

}

}catch (IOException e) {

e.printStackTrace();

}

}

if (null != sb){

result =  sb.toString();

}

return result;

}

}

上一篇 下一篇

猜你喜欢

热点阅读