您的位置:首页 > 理论基础 > 计算机网络

使用URLConnection发送GET和POST请求的简单示例

2015-12-08 17:20 543 查看
Get请求
import java.net.URLConnection;

public class HttpGet {
public static void main(String[] args) throws Exception {
final String spec = "http://192.168.0.115:20000/test/test.json?item=123";

URL url = new URL(spec);
URLConnection connection = url.openConnection();
HttpURLConnection httpURLConnection = (HttpURLConnection) connection;

httpURLConnection.setRequestProperty("Accept-Charset", "utf-8");
httpURLConnection.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");

if (httpURLConnection.getResponseCode() == 200) {
try (BufferedReader reader = new BufferedReader(
new InputStreamReader(
httpURLConnection.getInputStream()))) {
String tempLine = null;
StringBuffer resultBuffer = new StringBuffer();
while ((tempLine = reader.readLine()) != null) {
resultBuffer.append(tempLine);
}
System.out.println(resultBuffer.toString());
}
}
}
}


POST请求
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

public class HttpPost {
public static void main(String[] args) throws Exception {
final String spec = "http://192.168.0.115:20000/test/test.json";

URL url = new URL(spec);
URLConnection connection = url.openConnection();
HttpURLConnection httpURLConnection = (HttpURLConnection) connection;

httpURLConnection.setRequestProperty("Accept-Charset", "utf-8");
httpURLConnection.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
connection.setDoOutput(true);

try (OutputStreamWriter outputStreamWriter = new OutputStreamWriter(
httpURLConnection.getOutputStream())) {
outputStreamWriter.write("item=123");
outputStreamWriter.flush();
}

Map<String, List<String>> headerFields = httpURLConnection.getHeaderFields();
for ( Entry<String, List<String>> entry : headerFields.entrySet()) {
System.out.println(entry.getKey());
for (String value : entry.getValue()) {
System.out.println("\t" + value);
}
}

if (httpURLConnection.getResponseCode() == 200) {
try (BufferedReader reader = new BufferedReader(
new InputStreamReader(
httpURLConnection.getInputStream()))) {
String tempLine = null;
StringBuffer resultBuffer = new StringBuffer();
while ((tempLine = reader.readLine()) != null) {
resultBuffer.append(tempLine);
}
System.out.println(resultBuffer.toString());
}
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  HTTP