class ExecuteTask extends AsyncTask<String, String, String> {
//网址
public static final String SERVICEURL ="XXXXXXXX";
public static final int CONNECTION_TIMEOUT_INT = 1000;
public static final int READ_TIMEOUT_INT = 1000;
@Override
protected String doInBackground(String... object) {
String result = httpPost(object[0]);
return result;
}
public String httpPost(String object) {
String param = object;
if (param != null) {
URL url = null;
try {
url = new URL(SERVICEURL);
HttpURLConnection urlConn = (HttpURLConnection) url
.openConnection();
urlConn.setDoInput(true); // 设置输入流采用字节流
urlConn.setDoOutput(true); // 设置输出流采用字节流
urlConn.setRequestMethod("POST");
urlConn.setUseCaches(false); // 设置缓存
urlConn.setRequestProperty("Charset", "utf-8");
urlConn.setConnectTimeout(CONNECTION_TIMEOUT_INT);
urlConn.setReadTimeout(READ_TIMEOUT_INT);
urlConn.connect(); // 连接既往服务端发送消息
DataOutputStream dop = new DataOutputStream(
urlConn.getOutputStream());
dop.write(param.getBytes("utf-8")); // 发送参数
dop.flush(); // 发送,清空缓存
dop.close(); // 关闭
String result = ""; // 获取服务器返回数据
if (urlConn.getResponseCode() == 200) {
// 下面开始做接收工作
BufferedReader bufferReader = new BufferedReader(
new InputStreamReader(urlConn.getInputStream(), "utf-8"));
String readLine = null;
while ((readLine = bufferReader.readLine()) != null) {
result += readLine;
}
bufferReader.close();
} else {
System.out.println("连接超时 ");
}
urlConn.disconnect();
System.out.println("result: " + result);
return result;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
} else {
System.out.println("param is null");
}
return null;
}
@Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
regResult(result);
}
}
异步线程post请求(支持json ,vo,字符串)
最新推荐文章于 2023-10-31 23:21:49 发布