java.net.URLConnection在这里经常询问使用情况,Oracle教程对此非常简洁.
该教程基本上只显示了如何触发GET请求并读取响应.它没有解释如何使用它来执行POST请求,设置请求标头,读取响应标头,处理cookie,提交HTML表单,上传文件等.
那么,我如何使用java.net.URLConnection触发和处理"高级"HTTP请求?
我试图改进Java Html文档一点点,但我遇到了问题HttpUrlConntion.有一点是,如果用户代理是Java VM,某些服务器会阻止请求.另一个问题是HttpUrlConnection没有设置Referrer或Location头字段.由于几个站点使用这些字段来验证内容是从他们自己的站点访问的,因此我也被阻止了.据我所知,唯一的解决方案是替换HTTP协议的URL处理程序.或者有没有办法修改默认的HTTP Handler?
我的代码是这样的:
URL url;
URLConnection uc;
StringBuilder parsedContentFromUrl = new StringBuilder();
String urlString="http://www.example.com/content/w2e4dhy3kxya1v0d/";
System.out.println("Getting content for URl : " + urlString);
url = new URL(urlString);
uc = url.openConnection();
uc.connect();
uc.getInputStream();
BufferedInputStream in = new BufferedInputStream(uc.getInputStream());
int ch;
while ((ch = in.read()) != -1) {
parsedContentFromUrl.append((char) ch);
}
System.out.println(parsedContentFromUrl);
Run Code Online (Sandbox Code Playgroud)
但是,当我尝试通过浏览器访问URL时没有问题,但是当我尝试通过java程序访问它时,它会抛出预期:
java.io.IOException: Server returned HTTP response code: 403 for URL
Run Code Online (Sandbox Code Playgroud)
解决办法是什么?
我试图获取数据,但总是让403(Forbidden)与RestTemplate.
但是当我尝试时org.apache.http.client.HttpClient,一切都很好.我也可以在我的机器上使用Postman获取数据.
代码很简单但我不知道什么是错的.
public Object get() {
try {
RestTemplate restTemplate = new RestTemplate();
Object result = restTemplate.getForObject("https://api.hearthstonejson.com/v1/19776/enUS/cards.json", Object.class);
return result;
} catch (Exception ex) {
logger.error(ex.getMessage(), ex);
return null;
}
}
Run Code Online (Sandbox Code Playgroud)
编辑:附加堆栈跟踪
org.springframework.web.client.HttpClientErrorException: 403 Forbidden
at org.springframework.web.client.DefaultResponseErrorHandler.handleError(DefaultResponseErrorHandler.java:63)
at org.springframework.web.client.RestTemplate.handleResponse(RestTemplate.java:700)
at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:653)
at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:613)
at org.springframework.web.client.RestTemplate.getForObject(RestTemplate.java:287)
at com.brawlstone.metaservice.service.SyncService.get(SyncService.java:49)
at com.brawlstone.metaservice.web.SyncController.getCards(SyncController.java:30)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:205)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:133)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:97)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:827)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:738)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:967) …Run Code Online (Sandbox Code Playgroud) 我正在尝试使用以下代码获取Google搜索结果:
Document doc = con.connect("http://www.google.com/search?q=lakshman").timeout(5000).get();
Run Code Online (Sandbox Code Playgroud)
但是我得到了这个例外:
org.jsoup.HttpStatusException: HTTP error fetching URL. Status=403,URL=http://www.google.com/search?q=lakshman
Run Code Online (Sandbox Code Playgroud)
403错误意味着服务器禁止访问,但我可以在Web浏览器中加载此URL.为什么Jsoup会收到403错误?
我想从网址打开一个链接:" http://www.kohls.com/search.jsp?search=jacket&submit-search=web-regular ",有时我得到:
java.io.IOException:服务器返回HTTP响应代码:403表示URL.但是使用浏览器打开网址时没关系.以下是我的代码的一部分:
URL url = new URL("http://www.kohls.com/search.jsp?search=jacket&submit-search=web-regular");
InputStream is = url.openConnection().getInputStream();
Run Code Online (Sandbox Code Playgroud)
错误细节
线程"main"中的异常java.io.IOException:服务器返回HTTP响应代码:403为URL:http://www.kohls.com/search.jsp? N = 0&search = jacket&WS = 96 at sun.net.www. Links.main上的protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1627)(Links.java:41)
我正在尝试制作一个在网格窗格中显示 4 个图像的简单程序。我在那里得到一个没问题,但是一旦我尝试添加第二个,我就遇到了一些问题。这是我的代码:
package sample;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.layout.GridPane;
import javafx.stage.Stage;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
public class Main extends Application {
@Override
public void start(Stage primaryStage) throws Exception{
GridPane gridPane = new GridPane();
gridPane.add(new ImageView(new Image ("http://gifimage.net/wp-content/uploads/2017/06/american-flag-gif-13.gif")), 1,1);
gridPane.add(new ImageView(new Image ("http://bestanimations.com/Flags/Asia/china/chinese-flag-waving-gif-animation-10.gif")), 2,2);
Scene scene = new Scene(gridPane, 1000, 500);
primaryStage.setTitle("Flags");
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
Application.launch(args);
}
}
Run Code Online (Sandbox Code Playgroud)
我认为这可能是图像后的行和列的问题,但我尝试了一些方法但没有成功。任何帮助是极大的赞赏。谢谢
尽管" https://jsonplaceholder.typicode.com/posts/1 "适用于邮递员,但禁止以下代码使用403
@ComponentScan
@EnableAutoConfiguration
public class Application {
public static void main(String[] args) {
RestTemplate rt = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
HttpEntity<String> entity = new HttpEntity<String>("parameters", headers);
String url = "https://jsonplaceholder.typicode.com/posts/1";
ResponseEntity<String> res = rt.exchange(url, HttpMethod.GET, entity, String.class);
System.out.println(res);
}
}
Run Code Online (Sandbox Code Playgroud)
错误:
23:28:21.447 [main] DEBUG o.s.web.client.RestTemplate - Created GET request for "https://jsonplaceholder.typicode.com/posts/1"
23:28:21.452 [main] DEBUG o.s.web.client.RestTemplate - Setting request Accept header to [text/plain, application/json, application/*+json, */*]
23:28:21.452 [main] DEBUG o.s.web.client.RestTemplate - Writing [parameters] using [org.springframework.http.converter.StringHttpMessageConverter@3234e239] …Run Code Online (Sandbox Code Playgroud) 我在 url 上与邮递员进行 api 调用:
https://cex.io/api/order_book/BTC/USD
Run Code Online (Sandbox Code Playgroud)
简单的 GET 没有标题没有参数没有什么。但与 java 相同:
RestTemplate rt = new RestTemplate();
rt.getForObject("https://cex.io/api/order_book/BTC/USD", String.class);
Run Code Online (Sandbox Code Playgroud)
让我 403. 问题出在哪里?
我正在尝试编写一个显示各种URL内容的简单程序。我的代码是这个。
import java.io.IOException;
import java.io.InputStream;
import java.net.*;
public class test {
public static void main(String[] args) {
URL url;
//String site ="ftp://ftp.suse.com/";
//String site ="http://www.google.ca";
//String site = "ftp://ftp.gnu.org/README";
String site = "ftp://metalab.unc.edu/";
try {
url = new URL(site);
InputStream stream = url.openStream();
for(int i = 0;i!= -1;i= stream.read()){
System.out.print((char)i);
}
stream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
Run Code Online (Sandbox Code Playgroud)
}
前3个资源都很好
但是最后一个
产生以下错误
java.net.ConnectException: Connection refused: connect
at java.net.DualStackPlainSocketImpl.connect0(Native Method) …Run Code Online (Sandbox Code Playgroud) 无法通过以下代码从 URL 访问此页面“kissanime.com”的内容(它不返回任何内容):
String a="http://kissanime.com";
url = new URL(a);
URLConnection conn = url.openConnection();
try ( // open the stream and put it into BufferedReader
BufferedReader br = new BufferedReader(
new InputStreamReader(conn.getInputStream()))) {
String inputLine;
while ((inputLine = br.readLine()) != null) {
System.out.println(inputLine);
}
}
Run Code Online (Sandbox Code Playgroud) java ×11
http ×3
resttemplate ×2
spring ×2
gridpane ×1
http-headers ×1
httprequest ×1
image ×1
ioexception ×1
javafx ×1
jsoup ×1
restful-url ×1
spring-boot ×1
url ×1