java 如何模拟浏览器调用rest api接口 10
展开全部
package com.demo;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import javax.xml.bind.DatatypeConverter;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
public class restTest {
public static voidmain(String[] args) {
try {
DefaultHttpClient Client = newDefaultHttpClient();
HttpGet httpGet = newHttpGet("你的地址");
String encoding =DatatypeConverter.printBase64Binary("admin:admin".getBytes("UTF-8"));
httpGet.setHeader("Authorization", "Basic " +encoding);
HttpResponse response = Client.execute(httpGet);
System.out.println("response =" + response);
BufferedReader breader = newBufferedReader(new InputStreamReader(response.getEntity().getContent()));
StringBuilder responseString = newStringBuilder();
String line = "";
while ((line = breader.readLine()) !=null) {
responseString.append(line);
}
breader.close();
String repsonseStr =responseString.toString();
System.out.println("repsonseStr =" + repsonseStr);
} catch (IOException e) {
e.printStackTrace();
}
}
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询