Javapost推送网址到百度代码
时间: 2024-03-30 10:36:00 浏览: 66
以下是使用Java代码将网址推送到百度的示例:
```java
import java.net.HttpURLConnection;
import java.net.URL;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.HashMap;
import java.util.Map;
public class BaiduPusher {
public static void main(String[] args) {
String url = "http://data.zz.baidu.com/urls?site=your_website_url&token=your_push_token";
String[] urls = {"http://example.com/page1", "http://example.com/page2"};
Map<String, String[]> paramMap = new HashMap<>();
paramMap.put("urls", urls);
try {
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
// add request header
con.setRequestMethod("POST");
con.setRequestProperty("Content-Type", "text/plain");
// send post request
con.setDoOutput(true);
OutputStreamWriter writer = new OutputStreamWriter(con.getOutputStream());
writer.write(buildUrlParamString(paramMap));
writer.flush();
writer.close();
int responseCode = con.getResponseCode();
System.out.println("Response Code : " + responseCode);
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
// print result
System.out.println(response.toString());
} catch (Exception e) {
e.printStackTrace();
}
}
private static String buildUrlParamString(Map<String, String[]> paramMap) {
StringBuilder paramStringBuilder = new StringBuilder();
for (Map.Entry<String, String[]> entry : paramMap.entrySet()) {
String key = entry.getKey();
for (String value : entry.getValue()) {
paramStringBuilder.append(key).append('=').append(value).append('&');
}
}
String paramString = paramStringBuilder.toString();
return paramString.substring(0, paramString.length() - 1); // remove last '&'
}
}
```
其中,`your_website_url`和`your_push_token`需要替换为您在百度站长平台中设置的网站链接和推送用的准入密钥。
上述代码中使用了`HttpURLConnection`来发送POST请求,将网址提交到百度站长平台。将要提交的网址放在一个字符串数组中,然后将这个数组放到一个Map中,再通过`buildUrlParamString`方法将Map转换为URL格式的参数字符串。最后将参数字符串写入HTTP请求的正文中,发送POST请求即可。
阅读全文