private void httpRequest(){
new Thread(new Runnable() {
@Override
public void run() {
HttpURLConnection httpURLConnection=null;
BufferedReader bufferedReader=null;
try {
URL url=new URL("http://www.baidu.com");
httpURLConnection = (HttpURLConnection)url.openConnection();
httpURLConnection.setRequestMethod("GET");
httpURLConnection.setReadTimeout(8000);
httpURLConnection.setConnectTimeout(8000);
InputStream inputStream=httpURLConnection.getInputStream();
bufferedReader=new BufferedReader(new InputStreamReader(inputStream));
StringBuilder stringBuilder=new StringBuilder();
String line="";
while ((line=bufferedReader.readLine())!=null){
stringBuilder.append(line);
}
showResponse(stringBuilder.toString());
//下面是POST模式
//httpURLConnection.setRequestMethod("POST");
//DataOutputStream out = new DataOutputStream(httpURLConnection.getOutputStream());
//out.writeBytes("user=admin&password=123456");
} catch (IOException e) {
e.printStackTrace();
}finally {
if(httpURLConnection!=null){
httpURLConnection.disconnect();
}
if(bufferedReader!=null){
try {
bufferedReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}).start();
}
private void showResponse(final String outputString){
runOnUiThread(new Runnable() {
@Override
public void run() {
responseText.setText(outputString);
}
});
}
Android HttpURLConnection GET POST
最新推荐文章于 2024-05-09 17:47:45 发布