demo包含GET及POST数据传输方法,将数据以键值对的形式存储到JSONobject里面,与服务器进行数据交互。
1.申请网络权限,在AndroidManifest.xml加入
2.编写服务器连接与交互代码
public class MainActivity extends AppCompatActivity {
//界面控件
Button btnTest;
TextView tvTest;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnTest=(Button)findViewById(R.id.btn);
tvTest=(TextView)findViewById(R.id.txt);
btnTest.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
//在新线程中进行网络操作
new Thread(){
@Override
public void run() {
try {
//选择请求方式
HttpURLConnectUtils http=new HttpURLConnectUtils();
String rlt=http.DoHttpPOST("输入网址");
//输出返回的结果
System.out.println(rlt);
} catch (MalformedURLException e1) {
e1.printStackTrace();
} catch (IOException e2) {
e2.printStackTrace();
}
}
}.start();
}
});
}
//利用HttpURLConnection联系Http服务器
public class HttpURLConnectUtils {
private HttpURLConnectUtils() {
}
//post
public String DoHttpPost(String mUrl) throws IOException {
URL url = new URL(mUrl);
//初始化创建HttpURLConnection实例
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
//设置当前连接的参数
httpURLConnection.setConnectTimeout(5000); //推荐设置网络延时,如果不设置此项,获取响应状态码时可能引起阻塞
httpURLConnection.setDoOutput(true); //可写
httpURLConnection.setDoInput(true); //可读
httpURLConnection.setUseCaches(false); //不用缓存
//设置HttpURLConnection请求头里面的属性
//设定传送的内容类型是可序列化的java对象
//(如果不设此项,在传送序列化对象时,当WEB服务默认的不是这种类型时可能抛java.io.EOFException)
//请求头里的属性需要自己根据服务器具体情况设定,下面两个可以不使用(因为这是我目前项目要求的头文件格式)
httpURLConnection.setRequestProperty("Content-type", "application/json");
httpURLConnection.setRequestProperty("accept", "application/json");
//设置请求的方法
httpURLConnection.setRequestMethod("POST");//Post请求
//创建输出流,此时会隐含的进行connect
OutputStream outputStream = httpURLConnection.getOutputStream();
//创建字符流对象并用高效缓冲流包装它,便获得最高的效率,发送的是字符串推荐用字符流,其它数据就用字节流
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(outputStream));
//输入所需信息
String params = new String();
JSONObject json = new JSONObject();
try {
json.put("Account", "System");
json.put("Password", "123456");
params = json.toString();
}catch (Exception e){
}
//把json字符串写入缓冲区中
bw.write(params);
//提交参数
bw.flush();
outputStream.close();
bw.close();
//获取响应的状态码,判断是否请求成功
int rltCode = httpURLConnection.getResponseCode();
//获取响应状态码的描述, 正常返回"OK"
String msg = httpURLConnection.getResponseMessage();
if (rltCode != 200) //判断响应状态是否成功
{
System.out.println();
return "Error Code--" + rltCode + ", Error Message--" + msg;
}
//接收返回值
//创建文件流对象, InputStream-->InputStreamReader-->BufferedReader
InputStreamReader inputStreamReader = new InputStreamReader(httpURLConnection.getInputStream());
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
//获取响应数据
StringBuilder builder = new StringBuilder();
//循环读取所有数据
for (String s = bufferedReader.readLine(); s != null; s = bufferedReader.readLine()) {
builder.append(s+"\n");
}
return builder.toString();
}
//get
public String DoHttpGet(String mUrl) throws IOException {
URL url = new URL(mUrl);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setConnectTimeout(5000);//推荐设置网络延时
httpURLConnection.setReadTimeout(5000);//设置从主机读取数据超时(单位:毫秒)
httpURLConnection.setRequestMethod("GET");
//设置请求头属性
httpURLConnection.setRequestProperty("accept", "application/json");
httpURLConnection.connect(); //此处必须显式进行连接
//以下同Post
//获取响应的状态码,判断是否请求成功
int rltCode = httpURLConnection.getResponseCode();
String msg = httpURLConnection.getResponseMessage(); //获取响应状态码的描述, "OK"
if (rltCode != 200) //判断响应状态是否成功
{
System.out.println();
return "Error Code--" + rltCode + ", Error Message--" + msg;
}
//获取响应内容--读输入流
InputStreamReader inputStreamReader = new InputStreamReader(httpURLConnection.getInputStream());
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
StringBuilder builder = new StringBuilder();
for (String s = bufferedReader.readLine(); s != null; s = bufferedReader.readLine()) {
builder.append(s);
}
return builder.toString();
}
}
}
3.补充一下,上述为用json传输数据,所以用字符串。但如果是图片之类的数据,需要用字节流,直接调用函数将图像之类的数据转化成Byte数据流,然后bw.write("比特流数据")即可。
本帖子中包含资源
您需要 登录 才可以下载,没有帐号?立即注册