概述
展开全部
更直接一点吧,用jdk自带的urlconnection来实现,无需依赖其他库。下边的e68a84e8a2ad3231313335323631343130323136353331333361313962示例实现了post和get方法。
示例如下:
Java代码
public class HttpUtil {
public static final String CHARSET = "UTF-8";
public static String post(String url, Map postParams) {
HttpURLConnection con = null;
OutputStream osw = null;
InputStream ins = null;
try {
con = (HttpURLConnection) new URL(url).openConnection();
con.setDoInput(true);
con.setRequestMethod("POST");
con.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
if (null != postParams) {
con.setDoOutput(true);
String postParam = encodeParameters(postParams);
byte[] bytes = postParam.getBytes(CHARSET);
con.setRequestProperty("Content-Length",
Integer.toString(bytes.length));
osw = con.getOutputStream();
osw.write(bytes);
osw.flush();
}
int resCode = con.getResponseCode();
if (resCode < 400) {
ins = con.getInputStream();
} else {
ins = con.getErrorStream();
}
return readContent(ins);
} catch (IOException e) {
} finally {
try {
if (osw != null) {
osw.close();
}
if (ins != null) {
ins.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
public static String get(String url) {
HttpURLConnection con = null;
OutputStream osw = null;
InputStream ins = null;
try {
con = (HttpURLConnection) new URL(url).openConnection();
con.setRequestMethod("GET");
int resCode = con.getResponseCode();
if (resCode < 400) {
ins = con.getInputStream();
} else {
ins = con.getErrorStream();
}
return readContent(ins);
} catch (IOException e) {
} finally {
try {
if (osw != null) {
osw.close();
}
if (ins != null) {
ins.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
private static final String readContent(InputStream ins) throws IOException {
StringBuilder sb = new StringBuilder();
BufferedReader br = new BufferedReader(new InputStreamReader(ins,
HttpUtil.CHARSET));
if (ins != null) {
String line;
while ((line = br.readLine()) != null) {
sb.append(line);
}
}
return sb.toString();
}
public static String encodeParameters(Map postParams) {
StringBuilder buf = new StringBuilder();
if (postParams != null && postParams.size() > 0) {
for (Map.Entry tmp : postParams.entrySet()) {
try {
buf.append(URLEncoder.encode(tmp.getKey(), CHARSET))
.append("=")
.append(URLEncoder.encode(tmp.getValue(), CHARSET))
.append("&");
} catch (java.io.UnsupportedEncodingException neverHappen) {
}
}
buf.deleteCharAt(buf.length() - 1);
}
return buf.toString();
}
}
本回答由提问者推荐
已赞过
已踩过<
你对这个回答的评价是?
评论
收起
最后
以上就是闪闪中心为你收集整理的代替httpclient JAVA_除了HttpClient,Java还有什么类似HttpClient的技术的全部内容,希望文章能够帮你解决代替httpclient JAVA_除了HttpClient,Java还有什么类似HttpClient的技术所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
发表评论 取消回复