Android与服务器通信

本文介绍了两种常见的网络通信方式:HTTP和Socket。通过Java代码示例展示了如何使用这两种方式进行数据交换,包括GET和POST请求的HTTP通信及Socket客户端的创建与消息发送。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.Http方式

package com.myapp.util;

import java.util.List;

import org.apache.http.HttpEntity;
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.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

public class MyUtil {
    public static String doGet(String url){
        HttpGet get=new HttpGet(url);  
        HttpClient client=new DefaultHttpClient();
        String result="";
        try {  
            HttpResponse response=client.execute(get);//执行Post方法
            
            result=EntityUtils.toString(response.getEntity());
        }catch (Exception e) {
            return "";
        }
        return result;
    }
      
    public  String doPost(String url,List<NameValuePair> values){     
        try {  
            HttpEntity httpEntity=new UrlEncodedFormEntity(values,"UTF-8");//使用编码构建Post实体
            HttpPost post=new HttpPost(url);  
            post.setEntity(httpEntity);//设置Post实体   
            HttpClient client=new DefaultHttpClient();  
            HttpResponse  response=client.execute(post);//执行Post方法   
            return EntityUtils.toString(response.getEntity());  
        } catch (Exception e) {
            return "";
        }
    }

}

2.Socket方式

package com.bjdata.myapp.util;

import java.io.*;
import java.net.*;

 public class SocketClient {
    static Socket client;
    
    public SocketClient(String site, int port){
        try{
            client = new Socket(site,port);
            System.out.println("Client is created! site:"+site+" port:"+port);
        }catch (UnknownHostException e){
            e.printStackTrace();
        }catch (IOException e){
            e.printStackTrace();
        }
    }
    
    public String sendMsg(String msg){
        try{
            BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));
            PrintWriter out = new PrintWriter(client.getOutputStream());
            out.println(msg);
            out.flush();
            return in.readLine();
        }catch(IOException e){
            e.printStackTrace();
        }
        return "";
    }
    public void closeSocket(){
        try{
            client.close();
        }catch(IOException e){
            e.printStackTrace();
        }
    }

}

 

转载于:https://www.cnblogs.com/zhanghaoh/archive/2012/12/27/2836197.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值