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的服务端,文件 ...
随机推荐
- stringstream用法
stringstream用法 1.头文件:#include<sstream> 2.stringstream是C++提供的串流(stream)物件,其中: clear()重置流的标志状态:s ...
- 008-MySQL报错-Access denied for user 'root'@'localhost' (using password: NO)
1.新安装的mysql报错 MySQL报错-Access denied for user 'root'@'localhost' (using password: NO) 解决方案 1.先停掉原来的服务 ...
- 转 ORA-16191 "Primary log shipping client not logged on standby
###sample 0 原因未知: 解决办法,重建密码文件 primary db :alter system set log_archive_dest_state_2=defer sid='*' sc ...
- How to Plan and Configure YARN and MapReduce 2 in HDP 2.0
As part of HDP 2.0 Beta, YARN takes the resource management capabilities that were in MapReduce and ...
- spring 使用Spring表达式(Spring EL)
Spring还提供了更灵活的注入方式,那就是Spring表达式,实际上Spring EL远比以上注入方式强大,我们需要学习它.Spring EL拥有很多功能. 使用Bean的id来引用Bean. •调 ...
- C#图片水印类
这个是学习用的呃,主要看一下水印在修改图片中距左边的宽度和高度是杂弄的就哦客了. using System; using System.Collections.Generic; using Syste ...
- npm 安装 -D 和-S的区别
-D 是在开发环境中协助开发需要使用的-S是生产环境打包时需要的,在package.json中 -D在devDependencies对象中,-S在dependencies对象中
- 单元测试-测试技术(Unit Test)
1.1白盒测试和单元测试的区别的论述: 1) 单元测试和白盒测试是不同的,虽然单元测试和白盒测试都是关注功能,虽然他们都需要代码支持,但是级别不同, 白盒测试关注的是类中一个方法的功能是更小的单位,但 ...
- 安装 KVM
安装 KVM 需要的包 sudo apt-get install -y qemu-kvm qemu-system libvirt-bin virt-manager bridge-utils vlan ...
- nginx 配置参数详细说明
#定义Nginx运行的用户和用户组 user www www; # #nginx进程数,建议设置为等于CPU总核心数. worker_processes 8; # #全局错误日志定义类型,[ debu ...