httppost

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;


public class TestHttpPost {

public static void main(String[] args) throws IOException {
//创建URL对象
URL url = new URL("http://127.0.0.1:8080/student/login.php");
//通过URL对象获取一个HttpURLConnection对象
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
conn.setRequestMethod("POST");//设置请求方式为POST
conn.setDoOutput(true);//设置允许输出数据到服务器
//设置请求头信息
conn.setRequestProperty("content-type", "application/x-www-form-urlencoded");
//获取输出流 通过输出流将POST请求提交的数据发送到服务器端
String data = "username=admin&password=admin";
//获取输出流对象 通过输出流将数据输出到服务器端
OutputStream out = conn.getOutputStream();
out.write(data.getBytes());//数据写出 输出数据的操作 必须放置在读取数据前
//获取输入流 通过该流可以获取服务器端响应信息
InputStream in = conn.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
//判断响应状态码 
if(conn.getResponseCode() == 200){
System.out.println("服务器请求处理成功,返回的响应:");
String msg = null;
while((msg=reader.readLine())!=null){
System.out.println(msg);
}
}
//断开连接
conn.disconnect();

}


}

##################################################

  1. import java.io.BufferedReader;  
  2. import java.io.InputStreamReader;  
  3. import java.io.OutputStream;  
  4. import java.net.HttpURLConnection;  
  5. import java.net.URL;  
  6. import java.net.URLEncoder;  
  7.   
  8. import android.app.Activity;  
  9. import android.os.Bundle;  
  10. import android.os.Handler;  
  11. import android.os.Message;  
  12. import android.view.View;  
  13. import android.view.View.OnClickListener;  
  14. import android.widget.Button;  
  15. import android.widget.EditText;  
  16. import android.widget.Toast;  
  17.   
  18. public class MainActivity extends Activity {  
  19.     private EditText et_username;  
  20.     private EditText et_password;  
  21.       
  22.     private Button bt_show;  
  23.       
  24.     String result="";  
  25.       
  26.     /**post请求URL地址*/  
  27.     private static final String URL="";  
  28.   
  29.     @Override  
  30.     protected void onCreate(Bundle savedInstanceState) {  
  31.         super.onCreate(savedInstanceState);  
  32.         setContentView(R.layout.activity_main);  
  33.           
  34.         init();  
  35.           
  36.         bt_show.setOnClickListener(new OnClickListener() {  
  37.               
  38.             @Override  
  39.             public void onClick(View arg0) {  
  40.                 //android4.0后的新的特性,网络数据请求时不能放在主线程中。  
  41.                 //9、使用线程执行访问服务器,获取返回信息后通知主线程更新UI或者提示信息。  
  42.                 final Handler handler = new Handler() {  
  43.                     @Override    
  44.                     public void handleMessage(Message msg) {    
  45.                         if (msg.what == 1) {  
  46.                             //8、提示读取结果  
  47.                             Toast.makeText(MainActivity.this, result, Toast.LENGTH_LONG).show();  
  48.                         }    
  49.                     }    
  50.                 };  
  51.                 // 启动线程来执行任务    
  52.                 new Thread() {    
  53.                     public void run() {  
  54.                         //请求网络  
  55.                         loginByPost(et_username.getText().toString(), et_password.getText().toString());   
  56.                         Message m = new Message();    
  57.                         m.what = 1;    
  58.                         // 发送消息到Handler    
  59.                         handler.sendMessage(m);    
  60.                     }    
  61.                 }.start();  
  62.                   
  63.             }  
  64.         });  
  65.           
  66.     }  
  67.       
  68.     private void init(){  
  69.         et_username=(EditText)findViewById(R.id.et_username);  
  70.         et_password=(EditText)findViewById(R.id.et_password);  
  71.         bt_show=(Button)findViewById(R.id.bt_login);  
  72.     }  
  73.       
  74.     /** 
  75.      * 请求后台,判断登录结果。 
  76.      * @param username 
  77.      * @param password 
  78.      */  
  79.     public void loginByPost(String username, String password) {    
  80.         try {   
  81.             //1、根据地址创建URL对象(网络访问的url)    
  82.             URL url = new URL(URL);    
  83.             //2、url.openConnection()打开网络链接    
  84.             HttpURLConnection conn = (HttpURLConnection)url.openConnection();    
  85.             //3、设置请求的方式    
  86.             conn.setRequestMethod("POST");   
  87.             conn.setDoInput(true);//发送POST请求必须设置允许输出  
  88.             conn.setDoOutput(true);//发送POST请求必须设置允许输入  
  89.             //4、设置请求的头  
  90.             conn.setRequestProperty("Content-Type""application/x-www-form-urlencoded");  
  91.             conn.setRequestProperty("Charset""utf-8");  
  92.             String data = "username=" + URLEncoder.encode(username, "UTF-8")    
  93.                     + "&password=" + URLEncoder.encode(password, "UTF-8");//传递的数据  
  94.             conn.setRequestProperty("Content-Length",String.valueOf(data.getBytes().length));   
  95.             //5、获取输出流   
  96.             OutputStream os = conn.getOutputStream();    
  97.             os.write(data.getBytes());    
  98.             os.flush();   
  99.               
  100.               
  101.             //6、获取响应的输入流对象  
  102.             InputStreamReader is = new InputStreamReader(conn.getInputStream());  
  103.             BufferedReader bufferedReader = new BufferedReader(is);  
  104.             StringBuffer strBuffer = new StringBuffer();  
  105.             String line = null;  
  106.             //7、读取服务器返回信息  
  107.             while ((line = bufferedReader.readLine()) != null) {  
  108.                 strBuffer.append(line);  
  109.             }  
  110.             result = strBuffer.toString();  
  111.   
  112.             //8、关闭InputStream、关闭http连接  
  113.             is.close();  
  114.             conn.disconnect();  
  115.               
  116.         } catch (Exception e) {    
  117.             e.printStackTrace();    
  118.         }    
  119.     }  
  120.       
  121. }  

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章