您的位置:首页 > 理论基础 > 计算机网络

通过json发送Http请求

2016-05-30 11:43 330 查看
package com.jusfoun;

public class StartReq {

private String path;
private String jobname;

public String getPath() {
return path;
}
public void setPath(String path) {
this.path = path;
}
public String getJobname() {
return jobname;
}
public void setJobname(String jobname) {
this.jobname = jobname;
}

}


package com.jusfoun;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import com.google.gson.Gson;
/**
* 发送http请求
* @author mengshanfeng
* @date 20160529
*/
public class KettleHttpPost {

private Gson gson = new Gson();//工具

private String startUrl = "http://192.168.172.221:8080/kettleWeb/startJob";
//private String startUrl = "http://192.168.172.221:8080/kettleWeb/stopJob";

public void startJob(StartReq req) throws IOException {
String json = gson.toJson(req);//转为json
//发送请求并获取结果
String result = doPost(startUrl, "data=" + json);
System.out.println(result);

}
public static void main(String[] args){

KettleHttpPost a = new KettleHttpPost();
StartReq req = new StartReq();
req.setPath("etl/");;
req.setJobname("job");

try {
a.startJob(req);
} catch (IOException e) {
e.printStackTrace();
}

}

private String doPost(String urlPath, String data) throws IOException {
StringBuilder sub = new StringBuilder();
System.out.println("调用kettle服务:urlPath="+urlPath+"; urlPath="+data);
for (int i = 0; i < 3; i++) {
// 建立连接
try {
URL url = new URL(urlPath);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();

// 设置连接请求属性post
conn.setDoOutput(true);
conn.setDoInput(true);

// 忽略缓存
conn.setUseCaches(false);
conn.setRequestMethod("POST");
conn.setRequestProperty("accept", "*/*");
conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestProperty("user-agent",
"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
conn.setRequestProperty("Charset", "UTF-8");

// 获取URLConnection对象对应的输出流
PrintWriter out = new PrintWriter(conn.getOutputStream());
out.print(data);
out.close();

// 定义BufferedReader输入流来读取URL的响应
int code = conn.getResponseCode();
if (HttpURLConnection.HTTP_OK == code) {
BufferedReader in = new BufferedReader(new InputStreamReader(
conn.getInputStream(), "UTF-8"));
String line;
while ((line = in.readLine()) != null) {
sub.append(line);
}
in.close();
}

System.out.println("调用kettle服务成功:"+"第"+(i+1)+"次"+";urlPath="+urlPath+";data:"+data);

return sub.toString();
} catch (IOException e) {
sub = new StringBuilder();
System.out.println("调用kettle服务失败:"+"第"+(i+1)+"次"+";urlPath="+urlPath+";data:"+data+"Message:"+e.getMessage());
}
}

return sub.toString();
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: