您的位置:首页 > 编程语言 > Java开发

Java后台发送Post请求,数据传输格式JSON

2015-06-14 17:03 821 查看
代码如下:

package com.test;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;

import net.sf.json.JSONObject;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicHeader;
import org.apache.http.protocol.HTTP;

public abstract class TestSend {

public static String URL = "http://115.28.191.62/web/control";

public static void main(String[] args) {

JSONObject jsobj1 = new JSONObject();
JSONObject jsobj2 = new JSONObject();
jsobj2.put("deviceID", "112");
jsobj2.put("channel", "channel");
jsobj2.put("state", "0");
jsobj1.put("item", jsobj2);
jsobj1.put("requestCommand", "control");

post(jsobj1);

}

public static String post(JSONObject json) {

HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(URL);

post.setHeader("Content-Type", "application/json");
post.addHeader("Authorization", "Basic YWRtaW46");
String result = "";

try {

StringEntity s = new StringEntity(json.toString(), "utf-8");
s.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,
"application/json"));
post.setEntity(s);

// 发送请求
HttpResponse httpResponse = client.execute(post);

// 获取响应输入流
InputStream inStream = httpResponse.getEntity().getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(
inStream, "utf-8"));
StringBuilder strber = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
strber.append(line + "\n");
inStream.close();

result = strber.toString();
System.out.println(result);

if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {

System.out.println("请求服务器成功,做相应处理");

} else {

System.out.println("请求服务端失败");

}

} catch (Exception e) {
System.out.println("请求异常");
throw new RuntimeException(e);
}

return result;
}

}


测试接收

<%@ page language="java" import="java.util.*,java.io.*" pageEncoding="UTF-8"%>
<%

System.out.println("conenction server success!");

System.out.println(request.getMethod());

//后台接收
InputStreamReader reader=new InputStreamReader(request.getInputStream(),"UTF-8");
char [] buff=new char[1024];
int length=0;
while((length=reader.read(buff))!=-1){

String x=new String(buff,0,length);

System.out.println(x);
}

//响应
out.println("{'responseCommand':'0','requestCommand':'control'}");

%>


所使用的 jar包:

commons-beanutils-1.8.3.jar

commons-codec-1.4.jar

commons-collections-3.2.1.jar

commons-lang-2.5.jar

commons-lang3-3.1.jar

commons-logging-1.1.1.jar

ezmorph-1.0.6.jar

httpclient-4.1.2.jar

httpcore-4.1-alpha1.jar

json-lib-2.4-jdk15.jar

morph-1.1.1.jar

morph-sandbox-1.1.1.jar
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: