httpjava调用的简单介绍

博主:adminadmin 2022-11-26 13:29:07 43

本篇文章给大家谈谈httpjava调用,以及对应的知识点,希望对各位有所帮助,不要忘了收藏本站喔。

本文目录一览:

java http调用接口书写?

1、直接用servlet就可以了,request.getInputStream(),然后解析xml,然后你的业务操作,组装XML,response.getOutputStream()写出去就OK了4但这个性能低,而且还要依赖web容器imq2、socket实现http协议,把HTTP协议好好看看,自己解析(其实就是字符串的操作哦)。3、你要是只做客户端的话可以用httpClient284几行代码搞定了

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接口 新手虚心求教

import java.io.BufferedReader;  

import java.io.DataOutputStream;  

import java.io.InputStreamReader;  

import java.net.HttpURLConnection;  

import java.net.URL;  

import java.net.URLEncoder;  

  

public class DemoTest1 {  

  

    public static final String GET_URL = "";  

//    public static final String POST_URL = "";  

    // 妙兜测试接口  

    public static final String POST_URL = "";  

      

    /** 

     * 接口调用 GET 

     */  

    public static void httpURLConectionGET() {  

        try {  

            URL url = new URL(GET_URL);    // 把字符串转换为URL请求地址  

            HttpURLConnection connection = (HttpURLConnection) url.openConnection();// 打开连接  

            connection.connect();// 连接会话  

            // 获取输入流  

            BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));  

            String line;  

            StringBuilder sb = new StringBuilder();  

            while ((line = br.readLine()) != null) {// 循环读取流  

                sb.append(line);  

            }  

            br.close();// 关闭流  

            connection.disconnect();// 断开连接  

            System.out.println(sb.toString());  

        } catch (Exception e) {  

            e.printStackTrace();  

            System.out.println("失败!");  

        }  

    }  

      

    /** 

     * 接口调用  POST 

     */  

    public static void httpURLConnectionPOST () {  

        try {  

            URL url = new URL(POST_URL);  

              

            // 将url 以 open方法返回的urlConnection  连接强转为HttpURLConnection连接  (标识一个url所引用的远程对象连接)  

            HttpURLConnection connection = (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-javascript text/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();  

              

            // 创建输入输出流,用于往连接里面输出携带的参数,(输出内容为?后面的内容)  

            DataOutputStream dataout = new DataOutputStream(connection.getOutputStream());  

              

            String app_key = "app_key="+ URLEncoder.encode("4f7bf8c8260124e6e9c6bf094951a111", "utf-8");        // 已修改【改为错误数据,以免信息泄露】  

            String agt_num = "agt_num="+ URLEncoder.encode("10111", "utf-8");              // 已修改【改为错误数据,以免信息泄露】  

            String pid = "pid="+ URLEncoder.encode("BLZXA150401111", "utf-8");             // 已修改【改为错误数据,以免信息泄露】  

            String departid = "departid="+ URLEncoder.encode("10007111", "utf-8");         // 已修改【改为错误数据,以免信息泄露】  

            String install_lock_name = "install_lock_name="+ URLEncoder.encode("南天大门", "utf-8");  

            String install_address = "install_address="+ URLEncoder.encode("北京育新", "utf-8");  

            String install_gps = "install_gps="+ URLEncoder.encode("116.350888,40.011001", "utf-8");  

            String install_work = "install_work="+ URLEncoder.encode("小李", "utf-8");  

            String install_telete = "install_telete="+ URLEncoder.encode("13000000000", "utf-8");  

            String intall_comm = "intall_comm="+ URLEncoder.encode("一切正常", "utf-8");  

              

            // 格式 parm = aaa=111bbb=222ccc=333ddd=444  

            String parm = 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)  

            BufferedReader bf = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));   

            String line;  

            StringBuilder sb = new StringBuilder(); // 用来存储响应数据  

              

            // 循环读取流,若不到结尾处  

            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 (Exception e) {  

            e.printStackTrace();  

        }  

    }  

      

    public static void main(String[] args) {  

//        httpURLConectionGET();  

        httpURLConnectionPOST();  

    }  

}

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");

        }

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

The End

发布于:2022-11-26,除非注明,否则均为首码项目网原创文章,转载请注明出处。