Get 方式:
String result = null;
URL url = null;
HttpURLConnection connection = null;
InputStreamReader in = null;
private void sendRequestWithHttpClient(String url) {
new Thread(new Runnable() {
@Override
public void run() {
try {
url = new URL(url);
connection = (HttpURLConnection) url.openConnection();
in = new InputStreamReader(connection.getInputStream());
BufferedReader bufferedReader = new BufferedReader(in);
StringBuffer strBuffer = new StringBuffer();
String line = null;
while ((line = bufferedReader.readLine()) != null) {
strBuffer.append(line);
}
result = strBuffer.toString();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (connection != null) {
connection.disconnect();
}
if (in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}).start();
}
POST方式:
new Thread(
new Runnable() {
@Override
public void run() {
String json="{'UserID':'"+account+"','Authenticator':'"+value+"','TerminalFlag':8}";
postDownloadJson("http://xxx.xxxx",json);
}
}).start();
public String postDownloadJson(String path, String Json) {
String result = "";
BufferedReader reader = null;
HttpURLConnection conn=null;
try {
URL url = new URL(path);
conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setUseCaches(false);
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("Charset", "UTF-8");
// 设置文件类型:
conn.setRequestProperty("Content-Type","application/json; charset=UTF-8");
conn.setRequestProperty("accept","application/json");
// 往服务器里面发送数据
if (Json != null && !TextUtils.isEmpty(Json)) {
byte[] writebytes = Json.getBytes();
// 设置文件长度
conn.setRequestProperty("Content-Length", String.valueOf(writebytes.length));
OutputStream outwritestream = conn.getOutputStream();
outwritestream.write(Json.getBytes());
outwritestream.flush();
outwritestream.close();
}
if (conn.getResponseCode() == 200) {
reader = new BufferedReader(
new InputStreamReader(conn.getInputStream()));
result = reader.readLine();
}
Message msg=new Message();
msg.obj=result;
handler.sendMessage(msg);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return result;
}
Handler handler=new Handler(new Handler.Callback() {
@Override
public boolean handleMessage(Message msg) {
Toast.makeText(MainActivity.this,msg.obj+"",Toast.LENGTH_LONG).show();
return false;
}
});