Java URLConnection의 사용자 에이전트 설정
URLConnection과 함께 Java를 사용하여 웹 페이지를 구문 분석하려고합니다. 다음과 같이 사용자 에이전트를 설정하려고합니다.
java.net.URLConnection c = url.openConnection();
c.setRequestProperty("User-Agent", "Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.4; en-US; rv:1.9.2.2) Gecko/20100316 Firefox/3.6.2");
그러나 결과 사용자 에이전트는 끝에 "Java / 1.5.0_19"가 추가 된 내가 지정한 것입니다. 이 추가없이 진정으로 사용자 에이전트를 설정하는 방법이 있습니까?
손으로 http.agent
시스템 속성을로 설정하면 ""
트릭을 수행 할 수 있습니다 (제 앞에 코드가 없습니다).
다음과 같이 벗어날 수 있습니다.
System.setProperty("http.agent", "");
하지만 시작시 값을 캐시하는 경우 사용자와 URL 프로토콜 처리기 초기화 사이에 경쟁이 필요할 수 있습니다 (실제로는 그렇게 생각하지 않습니다).
이 속성은 JNLP 파일 (6u10의 애플릿에서 사용 가능) 및 명령 줄을 통해 설정할 수도 있습니다.
-Dhttp.agent=
또는 래퍼 명령의 경우 :
-J-Dhttp.agent=
설명을 위해 : setRequestProperty("User-Agent", "Mozilla ...")
이제 잘 작동 java/xx
하며 끝에 추가되지 않습니다 ! 적어도 Java 1.6.30 이상에서는.
netcat (포트 리스너)를 사용하여 내 컴퓨터에서 수신했습니다.
$ nc -l -p 8080
단순히 포트에서 수신 대기하므로 원시 http-headers와 같이 요청 된 모든 것을 볼 수 있습니다.
그리고 setRequestProperty없이 다음과 같은 http-headers를 얻었습니다.
GET /foobar HTTP/1.1
User-Agent: Java/1.6.0_30
Host: localhost:8080
Accept: text/html, image/gif, image/jpeg, *; q=.2, */*; q=.2
Connection: keep-alive
그리고 setRequestProperty :
GET /foobar HTTP/1.1
User-Agent: Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.4; en-US; rv:1.9.2.2) Gecko/20100316 Firefox/3.6.2
Host: localhost:8080
Accept: text/html, image/gif, image/jpeg, *; q=.2, */*; q=.2
Connection: keep-alive
보시다시피 사용자 에이전트가 올바르게 설정되었습니다.
전체 예 :
import java.io.IOException;
import java.net.URL;
import java.net.URLConnection;
public class TestUrlOpener {
public static void main(String[] args) throws IOException {
URL url = new URL("http://localhost:8080/foobar");
URLConnection hc = url.openConnection();
hc.setRequestProperty("User-Agent", "Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.4; en-US; rv:1.9.2.2) Gecko/20100316 Firefox/3.6.2");
System.out.println(hc.getContentType());
}
}
나를 위해 그 작업 은 addRequestProperty에서 User-Agent를 설정합니다.
URL url = new URL(<URL>);
HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
httpConn.addRequestProperty("User-Agent","Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:56.0) Gecko/20100101 Firefox/56.0");
HTTP 서버는 오래된 브라우저와 시스템을 거부하는 경향이 있습니다.
The page Tech Blog (wh): Most Common User Agents reflects the user-agent property of your current browser in section "Your user agent is:", which can be applied to set the request property "User-Agent" of a java.net.URLConnection
or the system property "http.agent".
참고URL : https://stackoverflow.com/questions/2529682/setting-user-agent-of-a-java-urlconnection
'Development Tip' 카테고리의 다른 글
모든 리전에서 실행중인 모든 Amazon EC2 인스턴스를 보려면 어떻게해야합니까? (0) | 2020.10.23 |
---|---|
const 참조 매개 변수 (0) | 2020.10.23 |
MySQL WHERE : "! ="또는 "같지 않음"을 작성하는 방법은 무엇입니까? (0) | 2020.10.23 |
기간을 int milli 및 float 초로 가져 오는 방법 (0) | 2020.10.23 |
AngularJS로 URL 인코딩 앵커 링크를 생성하는 방법은 무엇입니까? (0) | 2020.10.23 |