欢迎来到代码驿站!

JAVA代码

当前位置:首页 > 软件编程 > JAVA代码

java以json格式向后台服务器接口发送请求的实例

时间:2021-05-13 08:12:24|栏目:JAVA代码|点击:

代码如下:

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

import net.sf.json.JSONObject;
public class InterfaceRequest {
	//模拟向腾讯云发送接口
	//接口
	private final static String URL = "https://console.tim.qq.com/v4/im_open_login_svc/account_import?";
	
	
	
	
	/**
	 * @param args
	 * @throws IOException 
	 */
	public static void main(String[] args) throws IOException {
		// TODO Auto-generated method stub
		//连接服务器
		HttpURLConnection connection = connection(URL);
	
		DataOutputStream out = new DataOutputStream(
				connection.getOutputStream());
		
		JSONObject obj = new JSONObject();
		
    obj.element("Identifier", "hehe");
		System.out.println(obj.toString());
	
		// 向腾讯请求传入编码为UTF-8格式的json数据
		out.write(obj.toString().getBytes("UTF-8"));
		
	
		out.flush();
		out.close();
		//获得服务器返回的结果
		BufferedReader reader = new BufferedReader(new InputStreamReader(
				connection.getInputStream()));
		String lines;
		StringBuffer sb = new StringBuffer("");
		while ((lines = reader.readLine()) != null) {
			lines = new String(lines.getBytes(), "utf-8");
			sb.append(lines);
		}
	
		reader.close();
		
		
		
		
	}
	
	public static HttpURLConnection connection(String URL
			) throws IOException {
		URL url = new URL(URL);
		HttpURLConnection connection = (HttpURLConnection) url.openConnection();
		connection.setDoOutput(true);
		connection.setDoInput(true);
		connection.setRequestMethod("POST");
		connection.setUseCaches(false);
		connection.setInstanceFollowRedirects(true);
		connection.setRequestProperty("Content-Type",
				"application/x-www-form-urlencoded;charset=UTF-8");
		connection.connect();
		return connection;
		// TODO Auto-generated method stub
	}
}

上一篇:Java反射机制用法总结

栏    目:JAVA代码

下一篇:SpringMVC访问静态资源的三种方式小结

本文标题:java以json格式向后台服务器接口发送请求的实例

本文地址:http://www.codeinn.net/misctech/120367.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有