JDK -GET,POST
Posted 尚文韬
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了JDK -GET,POST相关的知识,希望对你有一定的参考价值。
GET
public class JDKActivity extends AppCompatActivity { EditText et1; RequestQueue requestQueue; //请求队列 @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_jdk); et1=(EditText)findViewById(R.id.et1); } //显示结果 String str = ""; //JDK-GEt方式 public void bt_1(View v) { //1-启动进度对话框 final ProgressDialog pd = ProgressDialog.show(this,null,"请稍后……"); //2-启动子线程,访问远程服务器 new Thread() { @Override public void run() { //1-访问远程服务器 //JDK GET HttpURLConnection huc=null; try { //1-先构造URL对象 URL url = new URL("http://192.168.0.164:81/index.asp?name=mike&password=456"); //2-得到连接对象HttpURLConnection huc= (HttpURLConnection)url.openConnection(); //3-设置HttpURLConnection huc.setRequestMethod("GET"); huc.setConnectTimeout(3000); huc.setReadTimeout(3000); //4-连接远程服务器 huc.connect(); //5-接收响应报文的状态码 int code=huc.getResponseCode(); str = ""; //6-判断响应状态码,是否等于200 if (code==200) { //7-处理 //1-接收数据 //2-得到数据流 InputStream is = huc.getInputStream(); //读到的数据 byte[] b = new byte[1024]; //读到的数据长度 int i=0; while ((i=is.read(b))>0) { //接收字符串 str +=new String(b,0, i); } is.close(); } else { str="响应错误,错误码"+code; } //显示结果,不能直接跨线程访问主线程的视图 runOnUiThread(new Runnable() { @Override public void run() { et1.setText(str); } }); } catch (Exception e) { e.printStackTrace(); } finally { //8-关闭链接和进度对话框 //释放资源 if (huc!=null) { huc.disconnect(); } //支持跨线程访问 pd.dismiss(); } } }.start(); }
POST
//JDK-POST方式 public void bt_2(View v) { //1-启动进度对话框 final ProgressDialog pd = ProgressDialog.show(this,null,"请稍后……"); //2-启动子线程,访问远程服务器 new Thread() { @Override public void run() { //1-访问远程服务器 //JDK POST HttpURLConnection huc=null; try { //1-先构造URL对象 URL url = new URL("http://192.168.0.164:81/index.asp"); //2-得到连接对象HttpURLConnection huc= (HttpURLConnection)url.openConnection(); //3-设置HttpURLConnection huc.setRequestMethod("POST"); huc.setConnectTimeout(3000); huc.setReadTimeout(3000); //4-连接远程服务器,输出流 huc.connect(); //数据放到请求集里 //1)得到输入流 OutputStream os=huc.getOutputStream(); String outstr="name=tom&password=123 "; os.write(outstr.getBytes("UTF-8")); //5-接收响应报文的状态码 int code=huc.getResponseCode(); str = ""; //6-判断响应状态码,是否等于200 if (code==200) { //7-处理 //1-接收数据 //2-得到数据流,输入流 InputStream is = huc.getInputStream(); //读到的数据 byte[] b = new byte[1024]; //读到的数据长度 int i=0; while ((i=is.read(b))>0) { //接收字符串 str +=new String(b,0, i); } is.close(); os.close(); } else { str="响应错误,错误码"+code; } //显示结果,不能直接跨线程访问主线程的视图 runOnUiThread(new Runnable() { @Override public void run() { et1.setText(str); } }); } catch (Exception e) { e.printStackTrace(); } finally { //8-关闭链接和进度对话框 //释放资源 if (huc!=null) { huc.disconnect(); } //支持跨线程访问 pd.dismiss(); } } }.start(); }
以上是关于JDK -GET,POST的主要内容,如果未能解决你的问题,请参考以下文章