service api的demo实现,里面有java,php和python三种实现,打开一看,被python这类脚本语言所折服,单从代码量上来说,差别实在是太大,如果都是熟手开发,业务场景也正好适合该语言的话,开发效率自然就不用再说:
扣除掉注释之后:java 56行;php:30行;python:15行
package com.test.http;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.MessageDigest;
import java.math.BigInteger;
public class ApiDemo{
public static void sendRequest(String id, String secureKey) throws IOException{
URL request = new URL("xxxxxx?id="+id);
HttpURLConnection connection = (HttpURLConnection)request.openConnection();
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setRequestMethod("POST");
connection.setUseCaches(false);
connection.setInstanceFollowRedirects(true);
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.connect();
String scanParam = "{\"scanlist\":[{\"sid\":\"123\", \"url\":\"http://dl.test.com/test.apk\", \"md5\":\"3d41f29d762ec547bfa4b42f57f3dc7c\"}]}";
String authKey = getStringMd5(scanParam + id + secureKey);
String post = "authkey=" + authKey + "&request=" + scanParam;
DataOutputStream writeStream = new DataOutputStream(connection.getOutputStream());
writeStream.writeBytes(post);
writeStream.flush();
writeStream.close();
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line="";
while ((line = reader.readLine()) != null){
System.out.println(line);
}
reader.close();
connection.disconnect();
}
public static String getStringMd5(String src) {
MessageDigest md;
StringBuilder md5 = new StringBuilder();
try{
md = MessageDigest.getInstance("md5");
md.update(src.getBytes());
for (byte b : md.digest()) {
md5.append(String.format("%02x", b));
}
}
catch (Exception e) {
e.printStackTrace();
}
return md5.toString();
}
public static void main(String[] args) throws Exception {
try {
sendRequest("test", "123456");
} catch (IOException e) {
e.printStackTrace();
}
}
}
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) | 黑马程序员IT技术论坛 X3.2 |