http通信doGet与doPost方式小例子

package com.example.httptest;


import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Properties;


import javax.net.ssl.HttpsURLConnection;


import android.util.Log;


public class httpurl extends Thread {
public String name;
public String age;
public String url;


public httpurl(String url,String name, String string) {
super();
this.name = name;
this.age = string;
this.url = url;
}


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


private void doGet() {
try {
url = url + "?name=" +URLEncoder.encode(name+"utf-8")+ "&age=" + age;//解决客户端乱码问题。
URL urls = new URL(url);
HttpsURLConnection httpsURLConnection = (HttpsURLConnection) urls
.openConnection();
httpsURLConnection.setRequestMethod("GET");
httpsURLConnection.setReadTimeout(5000);
BufferedReader bufferedReader = new BufferedReader(
new InputStreamReader(httpsURLConnection.getInputStream()));
String str;
StringBuffer buffer = new StringBuffer();
while ((str = bufferedReader.readLine()) != null) {
buffer.append(str);
}
Log.d("me", buffer.toString());
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}


public void doPost()
{
try {
Properties properties=System.getProperties();
properties.list(System.out);//系统编码集,可以看到doPost方式是以utf-8传送的。
URL urls=new URL(url);
HttpsURLConnection connection=(HttpsURLConnection) urls.openConnection();
connection.setReadTimeout(5000);
connection.setRequestMethod("post");
OutputStream outputStream=connection.getOutputStream();
String connurl="name="+name+"&age"+age;
outputStream.write(connurl.getBytes());
BufferedReader bufferedReader=new BufferedReader(new InputStreamReader(connection.getInputStream()));
String strr;
StringBuffer buffer=new StringBuffer();
while ((strr=bufferedReader.readLine())!=null) {
buffer.append(strr);
}
Log.d("tag", buffer.toString());
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}













}

你可能感兴趣的:(http通信doGet与doPost方式小例子)