2014年2月25日

java http連線與傳送資料範例

原文來源:http://www.mkyong.com/java/how-to-send-http-request-getpost-in-java/
以下的範例我有稍微修改
-----------------------java-----------------------
package httppost;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

public class TestHttp {
 
 // HTTP GET request
 public void sendGet() throws Exception {
 
  String url = "http://127.0.0.1/test.php?id=中文字&pw=中文字";
 
  URL obj = new URL(url);
  HttpURLConnection con = (HttpURLConnection) obj.openConnection();
 

  con.setRequestMethod("GET");
 
  con.setRequestProperty("User-Agent", "Mozilla/5.0");
 
  int responseCode = con.getResponseCode();
  System.out.println("\nSending 'GET' request to URL : " + url);
  System.out.println("Response Code : " + responseCode);
 
  BufferedReader in = new BufferedReader(
          new InputStreamReader(con.getInputStream()));
  String inputLine;
  StringBuffer response = new StringBuffer();
 
  while ((inputLine = in.readLine()) != null) {
   response.append(inputLine);
  }
  in.close();

  System.out.println(response.toString());
 
 }


 // HTTP POST request
 private void sendPost() throws Exception {
 
  String url = "http://127.0.0.1/test.php";
  URL obj = new URL(url);
  HttpURLConnection con = (HttpURLConnection) obj.openConnection();
 

  con.setRequestMethod("POST");
  
  con.setRequestProperty("User-Agent", "Mozilla/5.0");
  con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
 
  String data = "id=UTF8中文字&pw=UTF8中文字";
 

  con.setDoOutput(true);
  DataOutputStream wr = new DataOutputStream(con.getOutputStream());
  //wr.writeBytes(data);
  wr.write(data.getBytes("utf-8"));//為了傳送utf8的文字改成這個
  wr.flush();
  wr.close();
 
  int responseCode = con.getResponseCode();
  System.out.println("Sending 'POST' request to URL : " + url);
  System.out.println("Post parameters : " + data);
  System.out.println("Response Code : " + responseCode);
 
  BufferedReader in = new BufferedReader(
          new InputStreamReader(con.getInputStream()));
  String inputLine;
  StringBuffer response = new StringBuffer();
 
  while ((inputLine = in.readLine()) != null) {
   response.append(inputLine);
  }
  in.close();

  System.out.println(response.toString());
 
 }
 
 
 public static void main(String[] args) throws Exception {
   

  TestHttp testhttp = new TestHttp();
  testhttp.sendPost();
  testhttp.sendGet();
 }
}

-----------------------PHP-----------------------
if($_GET['id'] != '' && $_GET['pw'] != '')
{
 echo 'id=' . $_GET['id'] . ' pw=' . $_GET['pw'];
}


if($_POST['id'] != '' && $_POST['pw'] != '')
{
 echo 'id=' . $_POST['id'] . ' pw=' . $_POST['pw'];
}

補充 可以用這個來取得標頭
		//---------
		Map> header = con.getHeaderFields();
		for (Map.Entry> entry : header.entrySet()) {
		    String key = entry.getKey();
		    for (String value : entry.getValue()) {
		        System.out.println(key + ":" + value);
		    }
		}
		//---------

沒有留言:

張貼留言