HttpURLConnection 使用POST请求方式
代码语言:javascript复制 new Thread(new Runnable() {
@Override
public void run() {
intView();
}
}).start();
}
private void intView() {
try {
URL url = new URL(path);
try {
HttpURLConnection urlConn = (HttpURLConnection) url.openConnection(); // 创建一个HTTP连接
urlConn.setRequestMethod("POST"); // 指定使用POST请求方式
urlConn.setDoInput(true); // 向连接中写入数据
urlConn.setDoOutput(true); // 从连接中读取数据
urlConn.setUseCaches(false); // 禁止缓存
urlConn.setInstanceFollowRedirects(true); //自动执行HTTP重定向
urlConn.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded"); // 设置内容类型
DataOutputStream out = new DataOutputStream(
urlConn.getOutputStream()); // 获取输出流
String key = Utils.getContentKey(contentss).replace("gradle/","");
String Etag = Utils.getContentEtag(contentss);
Long Size = Utils.getContentSize(contentss);
String data = "name=" key "&Size=" Size "&Etag=" Etag;
out.writeBytes(data);//将要传递的数据写入数据输出流
out.flush(); //输出缓存
out.close(); //关闭数据输出流
if (urlConn.getResponseCode() == HttpURLConnection.HTTP_OK) { //判断是否响应成功
InputStreamReader in = new InputStreamReader(
urlConn.getInputStream()); // 获得读取的内容
BufferedReader buffer = new BufferedReader(in); // 获取输入流对象
String inputLine = null;
String resul = null;
while ((inputLine = buffer.readLine()) != null) { //通过循环逐行读取输入流中的内容
resul = inputLine;
System.out.println(resul);
}
in.close(); //关闭字符输入流
}
urlConn.disconnect(); //断开连接
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
} catch (IOException e) {
e.printStackTrace();
}
}