首页 >Java >java教程 >java URL 获取PHP JSON 数据

java URL 获取PHP JSON 数据

高洛峰
高洛峰原创
2017-01-05 17:09:581099浏览

1:php地址  http://127.0.0.6/?c=json
2:java 输出的结果是

[{"id":1,"name":"zhdc"},{"id":2,"name":"\u5c0f\u6731"}]

index.php

<?php
if(isset($_REQUEST[&#39;c&#39;])){
  $c = $_REQUEST[&#39;c&#39;];
  if($c == "json"){
    $arr = array(
        array("id"=>1,"name"=>"zhdc"),
        array("id"=>2,"name"=>"小朱")
    );
    die(json_encode($arr));
  }
}
Main.class
  
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
  
public class Main {
  public static void main(String[] args){
    try {
      URL url = new URL("http://127.0.0.6/?c=json");
      HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
      httpURLConnection.setDoInput(true);
      httpURLConnection.connect();
      InputStream inputStream = httpURLConnection.getInputStream();
      BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream);
      Reader reader = new InputStreamReader(bufferedInputStream);
      String json = "";
      int c;
      while((c = reader.read()) != -1){
        json += (char)c;
      }
      System.out.println(json);
    } catch (MalformedURLException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
}


更多java URL 获取PHP JSON 数据相关文章请关注PHP中文网!


声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn