程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> JAVA編程 >> JAVA綜合教程 >> HttpUrlConnection get,post傳輸

HttpUrlConnection get,post傳輸

編輯:JAVA綜合教程

HttpUrlConnection get,post傳輸


這裡沒有寫UI操作,get請求中文亂碼問題這裡也沒有處理,如果做UI操作,需要在子線程中,這裡主要講解get,post如何傳遞數據,其他知識就不考慮了

package com.example.httpurlconnectiontest;

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

import android.content.Context;
import android.widget.Toast;

/**
 * 使用HttpUrlConnection實現get,post方式傳遞數據
 * @author Administrator
 *
 */

public class HttpThread extends Thread{

	private String url;
	private String name;
	private String age;
	private Context context;
	public HttpThread(Context context, String url, String name, String age) {
		this.context =context;
		this.url = url;
		this.name = name;
		this.age = age;
	}
	private void doGet(){
		url = url+"?username="+name+"&password="+age;
		try {
			URL httpUrl = new URL(url);
			HttpURLConnection conn = (HttpURLConnection) httpUrl.openConnection();
			conn.setRequestMethod("GET");
			conn.setReadTimeout(5000);
			BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
			String str;
			StringBuffer sb = new StringBuffer();
			while((str = reader.readLine())!=null){
				sb.append(str);
			}
			System.out.println(sb);

		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	private void doPost(){

		try {
			URL httpUrl = new URL(url);
			HttpURLConnection conn = (HttpURLConnection) httpUrl.openConnection();
			conn.setRequestMethod("POST");
			conn.setReadTimeout(5000);
			OutputStream out = conn.getOutputStream();
			String content ="username="+name+"&password="+age;
			out.write(content.getBytes());
			BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
			String str;
			StringBuffer sb = new StringBuffer();
			while((str = reader.readLine())!=null){
				sb.append(str);
			}
			System.out.println(sb);

		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}
	@Override
	public void run() {
		// TODO Auto-generated method stub
		//doGet();
		doPost();

	}

}
在MainActivity中調用:
String url = "http://115.158.57.173:8080/KuaiDi3/AddUser_servlet";

		new HttpThread(MainActivity.this,url, "123", "123").start();
 

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved