JSONObject和URL以及HttpURLConnection的使用
1 将java对象类转成json格式
首先引入依赖jar文件
注意依赖文件的版本号,高版本可能没有对应的类
2 我的实体类中包含内部类注意内部类要public才能被序列化成json格式
import java.util.List;
public class EuityParam {
public EuityParam(String filter,List<String> args)
{
super();
this.filter=new Param0(filter);
this.args=new Param1(args);
}
private Param1 args;
public Param1 getArgs()
{
return args;
}
public void setArgs(Param1 _Param1)
{
this.args=_Param1;
}
private Param0 filter;
public Param0 getFilter()
{
return filter;
}
public void setFilter(Param0 _param0)
{
this.filter=_param0;
}
public class Param1
{
public List<String> getNameList() {
return nameList;
}
public void setNameList(List<String> nameList) {
this.nameList = nameList;
}
public Param1(List<String> nameList)
{
this.nameList=nameList;
}
private List<String> nameList;
}
public class Param0
{
public Param0(String key)
{
this.key=key;
}
private String key;
public String getKey()
{
return key;
}
public void setKey(String key)
{
this.key=key;
}
}
}
3 导入包文件
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
4 序列化
List<String> nameLst=new LinkedList<String>();
nameLst.add("AIR PRODUCTS & CHEMICALS INC");
nameLst.add("AMAZON.COM INC");
nameLst.add("ALTRIA GROUP INC");
nameLst.add("APPLE INC");
nameLst.add("ALPHABET INC");
EuityParam euityParam=new EuityParam("EquityNameMatching", nameLst); JSONObject jsonData= JSONObject.fromObject(euityParam);
System.out.println(jsonData);
5 结果:
{
"args": {
"nameList": [
"AIR PRODUCTS & CHEMICALS INC",
"AMAZON.COM INC",
"ALTRIA GROUP INC",
"APPLE INC",
"ALPHABET INC"
]
},
"filter": {
"key": "EquityNameMatching"
}
}
6 接口的调用,这个调用是post
private static String doPost(URL url, Map<Object, Object> nameValuePairs, String userAgent, int redirescts)
throws IOException {
// TODO Auto-generated method stub
StringBuilder response = new StringBuilder();
// HttpURLConnection可以处理重定向
HttpURLConnection connect = (HttpURLConnection) url.openConnection();
if (userAgent != null) {
connect.setRequestProperty("Authorization", userAgent);//设置http请求头
}
if (redirescts >= 0) {
// 连接到服务器之前关闭自动重定向
connect.setFollowRedirects(false);
}
// 设置请求的输出流
connect.setDoOutput(true);
// 构建往请求body内写入请求数据的写入流
OutputStream out = connect.getOutputStream();
try (PrintWriter write = new PrintWriter(out)) {
boolean first = true;
for (Entry<Object, Object> pair : nameValuePairs.entrySet()) {
if (first) {
first = false;
} else {
write.print('&');
}
String name = pair.getKey().toString();
String value = pair.getValue().toString();
write.print(name);
write.print('=');
write.print(URLEncoder.encode(value, "UTF-8"));
}
} // 获取请求的编码类型
String encoding = connect.getContentEncoding();
if (encoding == null) {
encoding = "UTF-8";
} // 如果redirect大于0表明有重定向
if (redirescts > 0) {
// 获取请求的响应码
int responseCode = connect.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_MOVED_PERM || responseCode == HttpURLConnection.HTTP_MOVED_TEMP
|| responseCode == HttpURLConnection.HTTP_SEE_OTHER) { // 获取重定向的位置
String location = connect.getHeaderField("Location");
if (location != null) {
java.net.URL base = connect.getURL();
// 断开本次连接
connect.disconnect();
return doPost(new URL(base, location), nameValuePairs, userAgent, redirescts - 1);
}
}
} else if (redirescts == 0) {
throw new IOException("重定向太多无法处理");
} // 获取响应流
InputStream responseStream = connect.getInputStream();
try (Scanner in = new Scanner(responseStream, encoding)) {
while (in.hasNextLine()) {
response.append(in.nextLine());
response.append("\n");
}
}
catch (Exception e)
{
// TODO: handle exception
InputStream err = connect.getErrorStream();
if (err == null) {
throw e;
}
try (Scanner in = new Scanner(err)) {
response.append(in.hasNextLine()); }
}
return response.toString();
}
JSONObject和URL以及HttpURLConnection的使用的更多相关文章
- [02] URL和HttpURLConnection类
1.URL的概念 统一资源定位符URL(Uniform Resource Locator)是www客户机访问Internet时用来标识资源的名字和地址. URL的基本格式是: <METHOD&g ...
- 文件上传---普通文件fileupload.jar和url文件httpUrlConnection
文件上传---普通文件和url文件 主要用来学习使用common-fileupload.jar和java.net.httpURLConnection 普通文件: //上传xls文件到临时目录 if ( ...
- Url,HTTPUrlConnection(一)
package com.cmy.urlcon; import java.io.BufferedReader; import java.io.IOException; import java.io.In ...
- 一.HttpClient、JsonPath、JsonObject运用
HttpClient详细应用请参考官方api文档:http://hc.apache.org/httpcomponents-client-4.5.x/httpclient/apidocs/index.h ...
- AsyncTask异步加载和HttpURLConnection网络请求数据
//获得网络数据 private void huodeshuju() { //这里是使用线程,已注释掉 /*new Thread(){ public void ...
- HttpURLConnection从网上获取Json数据并解析详解
HttpURLConnection从网上获取Json数据并解析 1.HttpURLConnection请求数据的步骤 (1)构造一个URL接口地址: URL url = new URL("h ...
- HttpURLConnection实现两个服务端的对接
在企业开发中,很多时候需要用到两个服务端的对接,在java类中进行连接并传递参数,其中的HttpURLConnection是一种轻量化,并且简单的方法! package httptest; impor ...
- Java网络连接之HttpURLConnection、HttpsURLConnection
工具类包含两个方法: http请求.https请求 直接看代码: package com.jtools; import java.io.BufferedReader; import java.io.I ...
- HttpURLConnection 传输数据和下载图片
一.传输字符串数据 在Android中HttpURLConnection传输数据是必不可少的,我们继续在“AsyncTask(异步任务)”案例的基础上添加. 案例: 首先我们做一个jsp的服务端,文件 ...
随机推荐
- IMDB-WIKI – 500k+ face images with age and gender labels论文学习
DEX: Deep EXpectation of apparent age from a single image 这个论文我们使用深度学习解决了在静态人脸图像中面部年龄的估计.我们的卷积神经网络使用 ...
- 聚类K-Means和大数据集的Mini Batch K-Means算法
import numpy as np from sklearn.datasets import make_blobs from sklearn.cluster import KMeans from s ...
- python初级 1 内存和变量
一.回顾: 1.什么是程序 一堆指令的集合 2.回想一下猜数游戏程序的特征: 1)需要输入(input) 2)会处理输入(process) 3)产生输出(output) 二.程序的一般特征:输入.处理 ...
- LeetCode_217. Contains Duplicate
217. Contains Duplicate Easy Given an array of integers, find if the array contains any duplicates. ...
- 复习sql server 2000 MSDE2000 ,安装,打补丁,开1433端口。
前言: 由于工作需要,一个仍在使用的古董软件需要安装配置. 原有系统是在主机部署,单机安装sql2000,其他机器(分机)也单机部署软件,部署sql2000,通过dtsrun /f sync.dts( ...
- Java基础教程:多线程基础(5)——倒计时器(CountDownLatch)
Java基础教程:多线程基础(5)——倒计时器(CountDownLatch) 引入倒计时器 在多线程协作完成业务功能时,有时候需要等待其他多个线程完成任务之后,主线程才能继续往下执行业务功能,在这种 ...
- Python 的包管理工具 distribute, setuptools, easy_install命令与 pip命令
Setuptools 是 Python Enterprise Application Kit (PEAK)的一个副项目,它是 Python 的disutils工具的增强工具,可以让程序员更方便地创建和 ...
- windows系统中在jupyter安装虚拟环境内核
一.在jupyter中安装虚拟环境内核 1.创建Python3虚拟环境 参考本文其他博客 2.进入虚拟环境 3.安装jupyter pip install jupyter 4.添加当前环境到jupyt ...
- Qt5.编译错误.error: C2338: The slot requires more arguments than the signal provides.
1.Qt563x86vs2015,遇到如下 编译错误: error: C2338: The slot requires more arguments than the signal provides. ...
- top命令常用
top 使用时的命令: Ctrl+L擦除并且重写屏幕. h或者?显示帮助画面,给出一些简短的命令总结说明. k 终止一个进程.系统将提示用户输入需要终止的进程PID,以及需要发送给该进程什么样的信号. ...