httpurlconnection 怎么访问远程接口

HttpURLConnection(访问网络)
package&com.example.lyftools.&&&&import&java.io.BufferedInputS&&import&java.io.BufferedOutputS&&import&java.io.IOE&&import&java.io.InputS&&import&java.net.HttpURLC&&import&java.net.URL;&&&&public&class&HttpURLConnHelper&{&&&&&&/**&&&&&&*&作用:实现网络访问文件,将获取到数据储存在文件流中&&&&&&*&&&&&&&*&@param&url&&&&&&*&&&&&&&&&&&&:访问网络的url地址&&&&&&*&@return&inputstream&&&&&&*/&&&&&&public&static&InputStream&loadFileFromURL(String&url)&{&&&&&&&&&&URL&urlO&&&&&&&&&&BufferedInputStream&bis&=&&&&&&&&&&&HttpURLConnection&httpConn&=&&&&&&&&&&&try&{&&&&&&&&&&&&&&//&创建url对象&&&&&&&&&&&&&&urlObj&=&new&URL(url);&&&&&&&&&&&&&&//&创建HttpURLConnection对象,通过这个对象打开跟远程服务器之间的连接&&&&&&&&&&&&&&httpConn&=&(HttpURLConnection)&urlObj.openConnection();&&&&&&&&&&&&&&&&//&判断跟服务器的连接状态。如果是200,则说明连接正常,服务器有响应&&&&&&&&&&&&&&if&(httpConn.getResponseCode()&==&200)&{&&&&&&&&&&&&&&&&&&//&服务器有响应后,会将访问的url页面中的内容放进inputStream中,使用httpConn就可以获取到这个字节流&&&&&&&&&&&&&&&&&&bis&=&new&BufferedInputStream(httpConn.getInputStream());&&&&&&&&&&&&&&&&&&return&&&&&&&&&&&&&&&}&&&&&&&&&&}&catch&(Exception&e)&{&&&&&&&&&&&&&&e.printStackTrace();&&&&&&&&&&}&finally&{&&&&&&&&&&&&&&try&{&&&&&&&&&&&&&&&&&&//&对流对象进行关闭,对Http连接对象进行关闭。以便释放资源。&&&&&&&&&&&&&&&&&&bis.close();&&&&&&&&&&&&&&&&&&httpConn.disconnect();&&&&&&&&&&&&&&}&catch&(IOException&e)&{&&&&&&&&&&&&&&&&&&e.printStackTrace();&&&&&&&&&&&&&&}&&&&&&&&&&&&}&&&&&&&&&&return&&&&&&&}&&&&&&&&/**&&&&&&*&作用:实现网络访问文件,将获取到的数据存在字节数组中&&&&&&*&&&&&&&*&@param&url&&&&&&*&&&&&&&&&&&&:访问网络的url地址&&&&&&*&@return&byte[]&&&&&&*/&&&&&&public&static&byte[]&loadByteFromURL(String&url)&{&&&&&&&&&&HttpURLConnection&httpConn&=&&&&&&&&&&&BufferedInputStream&bis&=&&&&&&&&&&&try&{&&&&&&&&&&&&&&URL&urlObj&=&new&URL(url);&&&&&&&&&&&&&&httpConn&=&(HttpURLConnection)&urlObj.openConnection();&&&&&&&&&&&&&&//&httpConn.setRequestMethod("GET");&&&&&&&&&&&&&&//&httpConn.setDoInput(true);&&&&&&&&&&&&&&&&if&(httpConn.getResponseCode()&==&200)&{&&&&&&&&&&&&&&&&&&bis&=&new&BufferedInputStream(httpConn.getInputStream());&&&&&&&&&&&&&&&&&&return&MyIOHelper.streamToByte(bis);&&&&&&&&&&&&&&}&&&&&&&&&&}&catch&(Exception&e)&{&&&&&&&&&&&&&&e.printStackTrace();&&&&&&&&&&}&finally&{&&&&&&&&&&&&&&try&{&&&&&&&&&&&&&&&&&&bis.close();&&&&&&&&&&&&&&&&&&httpConn.disconnect();&&&&&&&&&&&&&&}&catch&(IOException&e)&{&&&&&&&&&&&&&&&&&&e.printStackTrace();&&&&&&&&&&&&&&}&&&&&&&&&&}&&&&&&&&&&return&&&&&&&}&&&&&&&&/**&&&&&&*&作用:实现网络访问文件,先给服务器通过“POST”方式提交数据,再返回相应的数据&&&&&&*&&&&&&&*&@param&url&&&&&&*&&&&&&&&&&&&:访问网络的url地址&&&&&&*&@param&params&&&&&&*&&&&&&&&&&&&:访问url时,需要传递给服务器的参数。格式为:username=wangxiangjun&password=abcde&&&&&&&*&&&&&&&&&&&&qq=&&&&&&*&&&&&&&&&&&&为了防止传中文参数时出现编码问题。采用URLEncoder.encode()对含中文的字符串进行编码处理。&&&&&&*&&&&&&&&&&&&服务器端会自动对进行过编码的字符串进行decode()解码。&&&&&&*&@return&byte[]&&&&&&*/&&&&&&public&static&byte[]&doPostSubmit(String&url,&String&params)&{&&&&&&&&&&BufferedOutputStream&bos&=&&&&&&&&&&&BufferedInputStream&bis&=&&&&&&&&&&&HttpURLConnection&httpConn&=&&&&&&&&&&&try&{&&&&&&&&&&&&&&URL&urlObj&=&new&URL(url);&&&&&&&&&&&&&&httpConn&=&(HttpURLConnection)&urlObj.openConnection();&&&&&&&&&&&&&&&&//&如果通过post方式给服务器传递数据,那么setDoOutput()必须设置为true。否则会异常。&&&&&&&&&&&&&&//&默认情况下setDoOutput()为false。&&&&&&&&&&&&&&//&其实也应该设置setDoInput(),但是因为setDoInput()默认为true。所以不一定要写。&&&&&&&&&&&&&&&&httpConn.setDoOutput(true);&&&&&&&&&&&&&&httpConn.setRequestMethod("POST");&&&&&&&&&&&&&&//&设置请求方式。请求方式有两种:POST/GET。注意要全大写。&&&&&&&&&&&&&&//&POST传递数据量大,数据更安全,地址栏中不会显示传输数据。&&&&&&&&&&&&&&//&而GET会将传输的数据暴露在地址栏中,传输的数据量大小有限制,相对POST不够安全。但是GET操作灵活简便。&&&&&&&&&&&&&&&&//&判断是否要往服务器传递参数。如果不传递参数,那么就没有必要使用输出流了。&&&&&&&&&&&&&&if&(params&!=&null)&{&&&&&&&&&&&&&&&&&&byte[]&data&=&params.getBytes();&&&&&&&&&&&&&&&&&&bos&=&new&BufferedOutputStream(httpConn.getOutputStream());&&&&&&&&&&&&&&&&&&bos.write(data);&&&&&&&&&&&&&&&&&&bos.flush();&&&&&&&&&&&&&&}&&&&&&&&&&&&&&//&判断访问网络的连接状态&&&&&&&&&&&&&&if&(httpConn.getResponseCode()&==&200)&{&&&&&&&&&&&&&&&&&&bis&=&new&BufferedInputStream(httpConn.getInputStream());&&&&&&&&&&&&&&&&&&//&将获取到的输入流转成字节数组&&&&&&&&&&&&&&&&&&return&MyIOHelper.streamToByte(bis);&&&&&&&&&&&&&&}&&&&&&&&&&}&catch&(Exception&e)&{&&&&&&&&&&&&&&e.printStackTrace();&&&&&&&&&&}&finally&{&&&&&&&&&&&&&&try&{&&&&&&&&&&&&&&&&&&if&(bis&!=&null)&{&&&&&&&&&&&&&&&&&&&&&&bis.close();&&&&&&&&&&&&&&&&&&}&&&&&&&&&&&&&&&&&&if&(bos&!=&null)&{&&&&&&&&&&&&&&&&&&&&&&bos.close();&&&&&&&&&&&&&&&&&&}&&&&&&&&&&&&&&&&&&httpConn.disconnect();&&&&&&&&&&&&&&}&catch&(IOException&e)&{&&&&&&&&&&&&&&&&&&e.printStackTrace();&&&&&&&&&&&&&&}&&&&&&&&&&&&}&&&&&&&&&&return&&&&&&&}&&}&&
TA的最新馆藏java HttpUrlConnection get和post 模拟请求 调用接口 - 博客频道 - CSDN.NET
分类:java
java模拟请求主要有两种比较常用的方法,而且简单:
一)HttpUrlConnection
主要有get和post的方式,其他就不贴出来了
不难发现,get和post请求大部分代码是一样的,post只是多了一步将参数写入流,其他配置都是一样的配
import java.io.BufferedR
import java.io.ByteArrayOutputS
import java.io.IOE
import java.io.InputS
import java.io.InputStreamR
import java.io.UnsupportedEncodingE
import java.net.HttpURLC
import java.net.MalformedURLE
import java.net.URL;
public class Test {
public static void main(String[] args) throws IllegalStateException, IOException {
urlConnection();
// 通过HttpUrlConnection的方式发送get请求
public static void doGet() throws IllegalStateException, IOException {
// 创建连接
URL url = new URL(&http://127.0.0.1:8080/Text?idfa=A49A2D7A-1D13-4671-A1AC-4CF69A70&);//请求地址
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setRequestMethod(&GET&);//这里是请求方式 ,或者&POST&
connection.setUseCaches(false);
// URLConnection.setInstanceFollowRedirects是成员函数,仅作用于当前函数
connection.setInstanceFollowRedirects(false);
&span style=&white-space:pre&&
&/span&connection.setRequestProperty(&Content-Type&, &application/x-www-form-urlencoded&);//content-Type要根据目标接口的类型填,常用就&form&
connection.connect();
// 读取响应
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String result = ConvertStream2Json(connection.getInputStream());
System.out.println(result);
reader.close();
// 断开连接
connection.disconnect();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
// 通过HttpUrlConnection的方式发送Post请求
@SuppressWarnings(&unused&)
public static void doPost() throws IllegalStateException, IOException {
// 创建连接
URL url = new URL(&http://127.0.0.1:8080/Text&);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setRequestMethod(&POST&);
connection.setUseCaches(false);
connection.setRequestProperty(&Content-Type&, &application/json&);//以json的方式传递参数
connection.setInstanceFollowRedirects(false);
connection.setConnectTimeout(2000);
connection.setReadTimeout(3000);
connection.setRequestProperty(&Charsert&, &UTF-8&);
connection.connect();
// POST请求
DataOutputStream out = new DataOutputStream(connection.getOutputStream());
out.write(&{\&name\&,\&admin\&}&.getBytes(&UTF-8&));//参数需要json格式(其实就是一个字符串)
out.flush();
out.close();
// 读取响应
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String result = ConvertStream2Json(connection.getInputStream());
System.out.println(result);
reader.close();
// 断开连接
connection.disconnect();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
* 将流转换成String
* @param inputStream
private static String ConvertStream2Json(InputStream inputStream) {
String jsonStr = &&;
// ByteArrayOutputStream相当于内存输出流
ByteArrayOutputStream out = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len = 0;
// 将输入流转移到内存输出流中
while ((len = inputStream.read(buffer, 0, buffer.length)) != -1) {
out.write(buffer, 0, len);
// 将内存流转换为字符串
jsonStr = new String(out.toByteArray());
} catch (IOException e) {
e.printStackTrace();
return jsonS
hongtu1993
排名:千里之外
(6)(2)(6)(0)(0)(1)(1)(0)(3)(1)(1)(4)(1)(1)}

我要回帖

更多推荐

版权声明:文章内容来源于网络,版权归原作者所有,如有侵权请点击这里与我们联系,我们将及时删除。

点击添加站长微信