与B项目进行交互,由于B项目一些原因,请求处理缓慢.A项目等待返回结果需要很久...现只需发送数据无需判断发送成功失败与否,求教如何操作???以下是发送get请求的代码
public static String doGet(String HTTP_URL, Object object) {
BufferedReader reader = null;
String result = null;
StringBuffer httpUrl = new StringBuffer(HTTP_URL);
StringBuffer sbf = new StringBuffer();
try {
System.out.println(httpUrl.toString());
URL url = new URL(httpUrl.toString());
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setDoInput(true);
// 请求方式设置 POST
connection.setRequestMethod("GET");
// 设置维持长连接
connection.setRequestProperty("Connection", "Keep-Alive");
// 设置文件字符集:
connection.setRequestProperty("Charset", "UTF-8");
// 开始连接请求
connection.connect();
OutputStream out = connection.getOutputStream();
out.write((object.toString()).getBytes());
out.flush();
out.close();
if (connection.getResponseCode() == 200) {
System.out.println("连接成功,传送数据...");
InputStream is = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
String strRead = null;
while ((strRead = reader.readLine()) != null) {
sbf.append(strRead);
sbf.append("\r\n");
}
reader.close();
result = sbf.toString();
if (result.equals("1")) {
return "1";
} else if(result.equals("0")) {
return "0";
} else {
return result;
}
} else {
System.out.println("连接失败,错误代码:"+connection.getResponseCode());
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
2 回答
侃侃无极
TA贡献2051条经验 获得超10个赞
public static String doGet(String HTTP_URL, Object object) {
BufferedReader reader = null;
String result = null;
StringBuffer httpUrl = new StringBuffer(HTTP_URL);
StringBuffer sbf = new StringBuffer();
try {
System.out.println(httpUrl.toString());
URL url = new URL(httpUrl.toString());
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setDoInput(true);
// 请求方式设置 POST
connection.setRequestMethod("POST");
// 设置文件字符集:
connection.setRequestProperty("Charset", "UTF-8");
// 开始连接请求
connection.connect();
OutputStream out = connection.getOutputStream();
out.write((object.toString()).getBytes());
out.flush();
out.close();
if (connection.getResponseCode() == 200) {
System.out.println("连接成功,传送数据...");
} else {
System.out.println("连接失败,错误代码:"+connection.getResponseCode());
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
添加回答
举报
0/150
提交
取消