求java通过http请求获取json数据的demo

java获取这个网址的json数据并解析http://www.yemaxgo.com/connect.php

10个回答

package com.binjava.test;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;

public class MainFrame{

public static void main(String[] args) {
    HttpURLConnection connection = null;
    InputStream is = null;
    BufferedReader br = null;
    String result = null;
    try {
        URL url = new URL("http://www.yemaxgo.com/connect.php");
        connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("GET");
        connection.setConnectTimeout(15000);
        connection.setReadTimeout(60000);
        connection.connect();
        if (connection.getResponseCode() == 200) {
            is = connection.getInputStream();
            br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
            StringBuffer sbf = new StringBuffer();
            String temp = null;
            while ((temp = br.readLine()) != null) {
                sbf.append(temp);
                sbf.append("\r\n");
            }
            result = sbf.toString();
            result = "{1:"+result+"}";//不是严格的JSON数据格式,补成标准的json数据格式
            JsonParser jParser = new JsonParser();
            JsonObject jt = (JsonObject) jParser.parse(result);
            JsonArray jArray = jt.get("1").getAsJsonArray();
            JsonObject subObject=jArray.get(0).getAsJsonObject();
            System.out.println("id值为:"+subObject.get("id").getAsInt());
            System.out.println("speed值为:"+subObject.get("speed").getAsInt());
            System.out.println("pm25为:"+subObject.get("pm25").getAsInt());
            System.out.println("temperature(温度)为:"+subObject.get("temperature").getAsInt());
            System.out.println("humidity值为:"+subObject.get("humidity").getAsInt());
            System.out.println("temperature_warning值为:"+subObject.get("temperature_warning").getAsInt());
            System.out.println("gas_warning值为:"+subObject.get("gas_warning").getAsInt());
            System.out.println("humidity_warning值为:"+subObject.get("humidity_warning").getAsInt());
            System.out.println("lowpower_warning值为:"+subObject.get("lowpower_warning").getAsInt());
            System.out.println("mode值为:"+subObject.get("mode").getAsInt());
            System.out.println("timing_hour值为:"+subObject.get("timing_hour").getAsInt());
            System.out.println("timing_minute值为:"+subObject.get("timing_minute").getAsInt());
            System.out.println("timing_second值为:"+subObject.get("timing_second").getAsInt());
            System.out.println("update_time值为:"+subObject.get("update_time").getAsString());
            subObject=jArray.get(1).getAsJsonObject();
            System.out.println("time值为:"+subObject.get("time").getAsString());          
        }
    }catch (Exception e) {
        // TODO: handle exception
        e.printStackTrace();
    }

}
}
图片说明

代码需要导入gson模块包

public static void temp(String isbn) throws IOException{
// 我们需要进行请求的地址:
String temp = "https://api.douban.com/v2/book/isbn/" + isbn;
try {
// 1.URL类封装了大量复杂的实现细节,这里将一个字符串构造成一个URL对象
URL url = new URL(temp);
// 2.获取HttpURRLConnection对象
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
// 3.调用connect方法连接远程资源
connection.connect();
// 4.访问资源数据,使用getInputStream方法获取一个输入流用以读取信息
BufferedReader bReader = new BufferedReader(
new InputStreamReader(connection.getInputStream(), "UTF-8"));

    // 对数据进行访问
    String line = null;
    StringBuilder stringBuilder = new StringBuilder();
    while ((line = bReader.readLine()) != null) {
        stringBuilder.append(line);
    }

    // 关闭流
    bReader.close();
    // 关闭链接
    connection.disconnect();
    // 打印获取的结果
    System.out.println(stringBuilder.toString());

    } catch (MalformedURLException e) {
        e.printStackTrace();
    }
}
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Iterator;
import java.util.Map.Entry;

import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;

public class JsonDemo {

    /**
     * 打印json信息
     * @param jsonStr json字符串
     * @throws Exception
     */
    public static void printJson(String jsonStr) throws Exception {
        JsonParser jsonParser = new JsonParser();
        JsonArray jsonArray = (JsonArray) jsonParser.parse(jsonStr);
        for (int i = 0; i < jsonArray.size(); i++) {
            JsonObject jsonObject = jsonArray.get(i).getAsJsonObject();
            Iterator<Entry<String, JsonElement>> iterator = jsonObject.entrySet().iterator();
            while (iterator.hasNext()) {
                System.out.println(iterator.next());
            }
        }
    }

    /**
     * 发送get请求
     * @param getUrl 请求地址
     * @return
     * @throws Exception
     */
    public static String sendGet(String getUrl) throws Exception {
        HttpURLConnection connection = null;
        InputStream is = null;
        BufferedReader br = null;
        String result = null;
        URL url = new URL(getUrl);
        connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("GET");
        connection.connect();
        if (connection.getResponseCode() == 200) {
            is = connection.getInputStream();
            br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
            StringBuffer sbf = new StringBuffer();
            String temp = null;
            while ((temp = br.readLine()) != null) {
                sbf.append(temp+"\n");
                sbf.append("\r\n");
            }
            result = sbf.toString();
        }
        return result;
    }

    public static void main(String[] args) throws Exception {
        String jsonStr = null;
        String getUrl = "http://www.yemaxgo.com/connect.php";
        jsonStr = sendGet(getUrl);
        if(jsonStr!=null) {
            printJson(jsonStr);
        }
    }
}
batterMRTAN
batterMRTAN //sbf.append("\r\n");
接近 2 年之前 回复

首先你需要一个JSON jar包
然后解析这个JSON对象即可,下面有个链接是HTTP发送JSON数据,解析JSON数据的示例

//解析示例代码
JSONArray userarr = new JSONArray(userjson);
            JSONObject userobj = userarr.getJSONObject(0);

            user = new User();  //实例化 user 对象,否则报空指针异常
            user.setUsername(userobj.getString("username"));
            user.setGender(userobj.getString("gender"));
            user.setAge(userobj.getInt("age"));

网络JSON对象传输解析https://blog.csdn.net/niaonao/article/details/52210651https://blog.csdn.net/niaonao/article/details/52210651

public static void main(String[] args) {
    HttpURLConnection connection = null;
    InputStream is = null;
    BufferedReader br = null;
    String result = null;
    try {
        URL url = new URL("http://www.yemaxgo.com/connect.php");
        connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("GET");
        connection.setConnectTimeout(15000);
        connection.setReadTimeout(60000);
        connection.connect();
        if (connection.getResponseCode() == 200) {
            is = connection.getInputStream();
            br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
            StringBuffer sbf = new StringBuffer();
            String temp = null;
            while ((temp = br.readLine()) != null) {
                sbf.append(temp);
                sbf.append("\r\n");
            }
            result = sbf.toString();
            System.out.println("结果:"+result);
            //解析json
         /*   [{"id":"9311","speed":"65","pm25":"83","temperature":"268","humidity":"66",""
                    + "temperature_warning":"0","gas_warning":"0","humidity_warning":"0",
                    "lowpower_warning":"0","mode":"1","timing_hour":"0","timing_minute":"0",
                    "timing_second":"0","update_time":"2018-06-28 21:01:10"},{"time":"184882234"}]*/

            JSONArray array = JSON.parseArray(result);
            com.alibaba.fastjson.JSONObject jo = array.getJSONObject(0);
            System.out.println("id:"+jo.getString("id"));
            System.out.println("speed:"+jo.getString("speed"));
            System.out.println("pm25:"+jo.getString("pm25"));
            System.out.println("temperature:"+jo.getString("temperature"));
            System.out.println("humidity:"+jo.getString("humidity"));
            System.out.println("temperature_warning:"+jo.getString("temperature_warning"));
            System.out.println("gas_warning:"+jo.getString("gas_warning"));
            System.out.println("humidity_warning:"+jo.getString("humidity_warning"));
            System.out.println("timing_second:"+jo.getString("timing_second"));
            System.out.println("update_time:"+jo.getString("update_time"));
            System.out.println("timing_hour:"+jo.getString("timing_hour"));

            com.alibaba.fastjson.JSONObject jo2 = array.getJSONObject(1);
            System.out.println("time"+jo2.getString("time"));
        }
    }catch (Exception e) {
        // TODO: handle exception
        e.printStackTrace();
    }
}

记得导一下 com.alibaba.fastjson

将地址直接在浏览器输入,发现结果是[{"id":"9311","speed":"65","pm25":"83","temperature":"268","humidity":"66","temperature_warning":"0","gas_warning":"0","humidity_warning":"0","lowpower_warning":"0","mode":"1","timing_hour":"0","timing_minute":"0","timing_second":"0","update_time":"2018-06-28 21:01:10"},{"time":"184890422"}]
,是一个json数组。所以定义两个对象来接收,当然也可以不定义,直接转换成JSONObject。

 public class ObjectOne {

    private String id;

    private String speed;

    private String pm25;

    private String temperature;

    private String humidity;

    private String temperature_warning;

    private String gas_warning;

    private String humidity_warning;

    private String lowpower_warning;

    private String mode;

    private String timing_hour;

    private String timing_minute;

    private String timing_second;

    private String update_time;

    public ObjectOne() {
    }

    public ObjectOne(String id, String speed, String pm25, String temperature, String humidity, String temperature_warning, String gas_warning, String humidity_warning, String lowpower_warning, String mode, String timing_hour, String timing_minute, String timing_second, String update_time) {
        this.id = id;
        this.speed = speed;
        this.pm25 = pm25;
        this.temperature = temperature;
        this.humidity = humidity;
        this.temperature_warning = temperature_warning;
        this.gas_warning = gas_warning;
        this.humidity_warning = humidity_warning;
        this.lowpower_warning = lowpower_warning;
        this.mode = mode;
        this.timing_hour = timing_hour;
        this.timing_minute = timing_minute;
        this.timing_second = timing_second;
        this.update_time = update_time;
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getSpeed() {
        return speed;
    }

    public void setSpeed(String speed) {
        this.speed = speed;
    }

    public String getPm25() {
        return pm25;
    }

    public void setPm25(String pm25) {
        this.pm25 = pm25;
    }

    public String getTemperature() {
        return temperature;
    }

    public void setTemperature(String temperature) {
        this.temperature = temperature;
    }

    public String getHumidity() {
        return humidity;
    }

    public void setHumidity(String humidity) {
        this.humidity = humidity;
    }

    public String getTemperature_warning() {
        return temperature_warning;
    }

    public void setTemperature_warning(String temperature_warning) {
        this.temperature_warning = temperature_warning;
    }

    public String getGas_warning() {
        return gas_warning;
    }

    public void setGas_warning(String gas_warning) {
        this.gas_warning = gas_warning;
    }

    public String getHumidity_warning() {
        return humidity_warning;
    }

    public void setHumidity_warning(String humidity_warning) {
        this.humidity_warning = humidity_warning;
    }

    public String getLowpower_warning() {
        return lowpower_warning;
    }

    public void setLowpower_warning(String lowpower_warning) {
        this.lowpower_warning = lowpower_warning;
    }

    public String getMode() {
        return mode;
    }

    public void setMode(String mode) {
        this.mode = mode;
    }

    public String getTiming_hour() {
        return timing_hour;
    }

    public void setTiming_hour(String timing_hour) {
        this.timing_hour = timing_hour;
    }

    public String getTiming_minute() {
        return timing_minute;
    }

    public void setTiming_minute(String timing_minute) {
        this.timing_minute = timing_minute;
    }

    public String getTiming_second() {
        return timing_second;
    }

    public void setTiming_second(String timing_second) {
        this.timing_second = timing_second;
    }

    public String getUpdate_time() {
        return update_time;
    }

    public void setUpdate_time(String update_time) {
        this.update_time = update_time;
    }

    @Override
    public String toString() {
        final StringBuilder sb = new StringBuilder("{");
        sb.append("\"id\":\"")
                .append(id).append('\"');
        sb.append(",\"speed\":\"")
                .append(speed).append('\"');
        sb.append(",\"pm25\":\"")
                .append(pm25).append('\"');
        sb.append(",\"temperature\":\"")
                .append(temperature).append('\"');
        sb.append(",\"humidity\":\"")
                .append(humidity).append('\"');
        sb.append(",\"temperature_warning\":\"")
                .append(temperature_warning).append('\"');
        sb.append(",\"gas_warning\":\"")
                .append(gas_warning).append('\"');
        sb.append(",\"humidity_warning\":\"")
                .append(humidity_warning).append('\"');
        sb.append(",\"lowpower_warning\":\"")
                .append(lowpower_warning).append('\"');
        sb.append(",\"mode\":\"")
                .append(mode).append('\"');
        sb.append(",\"timing_hour\":\"")
                .append(timing_hour).append('\"');
        sb.append(",\"timing_minute\":\"")
                .append(timing_minute).append('\"');
        sb.append(",\"timing_second\":\"")
                .append(timing_second).append('\"');
        sb.append(",\"update_time\":\"")
                .append(update_time).append('\"');
        sb.append('}');
        return sb.toString();
    }
}

 public class ObjectTwo {

    private String time;

    public ObjectTwo() {
    }

    public ObjectTwo(String time) {
        this.time = time;
    }

    public String getTime() {
        return time;
    }

    public void setTime(String time) {
        this.time = time;
    }

    @Override
    public String toString() {
        final StringBuilder sb = new StringBuilder("{");
        sb.append("\"time\":\"")
                .append(time).append('\"');
        sb.append('}');
        return sb.toString();
    }
}

 import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

public class ReadUrl {
    public static void main(String args []){
        String url = "http://www.yemaxgo.com/connect.php";
        try{
            String jsonStr = sendGet(url);
            System.out.println(jsonStr);

            //[{"id":"9311","speed":"65","pm25":"83","temperature":"268","humidity":"66","temperature_warning":"0","gas_warning":"0","humidity_warning":"0","lowpower_warning":"0","mode":"1","timing_hour":"0","timing_minute":"0","timing_second":"0","update_time":"2018-06-28 21:01:10"},{"time":"184884931"}]

            JSONArray jsonArray = JSONArray.parseArray(jsonStr);

            System.out.println(jsonArray);

            JSONObject obj1 = (JSONObject) jsonArray.get(0);

            JSONObject obj2 = (JSONObject) jsonArray.get(1);

            System.out.println(obj1);

            System.out.println(obj2);

            ObjectOne objectOne = JSONObject.parseObject(obj1.toJSONString(),ObjectOne.class);

            ObjectTwo objectTwo = JSONObject.parseObject(obj2.toJSONString(),ObjectTwo.class);


            System.out.println(objectOne);

            System.out.println(objectTwo);

        }catch(Exception e){
            e.printStackTrace();
        }
    }


    public static String sendGet(String getUrl) throws Exception {
        HttpURLConnection connection = null;
        InputStream is = null;
        BufferedReader br = null;
        String result = null;
        URL url = new URL(getUrl);
        connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("GET");
        connection.connect();
        if (connection.getResponseCode() == 200) {
            is = connection.getInputStream();
            br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
            StringBuffer sbf = new StringBuffer();
            String line = null;
            while ((line = br.readLine()) != null) {
                sbf.append(line);

            }
            result = sbf.toString();
        }
        return result;
    }

}

需要fastjson-1.1.24.jar
此方法必须访问http请求,访问https需要httpclient
具体方法:



@RequestMapping("geturl.do")

   public void geturl(HttpServletResponseresponse){



      String url = "http://localhost:8080/Test/getUsers.do?id=1";

      //new一个stringbuffer

      StringBuffer json = new StringBuffer();

      try {

         //通过url获得连接

         URL u = new URL(url);

         URLConnection yc = u.openConnection();

         //读取返回的数据

         BufferedReader in = new BufferedReader(new InputStreamReader(yc.getInputStream(),"UTF-8"));

         String inputline = null;

         while((inputline=in.readLine())!=null){

            json.append(inputline);

         }

         in.close();

      } catch (Exception e) {

         e.printStackTrace();

      }

      //获得jsonobject

      JSONObject jo = JSON.parseObject(json.toString());

      JSONObject jo2 = jo.getJSONObject("data");

      //获得json数组

      JSONArray ja = jo2.getJSONArray("users");

      JSONObject jo3 = null;

      Users user = null;

      for (int i = 0; i < ja.size(); i++) {

         jo3 = ja.getJSONObject(i);

         user = new Users();

         user.setId(jo3.getIntValue("id"));

         user.setUsername(jo3.getString("username"));

         user.setPassword(jo3.getString("password"));

         user.setAge(jo3.getIntValue("age"));

         user.setSex(jo3.getIntValue("sex"));

         System.out.println(user.getUsername());

      }

   }

package com.ruijie.spl.xhjy;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import org.apache.http.HttpResponse;
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.protocol.HTTP;
import org.apache.http.util.EntityUtils;

import com.ruijie.spl.xhjy.util.bean.Person;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

public class TestJsonObject {
public static void main(String[] args) {
String res = post("http://www.yemaxgo.com/connect.php","");
pase(res);

}

private static void pase(String res) {
    JSONArray resJsonArray= JSONArray.fromObject(res);
    System.out.println(resJsonArray.toString());
    JSONObject jsonObject;
    for (int j= 0;j<resJsonArray.size();j++){  
        //获取JsonArray 中的JSONObject
        jsonObject=resJsonArray.getJSONObject(j);
        //获取JSONObject中的属性值,根据key jsonObject.get("id");
        System.out.println( jsonObject.get("id"));
        //封装到对应的JavaBean 中,进行其他操作,插入数据库
        System.out.println("属性封装对象");
    }

}
/**
 * httppost
 * @param url
 * @param postStr
 * @return
 */
@SuppressWarnings({ "resource", "deprecation" })
public static String post(String url,String postStr) {
    String result = "";
    try {
        HttpPost post = new HttpPost(url);
        StringEntity postEntity = new StringEntity(postStr,"UTF-8");
        postEntity.setContentType("application/x-www-form-urlencoded");  
        post.setEntity(postEntity);  
        HttpClient client = new DefaultHttpClient();  
        HttpResponse httpResponse = client.execute(post);  
        result = EntityUtils.toString(httpResponse.getEntity(), HTTP.UTF_8);
        System.out.println(result);
    } catch(Exception ex) {
        ex.printStackTrace();
    }
    return result;
}   

}

需要的包 httpclient-4.3.6.jar
<!-- JSONObject 开始 jdk15 不加会找不到包-->

net.sf.json-lib
json-lib
2.4
jdk15

<!-- JSONObject 结束 -->


import net.sf.json.JSONObject;
2 import org.apache.commons.httpclient.*;
3 import org.apache.commons.httpclient.methods.GetMethod;
4 import org.apache.commons.httpclient.params.HttpMethodParams;
5 import org.apache.http.HttpEntity;
6 import org.apache.http.HttpResponse;
7 import org.apache.http.client.methods.HttpPost;
8 import org.apache.http.entity.StringEntity;
9 import org.apache.http.impl.client.DefaultHttpClient;
10 import org.apache.http.util.EntityUtils;
11 import java.io.IOException;
12
13 /**
14 * Created by liqun.chen on 2017/5/15.
15 /
16 public class HttpUtil {
17 /
*
18 * json 字符串
19 * @param url
20 * @param param
21 * @return
22 /
23 public static String getSerchPersion(String url,String param){
24 /
1 生成 HttpClinet 对象并设置参数 /
25 HttpClient httpClient = new HttpClient();
26 // 设置 Http 连接超时为5秒
27 httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(5000);
28 /
2 生成 GetMethod 对象并设置参数 /
29 GetMethod getMethod = new GetMethod(url);
30 // 设置 get 请求超时为 5 秒
31 getMethod.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, 5000);
32 // 设置请求重试处理,用的是默认的重试处理:请求三次
33 getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler());
34 String response = "";
35 /
3 执行 HTTP GET 请求 /
36 try {
37 int statusCode = httpClient.executeMethod(getMethod);
38 /
4 判断访问的状态码 /
39 if (statusCode != HttpStatus.SC_OK) {
40 System.err.println("请求出错: "+ getMethod.getStatusLine());
41 }
42 /
5 处理 HTTP 响应内容 /
43 // HTTP响应头部信息,这里简单打印
44 Header[] headers = getMethod.getResponseHeaders();
45 for (Header h : headers)
46 System.out.println(h.getName() + "------------ " + h.getValue());
47 // 读取 HTTP 响应内容,这里简单打印网页内容
48 byte[] responseBody = getMethod.getResponseBody();// 读取为字节数组
49 response = new String(responseBody, param);
50 System.out.println("----------response:" + response);
51 // 读取为 InputStream,在网页内容数据量大时候推荐使用
52 // InputStream response = getMethod.getResponseBodyAsStream();
53 } catch (HttpException e) {
54 // 发生致命的异常,可能是协议不对或者返回的内容有问题
55 System.out.println("请检查输入的URL!");
56 e.printStackTrace();
57 } catch (IOException e) {
58 // 发生网络异常
59 System.out.println("发生网络异常!");
60 e.printStackTrace();
61 } finally {
62 /
6 .释放连接 /
63 getMethod.releaseConnection();
64 }
65 return response;
66 }
67 /
*
68 * post请求
69 * @param url
70 * @param json
71 * @return
72 */
73 public static JSONObject doPost(String url,JSONObject json){
74 DefaultHttpClient client = new DefaultHttpClient();
75 HttpPost post = new HttpPost(url);
76 JSONObject response = null;
77 try {
78 StringEntity s = new StringEntity(json.toString());
79 s.setContentEncoding("UTF-8");
80 s.setContentType("application/json");//发送json数据需要设置contentType
81 post.setEntity(s);
82 HttpResponse res = client.execute(post);
83 if(res.getStatusLine().getStatusCode() == HttpStatus.SC_OK){
84 HttpEntity entity = res.getEntity();
85 String result = EntityUtils.toString(res.getEntity());// 返回json格式:
86 response = JSONObject.fromObject(result);
87 }
88 } catch (Exception e) {
89 throw new RuntimeException(e);
90 }
91 return response;
92 }

1 //调用
2 public static void main(String arg[]) throws Exception {
3 String url = "http://localhost:8080/";
4 JSONObject params = new JSONObject();
5 params.put("personName", "name");
6 params.put("personCode", "230882xxxxxx2116");
7 JSONObject param2 = new JSONObject();
8 param2.put("pageNo", 1);
9 param2.put("pageSize", 20);
10 params.put("page", param2);
11 String param = "q="+params.toString();
12 //get 请求
13 String ret = getSerchPersion(url, param.toString());
14 System.out.println(ret);
15 // JSONObject jsonResponse=JSONObject.fromObject(param);
16 // JSONObject json = (JSONObject)jsonResponse.get("page");
17 // System.out.println(json.get("pageSize"));
18
19 //post 请求
20 JSONObject jsonObject = doPost(url,params);
21 System.out.println(jsonObject.toString());
22 }

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
其他相关推荐
利用线程获取json数据,肯定能获取到,可是为空

利用线程获取json数据,肯定能获取到,获取到的json传给公有的json,可是每次公有的json里面都是空值,求大神给解决方案。 我的代码 package textview.exam; import android.app.AlertDialog; import android.content.DialogInterface; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.util.Log; import android.view.Gravity; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.Button; import android.widget.ListView; import android.widget.SimpleAdapter; import android.widget.TextView; import android.widget.Toast; import com.baidu.apistore.sdk.ApiCallBack; import com.baidu.apistore.sdk.ApiStoreSDK; import com.baidu.apistore.sdk.network.Parameters; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class FragmentMainchatweather extends Fragment { TextView mTextView; Button test; String city; WeatherPopup weatherPopup; JSONArray forecast; ListView list; JSONObject retData=null; private int[] weatherzt = new int[] { R.drawable.sun , R.drawable.cloudy , R.drawable.baoyu , R.drawable.thouder,R.drawable.snow,R.drawable.zhongyu, R.drawable.zhenyu,R.drawable.dayu}; @Override public void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); } @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { // TODO Auto-generated method stub View view=inflater.inflate(R.layout.main_chat_weather, null); Button weatheradd=(Button)view.findViewById(R.id.weatheradd); list = (ListView) view.findViewById(R.id.chat_weathers); list.setOnItemClickListener(weatherforListener); weatheradd.setOnClickListener(weatheraddListener); return view; } //点击添加按钮弹出输入城市对话框,然后根据城市名字进行查询并且显示 View.OnClickListener weatheraddListener=new View.OnClickListener() { @Override public void onClick(View v) { //加载文本框布局 final View weatheradd=getActivity().getLayoutInflater().inflate(R.layout.weatheradd, null); new AlertDialog.Builder(getActivity()) .setView(weatheradd) .setPositiveButton("确定",new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { TextView city1=(TextView)weatheradd.findViewById(R.id.citytext); city=city1.getText().toString(); Log.i("我靠"+retData,"1"); SyncThread st1 = new SyncThread(); st1.start(); Log.i("我靠"+retData,"2"); //view更新 weatherselect(); } }) .setNegativeButton("取消",new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { } }) .create() .show(); } }; AdapterView.OnItemClickListener weatherforListener=new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { //为未来天气设置SimpleAdapter //final SimpleAdapter simpleAdapter1 = new SimpleAdapter(getActivity(), listItemx, R.layout.weather_popup_item, // new String[]{"forecastweek", "forecasttype", "forecastlowtemp", "forecasthightemp"}, // new int[]{R.id.forecastweek, R.id.forecasttype, R.id.forecastlowtemp, R.id.forecasthightemp}); list.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { //实例化SelectPicPopupWindow weatherPopup = new WeatherPopup(getActivity()); //weatherPopup.setAdapter(simpleAdapter1); //显示窗口 weatherPopup.showAtLocation(getActivity().findViewById(R.id.main), Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0); } }); } }; public void weatherselect(){ List<Map<String, Object>> listItemx = new ArrayList<Map<String, Object>>(); try { Map<String, Object> listItem = new HashMap<String, Object>(); JSONObject today = retData.getJSONObject("today"); listItem.put("city", retData.getString("city")); listItem.put("lowtemp", today.getString("lowtemp")); listItem.put("hightemp", today.getString("hightemp")); listItem.put("week", today.getString("week")); listItem.put("curTemp", today.getString("curTemp")); listItem.put("type", today.getString("type")); listItem.put("fengli", today.getString("fengli")); listItem.put("aqi", today.getString("aqi")); listItemx.add(listItem); } catch (JSONException e) { e.printStackTrace(); Toast.makeText(getActivity(),"数据加载错误", Toast.LENGTH_LONG).show(); } final SimpleAdapter simpleAdapter = new SimpleAdapter(getActivity(), listItemx, R.layout.weather_simple_item, new String[]{"city", "lowtemp", "hightemp", "week", "curTemp", "type", "fengli", "aqi"}, new int[]{R.id.city, R.id.lowtemp, R.id.hightemp, R.id.week, R.id.curTemp, R.id.type, R.id.fengli, R.id.aqi}) { @Override public View getView(int position, View convertView,ViewGroup parent){ final View view=super.getView(position, convertView, parent); TextView text=(TextView)view.findViewById(R.id.type); switch (text.getText().toString()){ case "多云": view.setBackgroundResource(weatherzt[1]); break; case "雷阵雨": view.setBackgroundResource(weatherzt[3]); break; case "阵雨": view.setBackgroundResource(weatherzt[6]); break; case "大雨": view.setBackgroundResource(weatherzt[7]); break; case "暴雨": view.setBackgroundResource(weatherzt[2]); break; case "晴": view.setBackgroundResource(weatherzt[0]); break; case "雪": view.setBackgroundResource(weatherzt[4]); break; case "中雨": view.setBackgroundResource(weatherzt[5]); break; default: view.setBackgroundResource(weatherzt[0]); break; } return view; } }; simpleAdapter.notifyDataSetChanged(); list.setAdapter(simpleAdapter); } //开启子线程得到数据 public class SyncThread extends Thread { @Override public void run() { Parameters para = new Parameters(); para.put("cityname", city); ApiStoreSDK.execute("http://apis.baidu.com/apistore/weatherservice/recentweathers", ApiStoreSDK.GET, para, new ApiCallBack() { @Override public void onSuccess(int status, String responseString) { Log.i("连接状态(天气)", "成功"); try { JSONObject dataJson = new JSONObject(responseString); retData = dataJson.getJSONObject("retData"); Log.i("我靠" + retData, "3"); } catch (JSONException e) { Toast toast = Toast.makeText(getActivity(), "没有这个城市请重新输入", Toast.LENGTH_SHORT); //屏幕下方显示,X轴和Y轴偏移量都是0 toast.setGravity(Gravity.BOTTOM, 0, 0); toast.show(); Log.i("获取到数据:", responseString); } } @Override public void onComplete() { Log.i("sdkdemo", "onComplete"); } @Override public void onError(int status, String responseString, Exception e) { Log.i("sdkdemo", "onError, status: " + status); Log.i("sdkdemo", "errMsg: " + (e == null ? "" : e.getMessage())); } }); } } }

ajax获取不到php从数据库里面读取到的数据,(php读取到的数据已经成功转换成了json数据)

javascript代码: ```javascript // 初始化两个数组,盛装从数据库中获取到的数据 var dates = new Array(), moneys = new Array(); //调用ajax来实现异步的加载数据 function getusers() { $.ajax({ type: "post", async: false, data:{}, url: "dataDemo/dataIndex.php", data: {}, dataType: "json", success: function(result){ if(result){ for(var i = 0; i < result.length; i++){ dates.push(result[i].sum); moneys.push(result[i].money); } } }, error: function(errmsg) { alert("Ajax获取服务器数据出错了!"+ errmsg); } }); return dates, moneys; } //执行异步请求 getusers(); ``` public_function.php代码: ```php <?php function dbInit(){ global $con; $dsn = "mysql:dbname=info;localhost=127.0.0.1"; $user = "root"; $password = "644066YanMin&&!+"; try{ $con = new PDO($dsn,$user,$password); }catch(PDOExcepetion $e){ die ("Error!: " . $e->getMessage() . "<br/>"); } } /* 处理结果集中有多条数据的函数; */ function fetchAll($sql){ global $con; class user{ public $times; public $money; } if($result = $con->query($sql)){ //声明数组,用于接收结果集; $data = array(); //遍历结果集; while($row = $result->fetch(PDO::FETCH_ASSOC)){ $user = new User(); $user->times = $row['times']; $user->money = $row['sum']; $data[] = $user; } return $data; }else{ //执行失败; return false; } } ``` dataIndex.php代码 ```php <?php require "public_function.php"; dbInit(); $sql = 'select times,sum from date'; $datas = fetchAll($sql); // 返回JSON类型的数据 echo json_encode($datas); //$con = null; require "dataIndex.html"; ```

怎么请求聚合数据的数据,求一个demo,谢谢各位大神

我自己做的请求不出来数据,下面上一个类的代码。请大神指点指点 package com.action; import java.io.BufferedReader; import java.io.DataOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.UnsupportedEncodingException; import java.net.URL; import java.net.URLEncoder; import java.util.HashMap; import java.util.Map; import org.apache.commons.httpclient.util.HttpURLConnection; import net.sf.json.JSONObject; import android.app.Activity; import android.os.*; import android.view.*; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; public class Hanziqigua extends Activity{ /***********************/ public static final String DEF_CHATSET = "UTF-8"; public static final int DEF_CONN_TIMEOUT = 30000; public static final int DEF_READ_TIMEOUT = 30000; public static String userAgent = "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/29.0.1547.66 Safari/537.36"; String url ="http://v.juhe.cn/xhzd/query";//请求接口地址 /***********************/ private EditText hzText; private Button hzStartbt; private TextView hzTextBegin; public static final String APPKEY ="4e60f85fda2216b3d39f106204bb8c3d"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.hanziqigua_layout); /***控件初始化*/ hzText = (EditText) findViewById(R.id.hzText); hzStartbt = (Button) findViewById(R.id.hzStartbt); hzTextBegin = (TextView) findViewById(R.id.hzTextBegin); /***/ hzStartbt.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { /***拆分字符串*/ String textBegin=hzText.getText().toString(); final String textBeginOne=textBegin.substring(0,1); final String textBeginTwo=textBegin.substring(1,2); /***/ System.out.println("第一个字 -->"+textBeginOne); System.out.println("第二个字 -->"+textBeginTwo); /***********/ /***********网络请求****************/ /***********第一个字的地址**********/ final String newUrlone = url + "?" + "key=" + APPKEY + "&" + "word=" + textBeginOne; System.out.println("new url -- > "+ newUrlone); /***********************************/ /***********第二个字的地址***********/ final String newUrltwo = url + "?" + "key=" + APPKEY + "&" + "word=" + textBeginOne; System.out.println("new url -- > "+ newUrltwo); /***********************************/ String result =null; String url ="https://v.juhe.cn/xhzd/query";//请求接口地址 Map params = new HashMap();//请求参数 params.put("word",newUrlone);//填写需要查询的汉字,UTF8 urlencode编码 params.put("key",APPKEY);//应用APPKEY(应用详细页查询) params.put("dtype","");//返回数据的格式,xml或json,默认json try { result =net(url, params, "GET"); JSONObject object = JSONObject.fromObject(result); if(object.getInt("error_code")==0){ System.out.println(object.get("result")); }else{ System.out.println(object.get("error_code")+":"+object.get("reason")); } } catch (Exception e) { e.printStackTrace(); } /***********************************/ } }); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } /**************************************************************************************/ /** * * @param strUrl 请求地址 * @param params 请求参数 * @param method 请求方法 * @return 网络请求字符串 * @throws Exception */ public static String net(String strUrl, Map params,String method) throws Exception { HttpURLConnection conn = null; BufferedReader reader = null; String rs = null; try { StringBuffer sb = new StringBuffer(); if(method==null || method.equals("GET")){ strUrl = strUrl+"?"+urlencode(params); } URL url = new URL(strUrl); conn = (HttpURLConnection) url.openConnection(); if(method==null || method.equals("GET")){ conn.setRequestMethod("GET"); }else{ conn.setRequestMethod("POST"); conn.setDoOutput(true); } conn.setRequestProperty("User-agent", userAgent); conn.setUseCaches(false); conn.setConnectTimeout(DEF_CONN_TIMEOUT); conn.setReadTimeout(DEF_READ_TIMEOUT); conn.setInstanceFollowRedirects(false); conn.connect(); if (params!= null && method.equals("POST")) { try { DataOutputStream out = new DataOutputStream(conn.getOutputStream()); out.writeBytes(urlencode(params)); } catch (Exception e) { // TODO: handle exception } } InputStream is = conn.getInputStream(); reader = new BufferedReader(new InputStreamReader(is, DEF_CHATSET)); String strRead = null; while ((strRead = reader.readLine()) != null) { sb.append(strRead); } rs = sb.toString(); } catch (IOException e) { e.printStackTrace(); } finally { if (reader != null) { reader.close(); } if (conn != null) { conn.disconnect(); } } return rs; } //将map型转为请求参数型 public static String urlencode(Map<String,Object>data) { StringBuilder sb = new StringBuilder(); for (Map.Entry i : data.entrySet()) { try { sb.append(i.getKey()).append("=").append(URLEncoder.encode(i.getValue()+"","UTF-8")).append("&"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } } return sb.toString(); } /**************************************************************************************/ }

后台代码返回json数据没有接收到?

这是JS代码 var loading = new Loading(); var layer = new Layer(); $('Account').onclick = function(e){ var newProducts = products.map(function(arr){ return {'id':arr.id,'number':arr.num}; }); console.log(newProducts); var ele = e.target; layer.reset({ content:'确认购买吗?', onconfirm:function(){ layer.hide(); loading.show(); var xhr = new XMLHttpRequest(); var data = JSON.stringify(newProducts); xhr.onreadystatechange = function(){ if(xhr.readyState == 4){ var status = xhr.status; if(status >= 200 && status < 300 || status == 304){ var json = JSON.parse(xhr.responseText); if(json && json.code == 200){ loading.result('购买成功',function(){location.href = './account.html';}); util.deleteCookie(name); }else{ alert(json.message); } }else{ loading.result(message||'购买失败'); } } }; xhr.open('post','/api/buy'); xhr.setRequestHeader('Content-Type','application/json'); xhr.send(data); }.bind(this) }).show(); return; };

JSON字符串的拼接问题。

一个javaweb项目中有一个这种格式的json数据: [ { "cateName": "护肤", "id": 1, "pid": 0 }, { "cateName": "彩妆", "id": 2, "pid": 0 }, { "cateName": "洁面", "id": 3, "pid": 1 }, { "cateName": "化妆水", "id": 4, "pid": 1 }, { "cateName": "洁面乳", "id": 5, "pid": 3 } ] 我想把它转换成下面这种格式: [ { "cateName": "护肤", "id": 1, "pid": 0, "children":[{ "cateName": "化妆水", "id": 4, "pid": 1 }] }, { "cateName": "彩妆", "id": 2, "pid": 0 }, { "cateName": "洁面", "id": 3, "pid": 1, "children":[{ .... }] }, { "cateName": "洁面乳", "id": 5, "pid": 3, "children":[{ .... }] } ] 就是跟这个格式一样的:http://www.jeasyui.com/demo/main/treegrid_data1.json 请问一下要怎么处理? 没有cb了不能悬赏见谅。。。

java微信公众号开发获取jsapi_ticket问题

public JSONObject index1(Model model,HttpServletRequest request) { String code=request.getParameter("code"); net.sf.json.JSONObject jsonObject=WeChatUtils.getOpenId(code);//获取微信用户access_token String openid=jsonObject.getString("openid"); String access_token=jsonObject.getString("access_token"); HttpSession session=request.getSession(); session.setAttribute("access_token",access_token); session.setAttribute("openid",openid); System.out.println("index1-- access_token:"+access_token); // String refresh_token =jsonObject.getString("refresh_token"); net.sf.json.JSONObject ticket =WeChatUtils.getJsapi_ticket(access_token); String jsapi_ticket=jsonObject.getString("ticket");//通过access_token获取jsapi_ticket System.out.println("jsapi_ticket:"+jsapi_ticket); -------WechatUtil.java public static JSONObject getOpenId(String code) { String path=OAUTHUSERINFO.replace("APPID", appid).replace("SECRET", appsecret).replace("CODE", code); System.out.println("调用微信api url:"+path); JSONObject wxjsonObject=HttpRequest(path); return wxjsonObject; } private static JSONObject HttpRequest(String requestUrl) { JSONObject jsonObject=null; StringBuffer buffer=new StringBuffer(); InputStream inputStream=null; try { URL url=new URL(requestUrl); HttpsURLConnection httpsURLConnection=(HttpsURLConnection) url.openConnection(); httpsURLConnection.setDoOutput(true); httpsURLConnection.setDoInput(true); httpsURLConnection.setUseCaches(false); //设置请求方式 httpsURLConnection.setRequestMethod("GET"); httpsURLConnection.connect(); inputStream=httpsURLConnection.getInputStream(); InputStreamReader inputStreamReader=new InputStreamReader(inputStream,"utf-8"); BufferedReader bufferedReader=new BufferedReader(inputStreamReader); String str=null; while((str=bufferedReader.readLine())!=null) { buffer.append(str); } bufferedReader.close(); inputStreamReader.close(); //释放资源 inputStream.close(); inputStream=null; httpsURLConnection.disconnect(); jsonObject=JSONObject.fromObject(buffer.toString()); System.out.println(buffer.toString()); }catch(ConnectException ce) { ce.printStackTrace(); System.out.println("WeChat server connection timed out"); }catch(Exception e) { e.printStackTrace(); System.out.println("http request error:{}"); }finally { try { if(inputStream!=null) { inputStream.close(); } }catch(IOException e) { e.printStackTrace(); } } return jsonObject; } 初接触微信公众号开发, 前端传个code过来,根据code获取的access_token,获取jsapi_ticket时提示invalid credential, access_token is invalid or not latest hint access_token是可以获取到的,可是为什么jsapi_ticket获取失败?问题出在什么地方,做的的麻烦给看看

谁能帮我写一个点击按钮后提示正在加载,然后js get json返回的数据。插入指定DIV中

谁能帮我写一个点击按钮后提示正在加载,然后js get json返回的数据(本服务器,没有跨域)。然后把内容分别插入到load DIV中 。我自己找了好多试了都没有效果,没有办法才来发帖子的。在此先感谢了 ``` <div id="load">正在加载...</div> ``` 返回格式如下, ``` {"ok":true,"ww":"yybb","text":"爱我中国"} ```

急需Java 供外部调用的api的一个demo实例

写接口把json格式封装起来 用post请求的接口的方式 框架用springmvc

一个关于java对象的内存指向的问题菜鸟问题

java的spring框架,在controller中private一个object对象,用来返回json数据的。这个controller下的多个mapping方法。都会new一个新的对象指向。但是调用这个controller时候,有时候会出现数据错误。但是断点跟踪时候,bean层的数据是准确的。当每个mapping方法不用开始的private的对象直接 object json=new objcet ,数据错误好像正常了,但是自己写一个小demo测试发现数据也没有问题。请大神费点笔墨指点下到底传说中底层的对象的内存指向是同一个多人请求时候出现数据重复覆盖吗?![图片说明](https://img-ask.csdn.net/upload/201706/01/1496279544_832374.png)

支付宝java服务端 测试报错 大神来救

根本不理解支付宝提供的demo 从网上使用别人的源码 String orderStr=""; try { Map<String, String> orderMap = new LinkedHashMap<String, String>(); // 订单实体 Map<String, String> bizModel = new LinkedHashMap<String, String>(); // 公共实体 /****** 2.商品参数封装开始 *****/ // 手机端用 // 商户订单号,商户网站订单系统中唯一订单号,必填 orderMap.put("out_trade_no", "100000"); // 订单名称,必填 orderMap.put("subject", "***支付"); // 付款金额,必填 orderMap.put("total_amount", String.valueOf(10000)); // 销售产品码 必填 orderMap.put("product_code", "QUICK_WAP_PAY"); /****** --------------- 3.公共参数封装 开始 ------------------------ *****/ // 支付宝用 // 1.商户appid bizModel.put("app_id", AlipayConfig.APPID); // 2.请求网关地址 bizModel.put("method", AlipayConfig.URL); // 3.请求格式 bizModel.put("format", AlipayConfig.FORMAT); // 4.回调地址 bizModel.put("return_url", AlipayConfig.notify_url); // 5.私钥 bizModel.put("private_key", AlipayConfig.private_key); // 6.商家id bizModel.put("seller_id", AlipayConfig.partner); // 7.加密格式 bizModel.put("sign_type", AlipayConfig.sign_type + ""); /****** --------------- 3.公共参数封装 结束 ------------------------ *****/ // 实例化客户端 AlipayClient client = new DefaultAlipayClient(AlipayConfig.URL, AlipayConfig.APPID, AlipayConfig.private_key, AlipayConfig.FORMAT, AlipayConfig.input_charset, AlipayConfig.ali_public_key, AlipayConfig.sign_type); // 实例化具体API对应的request类,类名称和接口名称对应,当前调用接口名称:alipay.trade.app.pay AlipayTradeAppPayRequest ali_request = new AlipayTradeAppPayRequest(); // SDK已经封装掉了公共参数,这里只需要传入业务参数。以下方法为sdk的model入参方式(model和biz_content同时存在的情况下取biz_content)。 AlipayTradeAppPayModel model = new AlipayTradeAppPayModel(); // model.setPassbackParams(URLEncoder.encode((String)orderMap.get("body").toString()));; // //描述信息 添加附加数据 // model.setBody(orderMap.get("body")); //商品信息 model.setSubject(orderMap.get("subject")); // 商品名称 model.setOutTradeNo(orderMap.get("out_trade_no")); // 商户订单号(自动生成) model.setTotalAmount(orderMap.get("total_amount")); // 支付金额 model.setProductCode(orderMap.get("product_code")); // 销售产品码 model.setSellerId(AlipayConfig.partner); // 商家id ali_request.setBizModel(model); ali_request.setNotifyUrl(AlipayConfig.notify_url); // 回调地址 AlipayTradeAppPayResponse responses = client.sdkExecute(ali_request); orderStr = responses.getBody(); System.err.println(orderStr); // 就是orderString 可以直接给客户端请求,无需再做处理 } catch (Exception e) { e.printStackTrace(); } return orderStr; AlipayConfig是配置文件 包含密钥之类的 报错为 com.alipay.api.AlipayApiException: RSAcontent = alipay_sdk=alipay-sdk-java-dynamicVersionNo&app_id=2018030202299464&biz_content={"out_trade_no":"100000","product_code":"QUICK_WAP_PAY","seller_id":"2088031415344595","subject":"***支付","total_amount":"10000"}&charset=utf-8&format=json&method=alipay.trade.app.pay&sign_type=RSA2&timestamp=2018-04-12 11:55:38&version=1.0; charset = utf-8 at com.alipay.api.internal.util.AlipaySignature.rsa256Sign(AlipaySignature.java:141) at com.alipay.api.internal.util.AlipaySignature.rsaSign(AlipaySignature.java:102) at com.alipay.api.DefaultAlipayClient.getRequestHolderWithSign(DefaultAlipayClient.java:323) at com.alipay.api.DefaultAlipayClient.sdkExecute(DefaultAlipayClient.java:163) at com.yinuoapp.controller.Alipay00200009Controller.alipay(Alipay00200009Controller.java:83) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:497) at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:222) at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:137) at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:110) at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:814) at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:737) at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85) at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:959) at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:893) at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:969) at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:860) at javax.servlet.http.HttpServlet.service(HttpServlet.java:624) at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:845) at javax.servlet.http.HttpServlet.service(HttpServlet.java:731) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208) at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208) at com.yinuo.server.Filters.doFilter(Filters.java:50) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208) at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:121) at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:218) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122) at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:505) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:169) at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103) at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:958) at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:452) at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1087) at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:637) at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:316) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) at java.lang.Thread.run(Thread.java:745) Caused by: java.security.spec.InvalidKeySpecException: java.security.InvalidKeyException: IOException : DER input, Integer tag error at sun.security.rsa.RSAKeyFactory.engineGeneratePrivate(RSAKeyFactory.java:217) at java.security.KeyFactory.generatePrivate(KeyFactory.java:372) at com.alipay.api.internal.util.AlipaySignature.getPrivateKeyFromPKCS8(AlipaySignature.java:202) at com.alipay.api.internal.util.AlipaySignature.rsa256Sign(AlipaySignature.java:123) ... 48 more Caused by: java.security.InvalidKeyException: IOException : DER input, Integer tag error at sun.security.pkcs.PKCS8Key.decode(PKCS8Key.java:351) at sun.security.pkcs.PKCS8Key.decode(PKCS8Key.java:356) at sun.security.rsa.RSAPrivateCrtKeyImpl.<init>(RSAPrivateCrtKeyImpl.java:91) at sun.security.rsa.RSAPrivateCrtKeyImpl.newKey(RSAPrivateCrtKeyImpl.java:75) at sun.security.rsa.RSAKeyFactory.generatePrivate(RSAKeyFactory.java:316) at sun.security.rsa.RSAKeyFactory.engineGeneratePrivate(RSAKeyFactory.java:213) ... 51 more 根本不懂 求大神救我

关于启用线程获取网络消息然后添加到布局中,不出现是怎么回事啊

不说什么,直接上代码 package textview.exam; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.ListView; import android.widget.SimpleAdapter; import com.baidu.apistore.sdk.ApiCallBack; import com.baidu.apistore.sdk.ApiStoreSDK; import com.baidu.apistore.sdk.network.Parameters; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class FragmentMainchatnews extends Fragment { private Button button; private Bitmap imageView; @Override public void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); } public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View view = inflater.inflate(R.layout.main_chat_news, null); Thread thread=new Thread(runnable); return view; } //创建Hander对象,用于接收子线程的 Handler handler = new Handler() { public void handleMessage(android.os.Message msg) { if (msg.arg1 == 1) { List listitem=(List) msg.obj; // 创建一个SimpleAdapter实现界面的更新 SimpleAdapter simpleAdapter = new SimpleAdapter(getActivity(), listitem, R.layout.news_simple_item, new String[]{"image", "title", "abs"}, new int[]{R.id.image, R.id.title, R.id.abs}); ListView list = (ListView) getView().findViewById(R.id.chat_news); // 为ListView设置Adapter list.setAdapter(simpleAdapter); //imageView.setImageBitmap(bitmap); } } ; }; //开启子线程得到数据 Runnable runnable; { runnable = new Runnable() { public void run() { final Message message = handler.obtainMessage(); Parameters para = new Parameters(); //para.put("keyword", "娱乐"); ApiStoreSDK.execute("http://apis.baidu.com/songshuxiansheng/news/news", ApiStoreSDK.GET, para, new ApiCallBack() { @Override public void onSuccess(int status, String responseString) { Log.i("连接状态:", "连接成功"); try { JSONObject dataJson = new JSONObject(responseString); JSONArray data = dataJson.getJSONArray("retData"); // 创建一个List集合,List集合的元素是Map List<Map<String, Object>> listItems = new ArrayList<Map<String, Object>>(); for (int i = 0; i < 5; i++) { JSONObject info = data.getJSONObject(i); Map<String, Object> listItem = new HashMap<String, Object>(); //imageView = getHttpBitmap(info.getString("image_url")); listItem.put("title", info.getString("title")); //listItem.put("image",imageView); listItem.put("abs", info.getString("abstract")); listItems.add(listItem); message.obj = listItems; //定义标识子线程 message.arg1 = 1; handler.sendMessage(message); } } catch (JSONException e) { Log.i("获取到数据:", responseString); } } @Override public void onComplete() { Log.i("sdkdemo", "onComplete"); } @Override public void onError(int status, String responseString, Exception e) { Log.i("sdkdemo", "onError, status: " + status); Log.i("sdkdemo", "errMsg: " + (e == null ? "" : e.getMessage())); } }); } }; } //获取网络图片 private Bitmap getHttpBitmap(String urlString) { URL url; Bitmap bitmap = null; try { url = new URL(urlString); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setConnectTimeout(6000); connection.setDoInput(true); connection.setUseCaches(true); InputStream is = connection.getInputStream(); bitmap = BitmapFactory.decodeStream(is); is.close(); } catch (MalformedURLException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return bitmap; } }

bootstrap table怎么想java传参数

这是js ``` function load1() { var state=parent.$("input[name='state']:checked").val(); alert(state) $('#exampleTable') .bootstrapTable( { method : 'get', // 服务器数据的请求方式 get or post url : prefix + "/list", // 服务器数据的加载地址 queryParams:function(params){//向后台传值 return{ offset:params.offset, limit:params.limit, state:parent.$("input[name='state']:checked").val() } }, // showRefresh : true, // showToggle : true, // showColumns : true, iconSize : 'outline', toolbar : '#exampleToolbar', striped : true, // 设置为true会有隔行变色效果 dataType : "json", // 服务器返回的数据类型 pagination : true, // 设置为true会在底部显示分页条 // queryParamsType : "limit", // //设置为limit则会发送符合RESTFull格式的参数 singleSelect : false, // 设置为true将禁止多选 // contentType : "application/x-www-form-urlencoded", // //发送到服务器的数据编码类型 pageSize : 10, // 如果设置了分页,每页数据条数 pageNumber : 1, // 如果设置了分布,首页页码 //search : true, // 是否显示搜索框 showColumns : false, // 是否显示内容下拉框(选择显示的列) sidePagination : "server", // 设置在哪里进行分页,可选值为"client" 或者 "server" queryParams : function(params) { return { //说明:传入后台的参数包括offset开始索引,limit步长,sort排序列,order:desc或者,以及所有列的键值对 limit: params.limit, offset:params.offset, name:$('#searchName').val() // username:$('#searchName').val() }; }, // //请求服务器数据时,你可以通过重写参数的方式添加一些额外的参数,例如 toolbar 中的参数 如果 // queryParamsType = 'limit' ,返回参数必须包含 // limit, offset, search, sort, order 否则, 需要包含: // pageSize, pageNumber, searchText, sortName, // sortOrder. // 返回false将会终止请求 } ``` 这是java ``` @ResponseBody @RequestMapping("/list") public PageUtils list(@RequestParam Map<String, Object> params,String state){ System.out.println(state); //查询列表数据 Query query = new Query(params); List<WagesDO> wagesList = wagesService.list(query); int total = wagesService.count(query); PageUtils pageUtils = new PageUtils(wagesList, total); return pageUtils; } ``` 这样写在java接受到的是state为null,这是为什么y

layui中表格的url数据接口指向什么路径?

难受~![图片说明](https://img-ask.csdn.net/upload/201910/25/1571965877_562145.png)

使用HttpClient进行登录验证

<div class="post-text" itemprop="text"> <p>I am trying to send a POST request to a php file and when the user is asked for login information, if wrong, it prints the json message from the php file and if right, it allows user to login. However, my application crashes, giving a NetworkOnThreadMainException pointing errors to three lines.</p> <pre><code> HttpResponse response=httpClient.execute(httpPost); public class LoginActivity extends ActionBarActivity { login(); </code></pre> <p>So how can i make this possible? This is some part of the code I have written:</p> <pre><code>public class LoginActivity extends ActionBarActivity { EditText et, et2; ImageButton ib5; String name,pwd; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_login); et = (EditText) findViewById(R.id.editText); et2 = (EditText) findViewById(R.id.editText2); ib5 = (ImageButton) findViewById(R.id.imageButton5); name=et.getText().toString(); pwd=et2.getText().toString(); final LoginActivity loginActivity=null; ib5.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { //login(); new DownloadFilesTask(loginActivity,name,pwd).doInBackground(); } }); } public void login() { new LoginTask(this, et.getText().toString(), et2.getText().toString()); } private class LoginTask { public LoginTask(LoginActivity loginActivity, String name, String pwd) { } } void navigatetoMainActivity() { Intent homeIntent = new Intent(getApplicationContext(), MainActivity.class); homeIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); startActivity(homeIntent); } void InvalidToast(){ Toast.makeText(getApplicationContext(), "Please enter valid name and password", Toast.LENGTH_LONG).show(); } void EmptyToast(){ Toast.makeText(getApplicationContext(), "Please fill the form, don't leave any field blank", Toast.LENGTH_LONG).show(); } } </code></pre> <p>DownloadFilesTask.java</p> <pre><code>public class DownloadFilesTask extends AsyncTask&lt;String, String, String&gt; { private String name, pwd; private LoginActivity loginActivity; public DownloadFilesTask(LoginActivity loginActivity,String name, String pwd){ this.loginActivity=loginActivity; this.name=name; this.pwd=pwd; } @Override protected String doInBackground(String... strings) { HttpClient httpClient=new DefaultHttpClient(); HttpPost httpPost=new HttpPost("login.php"); List&lt;NameValuePair&gt; nameValuePairs=new ArrayList&lt;NameValuePair&gt;(2); String result=null; nameValuePairs.add(new BasicNameValuePair("name", name)); nameValuePairs.add(new BasicNameValuePair("password", pwd)); try { httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } HttpResponse response= null; try { response = httpClient.execute(httpPost); //error is given here } catch (IOException e) { e.printStackTrace(); } HttpEntity entity=response.getEntity(); InputStream instream= null; try { instream = entity.getContent(); } catch (IOException e) { e.printStackTrace(); } result=convertStreamToString(instream); try { instream.close(); } catch (IOException e) { e.printStackTrace(); } if (Utility.isNotNull(name) &amp;&amp; Utility.isNotNull(pwd)) { RequestParams params = new RequestParams(); if (Utility.validate(name, pwd)) { params.put("username", name); params.put("password", pwd); onPostExecute(); } else { loginActivity.InvalidToast(); } } else { loginActivity.EmptyToast(); } return result; } private String convertStreamToString(InputStream instream) { BufferedReader reader=new BufferedReader(new InputStreamReader(instream)); StringBuilder sb=new StringBuilder(); String line=null; try { while ((line=reader.readLine())!=null){ sb.append(line + " "); } } catch (IOException e) { e.printStackTrace(); }finally{ try { instream.close(); } catch (IOException e) { e.printStackTrace(); } } return sb.toString(); } protected void onPostExecute(){ loginActivity.navigatetoMainActivity(); } private static class Utility { static Pattern pattern; static Matcher matcher; static Pattern pattern1; static Matcher matcher1; static String NAME_PATTERN="SuperBoise"; static String PWD_PATTERN="qwerty"; public static boolean validate(String name,String pwd){ pattern=Pattern.compile(NAME_PATTERN); pattern1=Pattern.compile(PWD_PATTERN); matcher=pattern.matcher(name); matcher1=pattern1.matcher(pwd); return matcher.matches()&amp;&amp; matcher1.matches(); } public static boolean isNotNull(String name) { return name!=null &amp;&amp; name.trim().length()&gt;0 ? true: false; } } } </code></pre> </div>

C#怎么获取网络接口?url写什么?token怎么验证?有点急。。。

``` string url = "xxxxx?PlateNumber=%E2%3A%36C78673&DeliveryPointCode=CC_0001"; WebRequest wRequest = WebRequest.Create(url); wRequest.Method = "GET"; wRequest.ContentType = "text/html;charset=UTF-8"; WebResponse wResponse = wRequest.GetResponse(); Stream stream = wResponse.GetResponseStream(); StreamReader reader = new StreamReader(stream, System.Text.Encoding.Default); string str = reader.ReadToEnd(); //url返回的值 reader.Close(); wResponse.Close(); ``` 在第四行wRequest.GetResponse()报了未授权的错误。![图片说明](https://img-ask.csdn.net/upload/201812/08/1544245888_57136.png) wRequest不为空,是因为我url写错了吗,还是wRequest的构造少东西了,厂商给我提供的token应该在哪体现在哪里呢?在Header里吗?代码怎么写呢?刚毕业第一次用这个。。。有好心人提供一个demo吗。。我真的搞不定了。。哎

大神们关于javassist 动态编译的问题

//ClassPool:CtClass对象的容器 ClassPool pool = ClassPool.getDefault(); //通过ClassPool生成一个public新类Emp.java CtClass ctClass = pool.makeClass("javassist.demo.MyCC"); //添加自定义方法 CtMethod ctMethod = new CtMethod(CtClass.voidType,"printInfo",new CtClass[]{},ctClass); //为自定义方法设置修饰符 ctMethod.setModifiers(Modifier.PUBLIC); //为自定义方法设置函数体 StringBuffer buffer2 = new StringBuffer(); buffer2.append("{\nSystem.out.println(\"begin!\");\n") .append("}"); ctMethod.setBody(buffer2.toString()); ctClass.addMethod(ctMethod); 执行以下代码报错 ctClass.toClass(); 大神求解决 Exception in thread "main" java.lang.Error: Unresolved compilation problems: StackWalker cannot be resolved to a type StackWalker cannot be resolved to a type StackWalker cannot be resolved StackWalker cannot be resolved to a variable StackWalker cannot be resolved to a type StackWalker cannot be resolved to a type The method dropLookupMode(int) is undefined for the type MethodHandles.Lookup The method defineClass(byte[]) is undefined for the type MethodHandles.Lookup at javassist.util.proxy.DefineClassHelper$SecuredPrivileged$3.<init>(DefineClassHelper.java:53) at javassist.util.proxy.DefineClassHelper$SecuredPrivileged.<clinit>(DefineClassHelper.java:38) at javassist.util.proxy.DefineClassHelper.<clinit>(DefineClassHelper.java:177) at javassist.ClassPool.toClass(ClassPool.java:1120) at javassist.ClassPool.toClass(ClassPool.java:1083) at javassist.ClassPool.toClass(ClassPool.java:1041) at javassist.CtClass.toClass(CtClass.java:1278) at javassist.demo.GenerateNewClassByJavassist.main(GenerateNewClassByJavassist.java:46)

java做易宝支付,所有银行支付通道关闭!

![图片说明](https://img-ask.csdn.net/upload/201906/04/1559649020_753493.jpg) ``` (PaymentUtil工具类) public class PaymentUtil { private static String encodingCharset = "UTF-8"; /** * 生成hmac方法 * * @param p0_Cmd 业务类型 * @param p1_MerId 商户编号 * @param p2_Order 商户订单号 * @param p3_Amt 支付金额 * @param p4_Cur 交易币种 * @param p5_Pid 商品名称 * @param p6_Pcat 商品种类 * @param p7_Pdesc 商品描述 * @param p8_Url 商户接收支付成功数据的地址 * @param p9_SAF 送货地址 * @param pa_MP 商户扩展信息 * @param pd_FrpId 银行编码 * @param pr_NeedResponse 应答机制 * @param keyValue 商户密钥(公司密钥) * @return */ //此方法把原文参数全部放入StringBuilder封装数据 public static String buildHmac(String p0_Cmd,String p1_MerId, String p2_Order, String p3_Amt, String p4_Cur,String p5_Pid, String p6_Pcat, String p7_Pdesc,String p8_Url, String p9_SAF,String pa_MP,String pd_FrpId, String pr_NeedResponse,String keyValue) { StringBuilder sValue = new StringBuilder(); // 业务类型 sValue.append(p0_Cmd); // 商户编号 sValue.append(p1_MerId); // 商户订单号 sValue.append(p2_Order); // 支付金额 sValue.append(p3_Amt); // 交易币种 sValue.append(p4_Cur); // 商品名称 sValue.append(p5_Pid); // 商品种类 sValue.append(p6_Pcat); // 商品描述 sValue.append(p7_Pdesc); // 商户接收支付成功数据的地址 sValue.append(p8_Url); // 送货地址 sValue.append(p9_SAF); // 商户扩展信息 sValue.append(pa_MP); // 银行编码 sValue.append(pd_FrpId); // 应答机制 sValue.append(pr_NeedResponse); //调用易宝工具类加密算法,对所有原文进行加密,返回密文(公司密钥) return PaymentUtil.hmacSign(sValue.toString(), keyValue); } /** * 返回校验hmac方法 * * @param hmac 支付网关发来的加密验证码 * @param p1_MerId 商户编号 * @param r0_Cmd 业务类型 * @param r1_Code 支付结果 * @param r2_TrxId 易宝支付交易流水号 * @param r3_Amt 支付金额 * @param r4_Cur 交易币种 * @param r5_Pid 商品名称 * @param r6_Order 商户订单号 * @param r7_Uid 易宝支付会员ID * @param r8_MP 商户扩展信息 * @param r9_BType 交易结果返回类型 * @param keyValue 密钥 * @return */ public static boolean verifyCallback(String hmac, String p1_MerId, String r0_Cmd, String r1_Code, String r2_TrxId, String r3_Amt, String r4_Cur, String r5_Pid, String r6_Order, String r7_Uid, String r8_MP, String r9_BType, String keyValue) { StringBuilder sValue = new StringBuilder(); // 商户编号 sValue.append(p1_MerId); // 业务类型 sValue.append(r0_Cmd); // 支付结果 sValue.append(r1_Code); // 易宝支付交易流水号 sValue.append(r2_TrxId); // 支付金额 sValue.append(r3_Amt); // 交易币种 sValue.append(r4_Cur); // 商品名称 sValue.append(r5_Pid); // 商户订单号 sValue.append(r6_Order); // 易宝支付会员ID sValue.append(r7_Uid); // 商户扩展信息 sValue.append(r8_MP); // 交易结果返回类型 sValue.append(r9_BType); String sNewString = PaymentUtil.hmacSign(sValue.toString(), keyValue); return sNewString.equals(hmac); } /** * @param aValue * @param aKey * @return */ //把原文和公司密钥传入hmacSign方法进行算法加密得到密文(字符串) public static String hmacSign(String aValue, String aKey) { byte k_ipad[] = new byte[64]; byte k_opad[] = new byte[64]; byte keyb[]; byte value[]; try { keyb = aKey.getBytes(encodingCharset); value = aValue.getBytes(encodingCharset); } catch (UnsupportedEncodingException e) { keyb = aKey.getBytes(); value = aValue.getBytes(); } Arrays.fill(k_ipad, keyb.length, 64, (byte) 54); Arrays.fill(k_opad, keyb.length, 64, (byte) 92); for (int i = 0; i < keyb.length; i++) { k_ipad[i] = (byte) (keyb[i] ^ 0x36); k_opad[i] = (byte) (keyb[i] ^ 0x5c); } MessageDigest md = null; try { md = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { return null; } md.update(k_ipad); md.update(value); byte dg[] = md.digest(); md.reset(); md.update(k_opad); md.update(dg, 0, 16); dg = md.digest(); return toHex(dg); } public static String toHex(byte input[]) { if (input == null) return null; StringBuffer output = new StringBuffer(input.length * 2); for (int i = 0; i < input.length; i++) { int current = input[i] & 0xff; if (current < 16) output.append("0"); output.append(Integer.toString(current, 16)); } return output.toString(); } /** * * @param args * @param key * @return */ public static String getHmac(String[] args, String key) { if (args == null || args.length == 0) { return (null); } StringBuffer str = new StringBuffer(); for (int i = 0; i < args.length; i++) { str.append(args[i]); } return (hmacSign(str.toString(), key)); } /** * @param aValue * @return */ public static String digest(String aValue) { aValue = aValue.trim(); byte value[]; try { value = aValue.getBytes(encodingCharset); } catch (UnsupportedEncodingException e) { value = aValue.getBytes(); } MessageDigest md = null; try { md = MessageDigest.getInstance("SHA"); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); return null; } return toHex(md.digest(value)); } // public static void main(String[] args) { // System.out.println(hmacSign("AnnulCard1000043252120080620160450.0http://localhost/SZXpro/callback.asp杩?4564868265473632445648682654736324511","8UPp0KE8sq73zVP370vko7C39403rtK1YwX40Td6irH216036H27Eb12792t")); // } } merchantInfo.properties(配置文件) p1_MerId=10001126856 keyValue=69cl522AV6q613Ii4W6u8K6XuW8vM1N6bFgyv769220IuYe9u37N4y7rI4Pl responseURL=http://api.ecps.com:8080/OrderServlet?method=callback (OrderServlet) @WebServlet(urlPatterns = "/OrderServlet") public class OrderServlet extends BaseServlet { //支付,请求方法 public void pay(HttpServletRequest request,HttpServletResponse response) throws Exception{ // 接受参数 String address=request.getParameter("address"); String name=request.getParameter("name"); String telephone=request.getParameter("telephone"); String oid=request.getParameter("oid"); // 调用业务层方法,更新订单信息 ordersService.updateOrder(name,address,telephone,oid); // 组织发送支付公司需要哪些数据 String pd_FrpId = request.getParameter("pd_FrpId"); String p0_Cmd = "Buy"; String p1_MerId = ResourceBundle.getBundle("merchantInfo").getString("p1_MerId"); String p2_Order = oid; String p3_Amt = "0.01"; String p4_Cur = "CNY"; String p5_Pid = ""; String p6_Pcat = ""; String p7_Pdesc = ""; // 支付成功回调地址 ---- 第三方支付公司会访问、用户访问 // 第三方支付可以访问网址 String p8_Url = ResourceBundle.getBundle("merchantInfo").getString("responseURL"); String p9_SAF = ""; String pa_MP = ""; String pr_NeedResponse = "1"; // 加密hmac 需要密钥 String keyValue = ResourceBundle.getBundle("merchantInfo").getString("keyValue"); // 传入回调地址 String hmac = PaymentUtil.buildHmac(p0_Cmd, p1_MerId, p2_Order, p3_Amt, p4_Cur, p5_Pid, p6_Pcat, p7_Pdesc, p8_Url, p9_SAF, pa_MP, pd_FrpId, pr_NeedResponse, keyValue); // 发送给第三方 StringBuffer sb = new StringBuffer("https://www.yeepay.com/app-merchant-proxy/node?"); sb.append("p0_Cmd=").append(p0_Cmd).append("&"); sb.append("p1_MerId=").append(p1_MerId).append("&"); sb.append("p2_Order=").append(p2_Order).append("&"); sb.append("p3_Amt=").append(p3_Amt).append("&"); sb.append("p4_Cur=").append(p4_Cur).append("&"); sb.append("p5_Pid=").append(p5_Pid).append("&"); sb.append("p6_Pcat=").append(p6_Pcat).append("&"); sb.append("p7_Pdesc=").append(p7_Pdesc).append("&"); sb.append("p8_Url=").append(p8_Url).append("&"); sb.append("p9_SAF=").append(p9_SAF).append("&"); sb.append("pa_MP=").append(pa_MP).append("&"); sb.append("pd_FrpId=").append(pd_FrpId).append("&"); sb.append("pr_NeedResponse=").append(pr_NeedResponse).append("&"); sb.append("hmac=").append(hmac); // Ajax跨域请求不能使用重定向,不能使用转发 // respone.sendRedirect(sb.toString()); //把sb的数据封装到JSON响应会页面 Result re = new Result(Result.SUCCESS,"",sb.toString()); response.getWriter().print(JSONObject.fromObject(re)); // return null; } /*callBack 获取易宝数据,并做比较.数据是否有效,有效则支付成功,支付后的回调方法*/ public String callback(HttpServletRequest request,HttpServletResponse response) throws Exception{ String p1_MerId = request.getParameter("p1_MerId"); String r0_Cmd = request.getParameter("r0_Cmd"); String r1_Code = request.getParameter("r1_Code"); String r2_TrxId = request.getParameter("r2_TrxId"); String r3_Amt = request.getParameter("r3_Amt"); String r4_Cur = request.getParameter("r4_Cur"); String r5_Pid = request.getParameter("r5_Pid"); String r6_Order = request.getParameter("r6_Order"); String r7_Uid = request.getParameter("r7_Uid"); String r8_MP = request.getParameter("r8_MP"); String r9_BType = request.getParameter("r9_BType"); String rb_BankId = request.getParameter("rb_BankId"); String ro_BankOrderId = request.getParameter("ro_BankOrderId"); String rp_PayDate = request.getParameter("rp_PayDate"); String rq_CardNo = request.getParameter("rq_CardNo"); String ru_Trxtime = request.getParameter("ru_Trxtime"); // 身份校验 --- 判断是不是支付公司通知你 String hmac = request.getParameter("hmac"); String keyValue = ResourceBundle.getBundle("merchantInfo").getString( "keyValue"); // 自己对上面数据进行加密 --- 比较支付公司发过来hamc boolean isValid = PaymentUtil.verifyCallback(hmac, p1_MerId, r0_Cmd, r1_Code, r2_TrxId, r3_Amt, r4_Cur, r5_Pid, r6_Order, r7_Uid, r8_MP, r9_BType, keyValue); //判断数据是否有效 if (isValid) { // 响应数据有效 if (r9_BType.equals("1")) { // 浏览器重定向 System.out.println("111"); request.setAttribute("msg", "您的订单号为:"+r6_Order+",金额为:"+r3_Amt+"已经支付成功,等待发货~~"); } else if (r9_BType.equals("2")) { // 修改订单状态: // 服务器点对点 --- 支付公司通知你 System.out.println("付款成功!222"); // 修改订单状态 为已付款 // 回复支付公司success,如果不回复,支付公司会一直通知 response.getWriter().print("success"); } //订单状态,更新订单状态为已经付款 ordersService.updateOrderState(r6_Order); } else { // 数据无效 System.out.println("数据被篡改!"); } return "/jsp/msg.jsp"; } ```

java微信公众号模板消息发送接口问题

java代码如下 ``` /** * 发送注册成功模板消息 * @return */ public static String toSendModelMessage(String openId,String phone,String id,String dayStr){ String accessToken=getAccessToken(); if(accessToken.length()<=0){ return ""; } System.out.println("accessToken==="+accessToken); String urlStr="https://api.weixin.qq.com/cgi-bin/message/template/send?access_token="+accessToken; try { URL url = new URL(urlStr); HttpURLConnection urlConnection = (HttpURLConnection)url.openConnection(); urlConnection.setDoOutput(true); urlConnection.setDoInput(true); urlConnection.setRequestMethod("POST"); urlConnection.setUseCaches(false); urlConnection.setInstanceFollowRedirects(true); urlConnection.setRequestProperty("Content-Type","application/x-www-form-urlencoded"); urlConnection.setRequestProperty("Charset", "UTF-8"); urlConnection.connect(); DataOutputStream out = new DataOutputStream(urlConnection.getOutputStream()); String params="{"+ "\"touser\":\""+openId+"\","+ "\"template_id\":\"ZvG8sGRKqo2Hk-OFRkHVLbvaeZTX7DDJFyS3G-0mb4A\","+ "\"url\":\"http://map.baidu.com/\","+ "\"topcolor\":\"#FF0000\","+ "\"data\":{"+ "\"first\": {"+ "\"value\":\"客官,恭喜您成功注册为VIP\","+ "\"color\":\"#173177\""+ "},"+ "\"keyword1\":{"+ "\"value\":\""+phone+"\","+ "\"color\":\"#173177\""+ "},"+ "\"keyword2\":{"+ "\"value\":\""+id+"\","+ "\"color\":\"#173177\""+ "},"+ "\"keyword3\":{"+ "\"value\":\""+dayStr+"\","+ "\"color\":\"#173177\""+ "},"+ "\"remark\":{"+ "\"value\":\"点击跳转\","+ "\"color\":\"#173177\""+ "}"+ "}"+ "}"; System.out.println(params); out.writeBytes(params); out.flush(); out.close(); BufferedReader reader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream(),"UTF-8")); String line; String responseStr=""; while ((line = reader.readLine()) != null){ responseStr+=line; } System.out.println(responseStr); reader.close(); urlConnection.disconnect(); }catch (MalformedURLException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ProtocolException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return ""; } ``` 返回的结果如下 ``` {"errcode":47001,"errmsg":"data format error hint: [IGparA0715ge14]"} ``` 以下是我打印出来的请求json ``` { "touser":"on3mAwuljdY12JuRbua28EUCgW9o", "template_id":"ZvG8sGRKqo2Hk-OFRkHVLbvaeZTX7DDJFyS3G-0mb4A", "url":"http://map.baidu.com/", "topcolor":"#FF0000", "data":{ "first":{ "value":"客官,恭喜您成功注册为VIP", "color":"#173177" }, "keyword1":{ "value":"18520040243", "color":"#173177" }, "keyword2":{ "value":"5", "color":"#173177" }, "keyword3":{ "value":"2014年7月21日 18:36", "color":"#173177" }, "remark":{ "value":"点击跳转", "color":"#173177" } } } ``` 很想知道我错在哪!求有经验的同学指点下

Android http client response500错误,求大神帮忙看看代码!

http://121.42.195.113/usay/register.jsp服务器这里没错啊。。。。但不知道为什么放到安卓上就不行 package com.example.demo_jsom1; import java.io.IOException; import java.util.ArrayList; import java.util.List; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.HttpClient; import org.apache.http.client.entity.UrlEncodedFormEntity; 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.BasicNameValuePair; import org.apache.http.protocol.HTTP; import org.apache.http.util.EntityUtils; import org.json.JSONObject; import android.app.Activity; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.TextView; public class MainActivity extends Activity implements OnClickListener { // 声明控件 //private EditText et_name, et_pass; private TextView tv_result; Handler handler =new Handler(){ @Override //当有消息发送出来的时候就执行Handler的这个方法 public void handleMessage(Message msg){ super.handleMessage(msg); //根据msg需求处理UI switch(msg.what){ case 1: String response = (String) msg.obj; tv_result.setText(response); } } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // 获取控件对象 //et_name = (EditText) findViewById(R.id.et_name); //用户名控件 //et_pass = (EditText) findViewById(R.id.et_pass);//密码控件 //tv_result = (TextView) findViewById(R.id.tv_result);//服务器端返回数据显示的控件 Button a = (Button) findViewById(R.id.login); tv_result = (TextView)findViewById(R.id.JSONtextView); a.setOnClickListener(this); } @Override public void onClick(View v) { // TODO Auto-generated method stub switch(v.getId()) { case R.id.login: SENDREQUEST(); Log.i("connectbutton", "1"); break; default: break; } } private void SENDREQUEST() { // TODO Auto-generated method stub new Thread() { @Override public void run() { try{ //网络传输 HttpClient httpclient = new DefaultHttpClient(); String uri = "http://121.42.195.113/usay/register.action"; HttpPost httppost = new HttpPost(uri); JSONObject obj = new JSONObject(); //放入键值对 obj.put("userAccount", "15602385611"); obj.put("userPassword", "123qwertyuiop"); //封装好发送 httppost.setEntity(new StringEntity(obj.toString()) ); //创建接收实例 HttpResponse reponse = httpclient.execute(httppost); //检验状态吗,如果成功接收数据 HttpEntity entity = reponse.getEntity(); int code = reponse.getStatusLine().getStatusCode(); Log.i("connectif", code +""); if(code == 200) { String rev = EntityUtils.toString(reponse.getEntity()); obj = new JSONObject(rev); //接收数据 String result = obj.getString("result"); //将服务器中返回的结果存放进message中 Message message = new Message(); message.what = 1; //obj传入对象 message.obj = result; handler.sendMessage(message); Log.i("result", result); }else{ Log.i("connectfalse", "4"); } }catch(ClientProtocolException e) { }catch(IOException E){ } catch (Exception e){ e.printStackTrace(); } } }.start(); } } ``` ```

大学四年自学走来,这些私藏的实用工具/学习网站我贡献出来了

大学四年,看课本是不可能一直看课本的了,对于学习,特别是自学,善于搜索网上的一些资源来辅助,还是非常有必要的,下面我就把这几年私藏的各种资源,网站贡献出来给你们。主要有:电子书搜索、实用工具、在线视频学习网站、非视频学习网站、软件下载、面试/求职必备网站。 注意:文中提到的所有资源,文末我都给你整理好了,你们只管拿去,如果觉得不错,转发、分享就是最大的支持了。 一、电子书搜索 对于大部分程序员...

在中国程序员是青春饭吗?

今年,我也32了 ,为了不给大家误导,咨询了猎头、圈内好友,以及年过35岁的几位老程序员……舍了老脸去揭人家伤疤……希望能给大家以帮助,记得帮我点赞哦。 目录: 你以为的人生 一次又一次的伤害 猎头界的真相 如何应对互联网行业的「中年危机」 一、你以为的人生 刚入行时,拿着傲人的工资,想着好好干,以为我们的人生是这样的: 等真到了那一天,你会发现,你的人生很可能是这样的: ...

Java基础知识面试题(2020最新版)

文章目录Java概述何为编程什么是Javajdk1.5之后的三大版本JVM、JRE和JDK的关系什么是跨平台性?原理是什么Java语言有哪些特点什么是字节码?采用字节码的最大好处是什么什么是Java程序的主类?应用程序和小程序的主类有何不同?Java应用程序与小程序之间有那些差别?Java和C++的区别Oracle JDK 和 OpenJDK 的对比基础语法数据类型Java有哪些数据类型switc...

我以为我学懂了数据结构,直到看了这个导图才发现,我错了

数据结构与算法思维导图

技术大佬:我去,你写的 switch 语句也太老土了吧

昨天早上通过远程的方式 review 了两名新来同事的代码,大部分代码都写得很漂亮,严谨的同时注释也很到位,这令我非常满意。但当我看到他们当中有一个人写的 switch 语句时,还是忍不住破口大骂:“我擦,小王,你丫写的 switch 语句也太老土了吧!” 来看看小王写的代码吧,看完不要骂我装逼啊。 private static String createPlayer(PlayerTypes p...

和黑客斗争的 6 天!

互联网公司工作,很难避免不和黑客们打交道,我呆过的两家互联网公司,几乎每月每天每分钟都有黑客在公司网站上扫描。有的是寻找 Sql 注入的缺口,有的是寻找线上服务器可能存在的漏洞,大部分都...

Linux 会成为主流桌面操作系统吗?

整理 |屠敏出品 | CSDN(ID:CSDNnews)2020 年 1 月 14 日,微软正式停止了 Windows 7 系统的扩展支持,这意味着服役十年的 Windows 7,属于...

讲一个程序员如何副业月赚三万的真实故事

loonggg读完需要3分钟速读仅需 1 分钟大家好,我是你们的校长。我之前讲过,这年头,只要肯动脑,肯行动,程序员凭借自己的技术,赚钱的方式还是有很多种的。仅仅靠在公司出卖自己的劳动时...

学习总结之HTML5剑指前端(建议收藏,图文并茂)

前言学习《HTML5与CSS3权威指南》这本书很不错,学完之后我颇有感触,觉得web的世界开明了许多。这本书是需要有一定基础的web前端开发工程师。这本书主要学习HTML5和css3,看...

女程序员,为什么比男程序员少???

昨天看到一档综艺节目,讨论了两个话题:(1)中国学生的数学成绩,平均下来看,会比国外好?为什么?(2)男生的数学成绩,平均下来看,会比女生好?为什么?同时,我又联想到了一个技术圈经常讨...

搜狗输入法也在挑战国人的智商!

故事总是一个接着一个到来...上周写完《鲁大师已经彻底沦为一款垃圾流氓软件!》这篇文章之后,鲁大师的市场工作人员就找到了我,希望把这篇文章删除掉。经过一番沟通我先把这篇文章从公号中删除了...

副业收入是我做程序媛的3倍,工作外的B面人生是怎样的?

提到“程序员”,多数人脑海里首先想到的大约是:为人木讷、薪水超高、工作枯燥…… 然而,当离开工作岗位,撕去层层标签,脱下“程序员”这身外套,有的人生动又有趣,马上展现出了完全不同的A/B面人生! 不论是简单的爱好,还是正经的副业,他们都干得同样出色。偶尔,还能和程序员的特质结合,产生奇妙的“化学反应”。 @Charlotte:平日素颜示人,周末美妆博主 大家都以为程序媛也个个不修边幅,但我们也许...

MySQL数据库面试题(2020最新版)

文章目录数据库基础知识为什么要使用数据库什么是SQL?什么是MySQL?数据库三大范式是什么mysql有关权限的表都有哪几个MySQL的binlog有有几种录入格式?分别有什么区别?数据类型mysql有哪些数据类型引擎MySQL存储引擎MyISAM与InnoDB区别MyISAM索引与InnoDB索引的区别?InnoDB引擎的4大特性存储引擎选择索引什么是索引?索引有哪些优缺点?索引使用场景(重点)...

新一代神器STM32CubeMonitor介绍、下载、安装和使用教程

关注、星标公众号,不错过精彩内容作者:黄工公众号:strongerHuang最近ST官网悄悄新上线了一款比较强大的工具:STM32CubeMonitor V1.0.0。经过我研究和使用之...

记一次腾讯面试,我挂在了最熟悉不过的队列上……

腾讯后台面试,面试官问:如何自己实现队列?

如果你是老板,你会不会踢了这样的员工?

有个好朋友ZS,是技术总监,昨天问我:“有一个老下属,跟了我很多年,做事勤勤恳恳,主动性也很好。但随着公司的发展,他的进步速度,跟不上团队的步伐了,有点...

我入职阿里后,才知道原来简历这么写

私下里,有不少读者问我:“二哥,如何才能写出一份专业的技术简历呢?我总感觉自己写的简历太烂了,所以投了无数份,都石沉大海了。”说实话,我自己好多年没有写过简历了,但我认识的一个同行,他在阿里,给我说了一些他当年写简历的方法论,我感觉太牛逼了,实在是忍不住,就分享了出来,希望能够帮助到你。 01、简历的本质 作为简历的撰写者,你必须要搞清楚一点,简历的本质是什么,它就是为了来销售你的价值主张的。往深...

冒泡排序动画(基于python pygame实现)

本项目效果初始截图如下 动画见本人b站投稿:https://www.bilibili.com/video/av95491382 本项目对应github地址:https://github.com/BigShuang python版本:3.6,pygame版本:1.9.3。(python版本一致应该就没什么问题) 样例gif如下 ======================= 大爽歌作,mad

Redis核心原理与应用实践

Redis核心原理与应用实践 在很多场景下都会使用Redis,但是到了深层次的时候就了解的不是那么深刻,以至于在面试的时候经常会遇到卡壳的现象,学习知识要做到系统和深入,不要把Redis想象的过于复杂,和Mysql一样,是个读取数据的软件。 有一个理解是Redis是key value缓存服务器,更多的优点在于对value的操作更加丰富。 安装 yum install redis #yum安装 b...

现代的 “Hello, World”,可不仅仅是几行代码而已

作者 |Charles R. Martin译者 | 弯月,责编 | 夕颜头图 |付费下载自视觉中国出品 | CSDN(ID:CSDNnews)新手...

带了6个月的徒弟当了面试官,而身为高级工程师的我天天修Bug......

即将毕业的应届毕业生一枚,现在只拿到了两家offer,但最近听到一些消息,其中一个offer,我这个组据说客户很少,很有可能整组被裁掉。 想问大家: 如果我刚入职这个组就被裁了怎么办呢? 大家都是什么时候知道自己要被裁了的? 面试软技能指导: BQ/Project/Resume 试听内容: 除了刷题,还有哪些技能是拿到offer不可或缺的要素 如何提升面试软实力:简历, 行为面试,沟通能...

!大部分程序员只会写3年代码

如果世界上都是这种不思进取的软件公司,那别说大部分程序员只会写 3 年代码,恐怕就没有程序员这种职业。

离职半年了,老东家又发 offer,回不回?

有小伙伴问松哥这个问题,他在上海某公司,在离职了几个月后,前公司的领导联系到他,希望他能够返聘回去,他很纠结要不要回去? 俗话说好马不吃回头草,但是这个小伙伴既然感到纠结了,我觉得至少说明了两个问题:1.曾经的公司还不错;2.现在的日子也不是很如意。否则应该就不会纠结了。 老实说,松哥之前也有过类似的经历,今天就来和小伙伴们聊聊回头草到底吃不吃。 首先一个基本观点,就是离职了也没必要和老东家弄的苦...

2020阿里全球数学大赛:3万名高手、4道题、2天2夜未交卷

阿里巴巴全球数学竞赛( Alibaba Global Mathematics Competition)由马云发起,由中国科学技术协会、阿里巴巴基金会、阿里巴巴达摩院共同举办。大赛不设报名门槛,全世界爱好数学的人都可参与,不论是否出身数学专业、是否投身数学研究。 2020年阿里巴巴达摩院邀请北京大学、剑桥大学、浙江大学等高校的顶尖数学教师组建了出题组。中科院院士、美国艺术与科学院院士、北京国际数学...

为什么你不想学习?只想玩?人是如何一步一步废掉的

不知道是不是只有我这样子,还是你们也有过类似的经历。 上学的时候总有很多光辉历史,学年名列前茅,或者单科目大佬,但是虽然慢慢地长大了,你开始懈怠了,开始废掉了。。。 什么?你说不知道具体的情况是怎么样的? 我来告诉你: 你常常潜意识里或者心理觉得,自己真正的生活或者奋斗还没有开始。总是幻想着自己还拥有大把时间,还有无限的可能,自己还能逆风翻盘,只不是自己还没开始罢了,自己以后肯定会变得特别厉害...

HTTP与HTTPS的区别

面试官问HTTP与HTTPS的区别,我这样回答让他竖起大拇指!

程序员毕业去大公司好还是小公司好?

虽然大公司并不是人人都能进,但我仍建议还未毕业的同学,尽力地通过校招向大公司挤,但凡挤进去,你这一生会容易很多。 大公司哪里好?没能进大公司怎么办?答案都在这里了,记得帮我点赞哦。 目录: 技术氛围 内部晋升与跳槽 啥也没学会,公司倒闭了? 不同的人脉圈,注定会有不同的结果 没能去大厂怎么办? 一、技术氛围 纵观整个程序员技术领域,哪个在行业有所名气的大牛,不是在大厂? 而且众所...

男生更看重女生的身材脸蛋,还是思想?

往往,我们看不进去大段大段的逻辑。深刻的哲理,往往短而精悍,一阵见血。问:产品经理挺漂亮的,有点心动,但不知道合不合得来。男生更看重女生的身材脸蛋,还是...

程序员为什么千万不要瞎努力?

本文作者用对比非常鲜明的两个开发团队的故事,讲解了敏捷开发之道 —— 如果你的团队缺乏统一标准的环境,那么即使勤劳努力,不仅会极其耗时而且成果甚微,使用...

为什么程序员做外包会被瞧不起?

二哥,有个事想询问下您的意见,您觉得应届生值得去外包吗?公司虽然挺大的,中xx,但待遇感觉挺低,马上要报到,挺纠结的。

立即提问
相关内容推荐