java请求http接口的简单介绍

博主:adminadmin 2023-03-18 10:31:09 471

本篇文章给大家谈谈java请求http接口,以及对应的知识点,希望对各位有所帮助,不要忘了收藏本站喔。

本文目录一览:

java调用http接口 get 接口的url怎么解决

Http请求类

package wzh.Http;

import java.io.BufferedReader;

import java.io.IOException;

import java.io.InputStreamReader;

import java.io.PrintWriter;

import java.net.URL;

import java.net.URLConnection;

import java.util.List;

import java.util.Map;

public class HttpRequest {

    /**

     * 向指定URL发送GET方法的请求

     * 

     * @param url

     *            发送请求的URL

     * @param param

     *            请求参数,请求参数应该是 name1=value1name2=value2 的形式。

     * @return URL 所代表远程资源的响应结果

     */

    public static String sendGet(String url, String param) {

        String result = "";

        BufferedReader in = null;

        try {

            String urlNameString = url + "?" + param;

            URL realUrl = new URL(urlNameString);

            // 打开和URL之间的连接

            URLConnection connection = realUrl.openConnection();

            // 设置通用的请求属性

            connection.setRequestProperty("accept", "*/*");

            connection.setRequestProperty("connection", "Keep-Alive");

            connection.setRequestProperty("user-agent",

                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");

            // 建立实际的连接

            connection.connect();

            // 获取所有响应头字段

            MapString, ListString map = connection.getHeaderFields();

            // 遍历所有的响应头字段

            for (String key : map.keySet()) {

                System.out.println(key + "---" + map.get(key));

            }

            // 定义 BufferedReader输入流来读取URL的响应

            in = new BufferedReader(new InputStreamReader(

                    connection.getInputStream()));

            String line;

            while ((line = in.readLine()) != null) {

                result += line;

            }

        } catch (Exception e) {

            System.out.println("发送GET请求出现异常!" + e);

            e.printStackTrace();

        }

        // 使用finally块来关闭输入流

        finally {

            try {

                if (in != null) {

                    in.close();

                }

            } catch (Exception e2) {

                e2.printStackTrace();

            }

        }

        return result;

    }

    /**

     * 向指定 URL 发送POST方法的请求

     * 

     * @param url

     *            发送请求的 URL

     * @param param

     *            请求参数,请求参数应该是 name1=value1name2=value2 的形式。

     * @return 所代表远程资源的响应结果

     */

    public static String sendPost(String url, String param) {

        PrintWriter out = null;

        BufferedReader in = null;

        String result = "";

        try {

            URL realUrl = new URL(url);

            // 打开和URL之间的连接

            URLConnection conn = realUrl.openConnection();

            // 设置通用的请求属性

            conn.setRequestProperty("accept", "*/*");

            conn.setRequestProperty("connection", "Keep-Alive");

            conn.setRequestProperty("user-agent",

                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");

            // 发送POST请求必须设置如下两行

            conn.setDoOutput(true);

            conn.setDoInput(true);

            // 获取URLConnection对象对应的输出流

            out = new PrintWriter(conn.getOutputStream());

            // 发送请求参数

            out.print(param);

            // flush输出流的缓冲

            out.flush();

            // 定义BufferedReader输入流来读取URL的响应

            in = new BufferedReader(

                    new InputStreamReader(conn.getInputStream()));

            String line;

            while ((line = in.readLine()) != null) {

                result += line;

            }

        } catch (Exception e) {

            System.out.println("发送 POST 请求出现异常!"+e);

            e.printStackTrace();

        }

        //使用finally块来关闭输出流、输入流

        finally{

            try{

                if(out!=null){

                    out.close();

                }

                if(in!=null){

                    in.close();

                }

            }

            catch(IOException ex){

                ex.printStackTrace();

            }

        }

        return result;

    }    

}

 调用方法:

    public static void main(String[] args) {

        //发送 GET 请求

        String s=HttpRequest.sendGet("", "key=123v=456");

        System.out.println(s);

        

        //发送 POST 请求

        String sr=HttpRequest.sendPost("", "key=123v=456");

        System.out.println(sr);

    }

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\" ?documenttxcode101/txcodenetnumber100001/netnumber........./document";

response=HttpUtil.doHttpOutput(xml, "post");

JSONObject json= JSONObject.parseObject(response);

String retcode=json.getString("retcode");

调用这个类就能获得返回的参数。。over.

}

}

}

java http请求

可能是这个网站做了权限校验啥的吧,你在浏览器是先登录以后再请求的这个接口,但是你的JAVA客户端没有做登录,直接请求,被认为是非法请求,所以就不给你返回数据了

java如何调用对方http接口

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

        //构建HttpClient实例

        CloseableHttpClient httpclient = HttpClients.createDefault();        //设置请求超时时间

        RequestConfig requestConfig = RequestConfig.custom()                .setSocketTimeout(60000)                .setConnectTimeout(60000)                .setConnectionRequestTimeout(60000)                .build();        //指定POST请求

        HttpPost httppost = new HttpPost(url);

        httppost.setConfig(requestConfig);        //包装请求体

        ListNameValuePair params = new ArrayListNameValuePair();        params.addAll(content);

        HttpEntity request = new UrlEncodedFormEntity(params, "UTF-8");        //发送请求

        httppost.setEntity(request);

        CloseableHttpResponse httpResponse = httpclient.execute(httppost);        //读取响应

        HttpEntity entity = httpResponse.getEntity();        String result = null;        if (entity != null) {

            result = EntityUtils.toString(entity, "UTF-8");

        }

如何用Java通过POST方法向HTTP接口传递数据?

这是corejava2的例子\x0d\x0aURLConnectionconnection=url.openConnection();//url为http服务器地址\x0d\x0aconnection.setDoOutput(true);\x0d\x0aPrintWriterout\x0d\x0a=newPrintWriter(connection.getOutputStream());//获得输出流\x0d\x0a//向服务器传递参数\x0d\x0aEnumerationenum=nameValuePairs.keys();\x0d\x0awhile(enum.hasMoreElements())\x0d\x0a{Stringname=(String)enum.nextElement();\x0d\x0aStringvalue=nameValuePairs.getProperty(name);\x0d\x0acharch;\x0d\x0aif(enum.hasMoreElements())ch='';elsech='\n';\x0d\x0aout.print(name+"="\x0d\x0a+URLEncoder.encode(value)+ch);\x0d\x0aSystem.out.println(name+value);\x0d\x0a}\x0d\x0a\x0d\x0aout.close();\x0d\x0a//获取输入流\x0d\x0aBufferedReaderin;\x0d\x0atry\x0d\x0a{in=newBufferedReader(new\x0d\x0aInputStreamReader(connection.getInputStream()));\x0d\x0a}\x0d\x0acatch(FileNotFoundExceptionexception)\x0d\x0a{InputStreamerr\x0d\x0a=((HttpURLConnection)connection).getErrorStream();\x0d\x0aif(err==null)throwexception;\x0d\x0ain=newBufferedReader(newInputStreamReader(err));\x0d\x0a}\x0d\x0aStringBufferresponse=newStringBuffer();\x0d\x0aStringline;\x0d\x0a//读取数据\x0d\x0awhile((line=in.readLine())!=null)\x0d\x0aresponse.append(line+"\n");\x0d\x0a\x0d\x0ain.close();\x0d\x0areturnresponse.toString();\x0d\x0a}\x0d\x0a}

java请求接口后是否会关闭连接

java请求接口后不会关闭连接。根据查询相关公开信息:HTTP请求之后并不需要关闭TCP连接,可以使下次HTTP请求使用相同的TCP通道,节省TCP建立连接的时间,不会关闭连接。Java是一门面向对象编程语言,1990年代初由詹姆斯·高斯林等人开发出Java语言的雏形,最初被命名为Oak,后随着互联网的发展,经过对Oak的改造,1995年5月Java正式发布。Java具有简单性、面向对象、分布式、健壮性、安全性、平台独立与可移植性、多线程、动态性等特点。Java可以编写桌面应用程序、Web应用程序、分布式系统和嵌入式系统应用程序等。

java请求http接口的介绍就聊到这里吧,感谢你花时间阅读本站内容,更多关于、java请求http接口的信息别忘了在本站进行查找喔。