导航:首页 > 编程语言 > java访问http

java访问http

发布时间:2022-08-11 13:01:20

1. java 怎么实现HTTP的POST方式通讯,以及HTTPS方式传递

虽然在 JDK 的 java.net 包中已经提供了访问 HTTP 协议的基本功能,但是对于大部分应用程序来说,JDK
库本身提供的功能还不够丰富和灵活。HttpClient 是 Apache Jakarta Common
下的子项目,用来提供高效的、最新的、功能丰富的支持 HTTP 协议的客户端编程工具包,并且它支持 HTTP 协议最新的版本和建议。以下是简单的post例子:
String url = "http://www.newsmth.net/bbslogin2.php";
PostMethod postMethod = new PostMethod(url);
// 填入各个表单域的值
NameValuePair[] data = { new NameValuePair("id", "youUserName"),
new NameValuePair("passwd", "yourPwd") };
// 将表单的值放入postMethod中
postMethod.setRequestBody(data);
// 执行postMethod
int statusCode = httpClient.executeMethod(postMethod);
// HttpClient对于要求接受后继服务的请求,象POST和PUT等不能自动处理转发
// 301或者302
if (statusCode == HttpStatus.SC_MOVED_PERMANENTLY ||
statusCode == HttpStatus.SC_MOVED_TEMPORARILY) {
// 从头中取出转向的地址
Header locationHeader = postMethod.getResponseHeader("location");
String location = null;
if (locationHeader != null) {
location = locationHeader.getValue();
System.out.println("The page was redirected to:" + location);
} else {
System.err.println("Location field value is null.");
}
return;
}

2. java如何调用对方http接口 新手虚心求教

importjava.io.BufferedReader;
importjava.io.DataOutputStream;
importjava.io.InputStreamReader;
importjava.net.HttpURLConnection;
importjava.net.URL;
importjava.net.URLEncoder;

publicclassDemoTest1{

publicstaticfinalStringGET_URL="http://112.4.27.9/mall-back/if_user/store_list?storeId=32";
//publicstaticfinalStringPOST_URL="http://112.4.27.9/mall-back/if_user/store_list";
//妙兜测试接口
publicstaticfinalStringPOST_URL="http://121.40.204.191:8180/mdserver/service/installLock";

/**
*接口调用GET
*/
(){
try{
URLurl=newURL(GET_URL);//把字符串转换为URL请求地址
HttpURLConnectionconnection=(HttpURLConnection)url.openConnection();//打开连接
connection.connect();//连接会话
//获取输入流
BufferedReaderbr=newBufferedReader(newInputStreamReader(connection.getInputStream(),"UTF-8"));
Stringline;
StringBuildersb=newStringBuilder();
while((line=br.readLine())!=null){//循环读取流
sb.append(line);
}
br.close();//关闭流
connection.disconnect();//断开连接
System.out.println(sb.toString());
}catch(Exceptione){
e.printStackTrace();
System.out.println("失败!");
}
}

/**
*接口调用POST
*/
(){
try{
URLurl=newURL(POST_URL);

//将url以open方法返回的urlConnection连接强转为HttpURLConnection连接(标识一个url所引用的远程对象连接)
HttpURLConnectionconnection=(HttpURLConnection)url.openConnection();//此时cnnection只是为一个连接对象,待连接中

//设置连接输出流为true,默认false(post请求是以流的方式隐式的传递参数)
connection.setDoOutput(true);

//设置连接输入流为true
connection.setDoInput(true);

//设置请求方式为post
connection.setRequestMethod("POST");

//post请求缓存设为false
connection.setUseCaches(false);

//设置该HttpURLConnection实例是否自动执行重定向
connection.setInstanceFollowRedirects(true);

//设置请求头里面的各个属性(以下为设置内容的类型,设置为经过urlEncoded编码过的from参数)
//application/x-javascripttext/xml->xml数据application/x-javascript->json对象application/x-www-form-urlencoded->表单数据
//;charset=utf-8必须要,不然妙兜那边会出现乱码【★★★★★】
connection.setRequestProperty("Content-Type","application/x-www-form-urlencoded;charset=utf-8");

//建立连接(请求未开始,直到connection.getInputStream()方法调用时才发起,以上各个参数设置需在此方法之前进行)
connection.connect();

//创建输入输出流,用于往连接里面输出携带的参数,(输出内容为?后面的内容)
DataOutputStreamdataout=newDataOutputStream(connection.getOutputStream());

Stringapp_key="app_key="+URLEncoder.encode("","utf-8");//已修改【改为错误数据,以免信息泄露】
Stringagt_num="&agt_num="+URLEncoder.encode("10111","utf-8");//已修改【改为错误数据,以免信息泄露】
Stringpid="&pid="+URLEncoder.encode("BLZXA150401111","utf-8");//已修改【改为错误数据,以免信息泄露】
Stringdepartid="&departid="+URLEncoder.encode("10007111","utf-8");//已修改【改为错误数据,以免信息泄露】
Stringinstall_lock_name="&install_lock_name="+URLEncoder.encode("南天大门","utf-8");
Stringinstall_address="&install_address="+URLEncoder.encode("北京育新","utf-8");
Stringinstall_gps="&install_gps="+URLEncoder.encode("116.350888,40.011001","utf-8");
Stringinstall_work="&install_work="+URLEncoder.encode("小李","utf-8");
Stringinstall_telete="&install_telete="+URLEncoder.encode("13000000000","utf-8");
Stringintall_comm="&intall_comm="+URLEncoder.encode("一切正常","utf-8");

//格式parm=aaa=111&bbb=222&ccc=333&ddd=444
Stringparm=app_key+agt_num+pid+departid+install_lock_name+install_address+install_gps+install_work+install_telete+intall_comm;

//将参数输出到连接
dataout.writeBytes(parm);

//输出完成后刷新并关闭流
dataout.flush();
dataout.close();//重要且易忽略步骤(关闭流,切记!)

//System.out.println(connection.getResponseCode());

//连接发起请求,处理服务器响应(从连接获取到输入流并包装为bufferedReader)
BufferedReaderbf=newBufferedReader(newInputStreamReader(connection.getInputStream(),"UTF-8"));
Stringline;
StringBuildersb=newStringBuilder();//用来存储响应数据

//循环读取流,若不到结尾处
while((line=bf.readLine())!=null){
//sb.append(bf.readLine());
sb.append(line).append(System.getProperty("line.separator"));
}
bf.close();//重要且易忽略步骤(关闭流,切记!)
connection.disconnect();//销毁连接
System.out.println(sb.toString());

}catch(Exceptione){
e.printStackTrace();
}
}

publicstaticvoidmain(String[]args){
//httpURLConectionGET();
httpURLConnectionPOST();
}
}

3. java 如何实现 http协议传输

Java 6 提供了一个轻量级的纯 Java Http 服务器的实现。下面是一个简单的例子:

public static void main(String[] args) throws Exception{
HttpServerProvider httpServerProvider = HttpServerProvider.provider();
InetSocketAddress addr = new InetSocketAddress(7778);
HttpServer httpServer = httpServerProvider.createHttpServer(addr, 1);
httpServer.createContext("/myapp/", new MyHttpHandler());
httpServer.setExecutor(null);
httpServer.start();
System.out.println("started");
}

static class MyHttpHandler implements HttpHandler{
public void handle(HttpExchange httpExchange) throws IOException {
String response = "Hello world!";
httpExchange.sendResponseHeaders(200, response.length());
OutputStream out = httpExchange.getResponseBody();
out.write(response.getBytes());
out.close();
}
}

然后,在浏览器中访问 http://localhost:7778/myapp/

4. 如何在java中发起http和https请求

1.写http请求方法
[java] view plain

//处理http请求 requestUrl为请求地址 requestMethod请求方式,值为"GET"或"POST"
public static String httpRequest(String requestUrl,String requestMethod,String outputStr){
StringBuffer buffer=null;
try{
URL url=new URL(requestUrl);
HttpURLConnection conn=(HttpURLConnection)url.openConnection();
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setRequestMethod(requestMethod);
conn.connect();
//往服务器端写内容 也就是发起http请求需要带的参数
if(null!=outputStr){
OutputStream os=conn.getOutputStream();
os.write(outputStr.getBytes("utf-8"));
os.close();
}
//读取服务器端返回的内容
InputStream is=conn.getInputStream();
InputStreamReader isr=new InputStreamReader(is,"utf-8");
BufferedReader br=new BufferedReader(isr);
buffer=new StringBuffer();
String line=null;
while((line=br.readLine())!=null){
buffer.append(line);
}
}catch(Exception e){
e.printStackTrace();
}
return buffer.toString();
}
2.测试。
[java] view plain

public static void main(String[] args){
String s=httpRequest("http://www.qq.com","GET",null);
System.out.println(s);
}
输出结果为www.qq.com的源代码,说明请求成功。
注:1).第一个参数url需要写全地址,即前边的http必须写上,不能只写www.qq.com这样的。

2).第二个参数是请求方式,一般接口调用会给出URL和请求方式说明。
3).第三个参数是我们在发起请求的时候传递参数到所要请求的服务器,要传递的参数也要看接口文档确定格式,一般是封装成json或xml.
4).返回内容是String类,但是一般是有格式的json或者xml。
二:发起https请求。
1.https是对链接加了安全证书SSL的,如果服务器中没有相关链接的SSL证书,它就不能够信任那个链接,也就不会访问到了。所以我们第一步是自定义一个信任管理器。自要实现自带的X509TrustManager接口就可以了。
[java] view plain

import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import javax.net.ssl.X509TrustManager;
public class MyX509TrustManager implements X509TrustManager {
@Override
public void checkClientTrusted(X509Certificate[] chain, String authType)
throws CertificateException {
// TODO Auto-generated method stub
}
@Override
public void checkServerTrusted(X509Certificate[] chain, String authType)
throws CertificateException {
// TODO Auto-generated method stub
}
@Override
public X509Certificate[] getAcceptedIssuers() {
// TODO Auto-generated method stub
return null;
}
}
注:1)需要的包都是java自带的,所以不用引入额外的包。
2.)可以看到里面的方法都是空的,当方法为空是默认为所有的链接都为安全,也就是所有的链接都能够访问到。当然这样有一定的安全风险,可以根据实际需要写入内容。

2.编写https请求方法。
[java] view plain

/*
* 处理https GET/POST请求
* 请求地址、请求方法、参数
* */
public static String httpsRequest(String requestUrl,String requestMethod,String outputStr){
StringBuffer buffer=null;
try{
//创建SSLContext
SSLContext sslContext=SSLContext.getInstance("SSL");
TrustManager[] tm={new MyX509TrustManager()};
//初始化
sslContext.init(null, tm, new java.security.SecureRandom());;
//获取SSLSocketFactory对象
SSLSocketFactory ssf=sslContext.getSocketFactory();
URL url=new URL(requestUrl);
HttpsURLConnection conn=(HttpsURLConnection)url.openConnection();
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setUseCaches(false);
conn.setRequestMethod(requestMethod);
//设置当前实例使用的SSLSoctetFactory
conn.setSSLSocketFactory(ssf);
conn.connect();
//往服务器端写内容
if(null!=outputStr){
OutputStream os=conn.getOutputStream();
os.write(outputStr.getBytes("utf-8"));
os.close();
}
//读取服务器端返回的内容
InputStream is=conn.getInputStream();
InputStreamReader isr=new InputStreamReader(is,"utf-8");
BufferedReader br=new BufferedReader(isr);
buffer=new StringBuffer();
String line=null;
while((line=br.readLine())!=null){
buffer.append(line);
}
}catch(Exception e){
e.printStackTrace();
}
return buffer.toString();
}
可见和http访问的方法类似,只是多了SSL的相关处理。
3.测试。先用http请求的方法访问,再用https的请求方法访问,进行对比。

http访问:
[java] view plain

public static void main(String[] args){
String s=httpRequest("https://kyfw.12306.cn/","GET",null);
System.out.println(s);
}
结果为:

https访问:

[java] view plain

public static void main(String[] args){
String s=httpsRequest("https://kyfw.12306.cn/","GET",null);
System.out.println(s);
}
结果为:

可见https的链接一定要进行SSL的验证或者过滤之后才能够访问。

三:https的另一种访问方式——导入服务端的安全证书。
1.下载需要访问的链接所需要的安全证书。https://kyfw.12306.cn/ 以这个网址为例。
1)在浏览器上访问https://kyfw.12306.cn/。

2)点击上图的那个打了×的锁查看证书。

3)选择复制到文件进行导出,我们把它导入到java项目所使用的jre的lib文件下的security文件夹中去,我的是这个路径。D:\Program Files (x86)\Java\jre8\lib\security

注:中间需要选导出格式,就选默认的就行,还需要命名,我命名的是12306.

2.打开cmd,进入到java项目所使用的jre的lib文件下的security目录。
3.在命令行输入 Keytool -import -alias 12306 -file 12306.cer -keystore cacerts
4.回车后会让输入口令,一般默认是changeit,输入时不显示,输入完直接按回车,会让确认是否信任该证书,输入y,就会提示导入成功。

5.导入成功后就能像请求http一样请求https了。

测试:
[java] view plain

public static void main(String[] args){
String s=httpRequest("https://kyfw.12306.cn/","GET",null);
System.out.println(s);
}
结果:
现在就可以用http的方法请求https了。
注:有时候这一步还是会出错,那可能是jre的版本不对,我们右键run as——run configurations,选择证书所在的jre之后再运行。

5. java双网卡怎么做http访问

用双网卡同时访问内外网暂时没有很完美的解决办法,因为存在路由冲突,毕竟有两个网关地址,现在可以试试下面的办法:
先来解决双网卡冲突的问题。可以通过改变路由地址表搞定。以你的单位用机为例,机器有两块网卡,接到两台路由器上:
内部网地址设置为192.168.1.110,子网掩码:255.255.255.0,网关:192.168.1.1
办公网地址:10.94.12.123,子网掩码:255.255.255.0,网关:10.94.12.254
如果按正常的设置方法设置每块网卡的IP地址和网关,再cmd下使用route print查看时会看到以0.0.0.0 0.0.0.0 开头的两个东西,即指向0.0.0.0的有两个网关,这样就会出现路由冲突,两个网络的访问存在困难。要实现同时访问两个网络就要用到route命令

6. java如何使用http方式调用第三方接口最好有代码~谢谢

星号是IP地址和端口号
public class HttpUtil {
private final static Log log = LogFactory.getLog(HttpUtil.class);
public static String doHttpOutput(String outputStr,String method) throws Exception {
Map map = new HashMap();
String URL = "http://****/interface/http.php" ;
String result = "";
InputStream is = null;
int len = 0;
int tmp = 0;

OutputStream output = null;
BufferedOutputStream objOutput = null;
String charSet = "gbk";
System.out.println("URL of fpcy request");
System.out.println("=============================");
System.out.println(URL);
System.out.println("=============================");
HttpURLConnection con = getConnection(URL);
try {
output = con.getOutputStream();
objOutput = new BufferedOutputStream(output);
objOutput.write(outputStr.getBytes(charSet));
objOutput.flush();
output.close();
objOutput.close();
int responseCode = con.getResponseCode();
if (responseCode == 200) {
is = con.getInputStream();
int dataLen = is.available();
int retry = 5;
while (dataLen == 0 && retry > 0) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
}
dataLen = is.available();
retry--;
log.info("未获取到任何数据,尝试重试,当前剩余次数" + retry);
}
log.info("获取到报文单位数据长度:" + dataLen);
byte[] bytes = new byte[dataLen];
while ((tmp = is.read()) != -1) {
bytes[len++] = (byte) tmp;
if (len == dataLen) {
dataLen = bytes.length + dataLen;
byte[] newbytes = new byte[dataLen];
for (int i = 0; i < bytes.length; i++) {
newbytes[i] = bytes[i];
}
bytes = newbytes;
}
}
result = new String(bytes, 0, len, charSet);
} else {
String responseMsg = "调用接口失败,返回错误信息:" + con.getResponseMessage() + "(" + responseCode + ")";
System.out.println(responseMsg);
throw new Exception(responseMsg);
}
} catch (IOException e2) {
log.error(e2.getMessage(), e2);
throw new Exception("接口连接超时!,请检查网络");
}
con.disconnect();
System.out.println("=============================");
System.out.println("Contents of fpcy response");
System.out.println("=============================");
System.out.println(result);
Thread.sleep(1000);
return result;
}
private static HttpURLConnection getConnection(String URL) throws Exception {
Map map = new HashMap();
int rTimeout = 15000;
int cTimeout = 15000;
String method = "";
method = "POST";
boolean useCache = false;
useCache = false;
HttpURLConnection con = null;
try {
con = (HttpURLConnection) new URL(URL).openConnection();
} catch (IOException e) {
log.error(e.getMessage(), e);
throw new Exception("URL不合法!");
}
try {
con.setRequestMethod(method);
} catch (ProtocolException e) {
log.error(e.getMessage(), e);
throw new Exception("通信协议不合法!");
}
con.setConnectTimeout(cTimeout);
con.setReadTimeout(rTimeout);
con.setUseCaches(useCache);
con.setDoInput(true);
con.setDoOutput(true);
log.info("当前连接信息: URL:" + URL + "," + "Method:" + method
+ ",ReadTimeout:" + rTimeout + ",ConnectTimeOut:" + cTimeout
+ ",UseCaches:" + useCache);
return con;
}

public static void main(String[] args) throws Exception {
String xml="<?xml version=\"1.0\" encoding=\"GBK\" ?><document><txcode>101</txcode><netnumber>100001</netnumber>.........</document>";

response=HttpUtil.doHttpOutput(xml, "post");
JSONObject json= JSONObject.parseObject(response);
String retcode=json.getString("retcode");
调用这个类就能获得返回的参数。。over.

}

}
}

7. java 接受http请求

使用servlet


public class Test extends HttpServlet {

private static final long serialVersionUID = 1L;

/**

* @see HttpServlet#HttpServlet()

*/

public Test() {

super();

// TODO Auto-generated constructor stub

}


/**

* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)

*/

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {//接收get请求

// 这里写你接收request请求后要处理的操作

}


/**

* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)

*/

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {//接收post请求

// 这里写你接收request请求后要处理的操作

}


}


8. java 怎么接收http请求

用servlet接收。
具体步骤是写一个类继承HttpServlet,如果是接收get请求就重写doGet(HttpServletRequest,HttpServletResponse),接收post就重写doPost(HttpServletRequest,HttpServletResponse),共同处理post和get就重写service(HttpServletRequest,HttpServletResponse)
其次在web.xml定义servlet标签,以及你这个servlet要处理的请求mapping
最后把项目部署在tomcat之类的web容器中即可。
如果使用框架的话就另当别论了,比如spring 的DispatcherServlet。当然你也可以自己写servlet。

9. java 怎么调用http接口

方法:只要New一个Map,然后把要传递的参数以键值对的形式存入Map即可。privatevoidExample(){Stringurl=地址;Mapparam=newHashMap();p.put("ParamName","ParamValue");Stringhtml=this.visitURL(url,param);}

10. java如何调用对方http接口

你是指发送http请求吗,可以使用Apache 的 HttpClient

//构建HttpClient实例
CloseableHttpClienthttpclient=HttpClients.createDefault();//设置请求超时时间
RequestConfigrequestConfig=RequestConfig.custom().setSocketTimeout(60000).setConnectTimeout(60000).setConnectionRequestTimeout(60000).build();//指定POST请求
HttpPosthttppost=newHttpPost(url);
httppost.setConfig(requestConfig);//包装请求体
List<NameValuePair>params=newArrayList<NameValuePair>();params.addAll(content);
HttpEntityrequest=newUrlEncodedFormEntity(params,"UTF-8");//发送请求
httppost.setEntity(request);
=httpclient.execute(httppost);//读取响应
HttpEntityentity=httpResponse.getEntity();Stringresult=null;if(entity!=null){
result=EntityUtils.toString(entity,"UTF-8");
}
阅读全文

与java访问http相关的资料

热点内容
超级命令的英文 浏览:781
做账为什么要用加密狗 浏览:583
考研群体怎么解压 浏览:156
linux修改命令提示符 浏览:224
圆圈里面k图标是什么app 浏览:59
pdf加空白页 浏览:945
linux服务器如何看网卡状态 浏览:316
解压新奇特视频 浏览:705
图书信息管理系统java 浏览:553
各种直线命令详解 浏览:863
程序员泪奔 浏览:147
素材怎么上传到服务器 浏览:516
android百度离线地图开发 浏览:191
web可视化编程软件 浏览:294
java笔试编程题 浏览:746
win11什么时候可以装安卓 浏览:564
java不写this 浏览:1001
云点播电影网php源码 浏览:97
pythonclass使用方法 浏览:226
移动加密软件去哪下载 浏览:294