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

Java web 项目发送请求到 thinkphp 项目返回Json字符串

2016-09-26 21:14 561 查看

一 java web 项目发送一个httpget请求

import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;

String url = "http://192.168.8.111:83/Home/Dock/getJson?auth=5d40f1dba14d7bf67d9ddcf8c4b634d6&website=slug";
HttpClient httpCient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);


二 thinkphp 项目接收请求,并根据发送的字符串处理对应数据 ,返回一个json字符串,到页面

php路径 : Home->DockController.class.php->getJson 方法中

<?php
namespace Home\Controller;
use Home\Controller\CommonController;
class DockController extends CommonController {

public function getJson($slug=''){
if( isset($_GET['auth']) && $_GET['auth'] == md5('java_to_php') ){
$slug=$_GET['website'];
//下面是根据slug 条件 查询 数据库 的代码,我查询到的数据放在 $normallist 中
echo json_encode($normallist);//把要传输的数据转成json串,打印到页面
}
exit;
}
}


附:我在页面打印的信息

页面url:
http://192.168.8.111:83/Home/Dock/getJson?auth=5d40f1dba14d7bf67d9ddcf8c4b634d6&website=slug


页面信息:

{
"3568": {
"website": "justtest.com",
"brand": "justtest.com",
"brand_url": "codes/justtest.com",
"redirect_url": "http://www.justtest.com",
"title": "justtest.com Promotion on Selected Porducts!",
"description": "It's just a test description",
"code": "",
"discount": "",
"freeshipping": "0",
"expiration_time": "05/26/2016",
"window_url": null
},
"6553": {
"website": "justtest.com",
"brand": "justtest.com",
"brand_url": "codes/justtest.com",
"redirect_url": "http://www.justtest.com/2016/08/20/just-a-test-url/",
"title": "I don't know what should I say with justtest.com",
"description": "It's just a test description",
"code": "",
"discount": "20%",
"freeshipping": "0",
"expiration_time": "10/28/2016",
"window_url": "./haha/1036923"
}
}


三 java web 项目接收json串 并转换成 List

List<Object> list = new ArrayList<>();

if (httpResponse.getStatusLine().getStatusCode() == 200) {//请求接受成功
String strResult = EntityUtils.toString(httpResponse.getEntity()).toString();
HashMap<String,Object> map = new Gson().fromJson(strResult, new TypeToken<HashMap<String, Object>>(){}.getType());
for(String id: map.keySet()){
list.add(map.get(id));
}
}


注: object是根据json串的 key 自定义的一个类

四 再次贴出java web 全部代码

package com.form.comm.util.importData;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client<
10ba0
/span>.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import com.form.domain.Object;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

public class TestString {
public static void main(String[] args) {
List<Object> list = new ArrayList<>();
String url = "http://192.168.8.111:83/Home/Dock/getJson?auth=9d775913307c1e0cbcbae4e4613a965f&website=justtest.com";
HttpClient httpCient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
try {
HttpResponse httpResponse = httpCient.execute(httpGet);

if (httpResponse.getStatusLine().getStatusCode() == 200) {

String strResult = EntityUtils.toString(httpResponse.getEntity()).toString();

HashMap<String,Object> map = new Gson().fromJson(strResult, new TypeToken<HashMap<String, Object>>(){}.getType());

for(String id: map.keySet()){
list.add(map.get(id));
}
}

} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}


附录:下面是本次需求在网上找的文档(以下部分,代码非原创)

1.java web 发送请求的相关内容

/*   注意get和post请求的发送区别
* 1、创建HttpGet(或HttpPost)对象,将要请求的URL通过构造方法传入HttpGet(或HttpPost)对象中;
2、使用DefaultHttpClient类的execute方法发送HTTP GET或HTTP POST 请求,并返回HttpResponse对象;
3、通过HttpResponse接口的getEntity方法返回响应信息。
* */

public class TestHttpActivity extends Activity {
private Button btn_get;
private Button btn_post;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
btn_get=(Button)findViewById(R.id.btn_get);
btn_post=(Button)findViewById(R.id.btn_post);
btn_get.setOnClickListener(listener);
btn_post.setOnClickListener(listener);
}
private OnClickListener listener=new OnClickListener() {

@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn_post:
Log.i("TestHttpActivity", "ok");
DefaultHttpClient client = new DefaultHttpClient();
/**NameValuePair是传送给服务器的请求参数    param.get("name") **/
List<NameValuePair> list = new ArrayList<NameValuePair>();
NameValuePair pair1 = new BasicNameValuePair("name", "name0001");
NameValuePair pair2 = new BasicNameValuePair("age", "age0001");
list.add(pair1);
list.add(pair2);
UrlEncodedFormEntity entity=null;
try {
/**设置编码 **/
entity = new UrlEncodedFormEntity(list,"UTF-8");
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
/**新建一个post请求**/
HttpPost post = new HttpPost("http://aaron-pc.wsd.com/Test/testHttp");
post.setEntity(entity);
HttpResponse response=null;
String strResult="";
try {
/**客服端向服务器发送请求**/
response = client.execute(post);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
/**请求发送成功,并得到响应**/
if(response.getStatusLine().getStatusCode()==200){
try {
/**读取服务器返回过来的json字符串数据**/
strResult = EntityUtils.toString(response.getEntity());
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

JSONObject jsonObject = null;
try {
/**把json字符串转换成json对象**/
jsonObject = getJSON(strResult);
} catch (JSONException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
String names="";

try {
/**
* jsonObject.getString("code") 取出code
* 比如这里返回的json 字符串为 [code:0,msg:"ok",data:[list:{"name":1},{"name":2}]]
* **/

/**得到data这个key**/
String data=jsonObject.getString("data");
/**把data下的数据转换成json对象**/
JSONObject jDat = new JSONObject(data);
/**判断data对象下的list是否存在**/
if(jDat.get("list")!=null){
/**把list转换成jsonArray对象**/
JSONArray jarr = jDat.getJSONArray("list");
/**循环list对象**/
for (int i = 0; i < jarr.length(); i++) {

/** **/
JSONObject jsono = (JSONObject) jarr.get(i);

/**取出list下的name的值 **/
names=names+jsono.getString("name");

}
}
Toast.makeText(TestHttpActivity.this, "code:"+jsonObject.getString("code")+"name:"+names, Toast.LENGTH_SHORT).show();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}
else Toast.makeText(TestHttpActivity.this, "POST提交失败", Toast.LENGTH_SHORT).show();
break;

case R.id.btn_get:
DefaultHttpClient client1 = new DefaultHttpClient();
/**NameValuePair是传送给服务器的请求参数    param.get("name") **/

UrlEncodedFormEntity entity1=null;

/**新建一个get请求**/
HttpGet get = new HttpGet("http://aaron-pc.wsd.com/Test/testHttp");
HttpResponse response1=null;
String strResult1="";
try {
/**客服端向服务器发送请求**/
response1 = client1.execute(get);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
/**请求发送成功,并得到响应**/
if(response1.getStatusLine().getStatusCode()==200){
try {
/**读取服务器返回过来的json字符串数据**/
strResult1 = EntityUtils.toString(response1.getEntity());
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

JSONObject jsonObject1 = null;
try {
/**把json字符串转换成json对象**/
jsonObject1 = getJSON(strResult1);
} catch (JSONException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
String names="";

try {
/**
* jsonObject.getString("code") 取出code
* 比如这里返回的json 字符串为 [code:0,msg:"ok",data:[list:{"name":1},{"name":2}]]
* **/

/**得到data这个key**/
String data=jsonObject1.getString("data");
/**把data下的数据转换成json对象**/
JSONObject jDat1 = new JSONObject(data);
/**判断data对象下的list是否存在**/
if(jDat1.get("list")!=null){
/**把list转换成jsonArray对象**/
JSONArray jarr1 = jDat1.getJSONArray("list");
/**循环list对象**/
for (int i = 0; i < jarr1.length(); i++) {

/** **/
JSONObject jsono = (JSONObject) jarr1.get(i);

/**取出list下的name的值 **/
names=names+jsono.getString("name");

}
}
Toast.makeText(TestHttpActivity.this,  "get请求: code:"+jsonObject1.getString("code")+"name:"+names, Toast.LENGTH_SHORT).show();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}
else Toast.makeText(TestHttpActivity.this, "get提交失败", Toast.LENGTH_SHORT).show();
break;
}

}
};
public JSONObject getJSON(String sb) throws JSONException {
return new JSONObject(sb);
}

}


2.java web 接收json串 并转化的内容

package myTest;

import java.util.List;

import com.google.gson.Gson;

public class MyTest {

public static void main(String... args) throws Exception {
String json =
"{"
+ "'title': 'Computing and Information systems',"
+ "'id' : 1,"
+ "'children' : 'true',"
+ "'groups' : [{"
+ "'title' : 'Level one CIS',"
+ "'id' : 2,"
+ "'children' : 'true',"
+ "'groups' : [{"
+ "'title' : 'Intro To Computing and Internet',"
+ "'id' : 3,"
+ "'children': 'false',"
+ "'groups':[]"
+ "}]"
+ "}]"
+ "}";

// Now do the magic.
Data data = new Gson().fromJson(json, Data.class);

// Show it.
System.out.println(data);
}

}

class Data {
private String title;
private Long id;
private Boolean children;
private List<Data> groups;

public String getTitle() { return title; }
public Long getId() { return id; }
public Boolean getChildren() { return children; }
public List<Data> getGroups() { return groups; }

public void setTitle(String title) { this.title = title; }
public void setId(Long id) { this.id = id; }
public void setChildren(Boolean children) { this.children = children; }
public void setGroups(List<Data> groups) { this.groups = groups; }

public String toString() {
return String.format("title:%s,id:%d,children:%s,groups:%s", title, id, children, groups);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  thinkphp java