java调用百度api生成短链接,跪求java代码,不要复制网上的,要自己亲测实际能运行的!谢谢
1个回答
展开全部
package com.zhidao.www;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class TestShort {
public static void main(String[] args) {
// TODO Auto-generated method stub
String httpUrl = "http://apis.baidu.com/3023/shorturl/shorten";
String httpArg = "url_long=http%3A%2F%2Fapistore.baidu.com%2Fastore%2Fshopready%2F1973.html";
String jsonResult = request(httpUrl, httpArg);
System.out.println(jsonResult);
}
/**
* @param urlAll
* :请求接口
* @param httpArg
* :参数
* @return 返回结果
*/
public static String request(String httpUrl, String httpArg) {
BufferedReader reader = null;
String result = null;
StringBuffer sbf = new StringBuffer();
httpUrl = httpUrl + "?" + httpArg;
try {
URL url = new URL(httpUrl);
HttpURLConnection connection = (HttpURLConnection) url
.openConnection();
connection.setRequestMethod("GET");
// 填入apikey到HTTP header
connection.setRequestProperty("apikey", "自己的apikey");
connection.connect();
InputStream is = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
String strRead = null;
while ((strRead = reader.readLine()) != null) {
sbf.append(strRead);
sbf.append("\拿首顷r\芹闹n");
}
reader.close();
result = sbf.toString();
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
}
这个可以用 不过要自己申请下api key 得到消陆的字符串也要自己解析
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class TestShort {
public static void main(String[] args) {
// TODO Auto-generated method stub
String httpUrl = "http://apis.baidu.com/3023/shorturl/shorten";
String httpArg = "url_long=http%3A%2F%2Fapistore.baidu.com%2Fastore%2Fshopready%2F1973.html";
String jsonResult = request(httpUrl, httpArg);
System.out.println(jsonResult);
}
/**
* @param urlAll
* :请求接口
* @param httpArg
* :参数
* @return 返回结果
*/
public static String request(String httpUrl, String httpArg) {
BufferedReader reader = null;
String result = null;
StringBuffer sbf = new StringBuffer();
httpUrl = httpUrl + "?" + httpArg;
try {
URL url = new URL(httpUrl);
HttpURLConnection connection = (HttpURLConnection) url
.openConnection();
connection.setRequestMethod("GET");
// 填入apikey到HTTP header
connection.setRequestProperty("apikey", "自己的apikey");
connection.connect();
InputStream is = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
String strRead = null;
while ((strRead = reader.readLine()) != null) {
sbf.append(strRead);
sbf.append("\拿首顷r\芹闹n");
}
reader.close();
result = sbf.toString();
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
}
这个可以用 不过要自己申请下api key 得到消陆的字符串也要自己解析
追问
谢谢您的回答!继续问下api key怎么申请啊!还有,得到的key字符串是如何解析的,可以举个例子吗,小弟对这块确实不熟,昨天搞了一天都没搞出来..如果弄成功到时候采纳你的答案再加100财富
本回答被提问者采纳
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询